@isdk/ai-tool 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.cn.md +103 -237
- package/README.md +101 -186
- package/dist/chunk-4XRPAC7C.mjs +1 -0
- package/dist/chunk-VIG2GB47.mjs +1 -1
- package/dist/funcs.d.mts +1 -1
- package/dist/funcs.d.ts +1 -1
- package/dist/funcs.js +1 -1
- package/dist/funcs.mjs +1 -1
- package/dist/index-DEUnmyUq.d.mts +1792 -0
- package/dist/index-DEUnmyUq.d.ts +1792 -0
- package/dist/index.d.mts +1068 -9
- package/dist/index.d.ts +1068 -9
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/test/util.js +1 -1
- package/docs/api/README.md +165 -0
- package/docs/{_media → api/_media}/CONTRIBUTING.md +3 -3
- package/docs/api/_media/pubsub.md +326 -0
- package/docs/api/_media/server_client_tools.md +88 -0
- package/docs/api/_media/toolFunc.md +183 -0
- package/docs/api/_media/transport.md +137 -0
- package/docs/{classes → api/classes}/AbortError.md +139 -54
- package/docs/api/classes/AlreadyExistsError.md +431 -0
- package/docs/api/classes/BaseError.md +440 -0
- package/docs/{classes → api/classes}/BinarySemaphore.md +25 -25
- package/docs/{classes → api/classes}/CancelableAbility.md +25 -25
- package/docs/api/classes/ClientToolTransport.md +310 -0
- package/docs/{classes → api/classes}/ClientTools.md +646 -180
- package/docs/{classes → api/classes}/CommonError.md +139 -54
- package/docs/{classes → api/classes}/ConfigFile.md +54 -5
- package/docs/{classes → api/classes}/EnvPromptTemplate.md +94 -48
- package/docs/{classes → api/classes}/EventClient.md +742 -234
- package/docs/{classes → api/classes}/EventEmitter.md +12 -12
- package/docs/{classes → api/classes}/EventServer.md +670 -209
- package/docs/{classes → api/classes}/EventToolFunc.md +561 -109
- package/docs/{classes → api/classes}/FStringPromptTemplate.md +94 -48
- package/docs/{classes → api/classes}/FewShotPromptTemplate.md +100 -52
- package/docs/{classes → api/classes}/GolangPromptTemplate.md +99 -53
- package/docs/api/classes/HttpClientToolTransport.md +324 -0
- package/docs/api/classes/HttpServerToolTransport.md +332 -0
- package/docs/{classes → api/classes}/IntSet.md +12 -12
- package/docs/{classes → api/classes}/LRUCache.md +26 -26
- package/docs/api/classes/NotFoundError.md +431 -0
- package/docs/api/classes/NotImplementationError.md +431 -0
- package/docs/{classes → api/classes}/PromptExampleSelector.md +9 -9
- package/docs/{classes → api/classes}/PromptTemplate.md +91 -47
- package/docs/api/classes/ReadableStreamError.md +451 -0
- package/docs/api/classes/ResClientTools.md +3365 -0
- package/docs/api/classes/ResServerTools.md +3342 -0
- package/docs/api/classes/RpcMethodsClientTool.md +3275 -0
- package/docs/api/classes/RpcMethodsServerTool.md +3224 -0
- package/docs/api/classes/SSEChannel.md +272 -0
- package/docs/{classes → api/classes}/Semaphore.md +26 -26
- package/docs/api/classes/ServerToolTransport.md +323 -0
- package/docs/{classes → api/classes}/ServerTools.md +583 -120
- package/docs/{classes → api/classes}/SignalGate.md +9 -9
- package/docs/api/classes/SseClientPubSubTransport.md +92 -0
- package/docs/api/classes/SseServerPubSubTransport.md +234 -0
- package/docs/{classes → api/classes}/TaskAbortController.md +9 -9
- package/docs/api/classes/ToolFunc.md +2665 -0
- package/docs/api/classes/ToolTransport.md +143 -0
- package/docs/api/classes/YamlTypeBaseObject.md +31 -0
- package/docs/api/enumerations/AsyncFeatureBits.md +33 -0
- package/docs/api/enumerations/AsyncFeatures.md +33 -0
- package/docs/api/enumerations/ErrorCode.md +177 -0
- package/docs/api/enumerations/HashAlgorithm.md +97 -0
- package/docs/{functions → api/functions}/AIArgProcessor.md +1 -1
- package/docs/{functions → api/functions}/AIStream.md +1 -1
- package/docs/{functions → api/functions}/ChoiceArgProcessor.md +1 -1
- package/docs/api/functions/DefaultDateFormat.md +21 -0
- package/docs/{functions → api/functions}/ObjectArgsToArgsInfo.md +1 -1
- package/docs/{functions → api/functions}/RateLimit.md +1 -1
- package/docs/{functions → api/functions}/TemplateArgProcessor.md +1 -1
- package/docs/api/functions/addDate.md +71 -0
- package/docs/{functions → api/functions}/assignDirs.md +1 -1
- package/docs/{functions → api/functions}/backendEventable.md +1 -1
- package/docs/{functions → api/functions}/beforeShutdown.md +1 -1
- package/docs/api/functions/calcPerplexity.md +60 -0
- package/docs/api/functions/calcPerplexitySimple.md +42 -0
- package/docs/api/functions/canonicalize.md +33 -0
- package/docs/{functions → api/functions}/completeSentences.md +1 -1
- package/docs/{functions → api/functions}/concatText.md +1 -1
- package/docs/{functions → api/functions}/countLLMTokens.md +1 -1
- package/docs/{functions → api/functions}/countRegexMatches.md +1 -1
- package/docs/{functions → api/functions}/createAbilityInjector.md +4 -4
- package/docs/{functions → api/functions}/createCallbacksTransformer.md +1 -1
- package/docs/{functions → api/functions}/createEmptyReadableStream.md +1 -1
- package/docs/{functions → api/functions}/createEndWithRepetitionDetector.md +1 -1
- package/docs/{functions → api/functions}/createError.md +1 -1
- package/docs/{functions → api/functions}/createEventStreamTransformer.md +1 -1
- package/docs/{functions → api/functions}/createHfValueFunc.md +1 -1
- package/docs/{functions → api/functions}/createLRUCache.md +1 -1
- package/docs/{functions → api/functions}/createYamlObjectTag.md +1 -1
- package/docs/{functions → api/functions}/dateToText.md +1 -1
- package/docs/{functions → api/functions}/decodeCharset.md +1 -1
- package/docs/api/functions/defaultsWithConcat.md +74 -0
- package/docs/{functions → api/functions}/detectCharset.md +1 -1
- package/docs/{functions → api/functions}/encodeLLMTokens.md +1 -1
- package/docs/{functions → api/functions}/ensureQuoted.md +1 -1
- package/docs/{functions → api/functions}/eventable.md +1 -1
- package/docs/{functions → api/functions}/expandConfig.md +1 -1
- package/docs/{functions → api/functions}/expandEnv.md +1 -1
- package/docs/{functions → api/functions}/expandObjEnv.md +1 -1
- package/docs/{functions → api/functions}/expandPath.md +1 -1
- package/docs/api/functions/expandPathInObject.md +29 -0
- package/docs/api/functions/expandPaths.md +25 -0
- package/docs/{functions → api/functions}/extNameLevel.md +1 -1
- package/docs/{functions → api/functions}/fileIsExists.md +1 -1
- package/docs/{functions → api/functions}/filterValidFnScope.md +1 -1
- package/docs/{functions → api/functions}/findIndexNonEmptyFrom.md +1 -1
- package/docs/{functions → api/functions}/findPort.md +1 -1
- package/docs/{functions → api/functions}/formatISO.md +1 -1
- package/docs/{functions → api/functions}/formatTextWithSpace.md +1 -1
- package/docs/api/functions/funcGetMeta.md +27 -0
- package/docs/api/functions/funcWithMeta.md +41 -0
- package/docs/api/functions/genUrlParamsStr.md +27 -0
- package/docs/{functions → api/functions}/getAllEnumKeys.md +1 -1
- package/docs/{functions → api/functions}/getConfigFileNames.md +1 -1
- package/docs/{functions → api/functions}/getConfigs.md +1 -1
- package/docs/{functions → api/functions}/getEnvVairables.md +1 -1
- package/docs/{functions → api/functions}/getFileMetaInfo.md +1 -1
- package/docs/{functions → api/functions}/getHashAlgoBySize.md +1 -1
- package/docs/{functions → api/functions}/getKeysPath.md +1 -1
- package/docs/{functions → api/functions}/getLLMTokenizer.md +1 -1
- package/docs/{functions → api/functions}/getMultiLevelExtname.md +1 -1
- package/docs/{functions → api/functions}/getPackageDir.md +1 -1
- package/docs/{functions → api/functions}/getRealFilepath.md +1 -1
- package/docs/{functions → api/functions}/getResponseErrorReadableStream.md +1 -1
- package/docs/{functions → api/functions}/getXDGConfigs.md +1 -1
- package/docs/{functions → api/functions}/hasDirectoryIn.md +1 -1
- package/docs/{functions → api/functions}/hash.md +1 -1
- package/docs/{functions → api/functions}/hashFile.md +1 -1
- package/docs/api/functions/hashObject.md +25 -0
- package/docs/{functions → api/functions}/hashStream.md +1 -1
- package/docs/api/functions/initShutdown.md +15 -0
- package/docs/{functions → api/functions}/isLangUsingSpaces.md +1 -1
- package/docs/{functions → api/functions}/isListItemString.md +1 -1
- package/docs/{functions → api/functions}/isModelNameMatched.md +1 -1
- package/docs/{functions → api/functions}/isPunctuationChar.md +1 -1
- package/docs/{functions → api/functions}/isQuoted.md +1 -1
- package/docs/{functions → api/functions}/isRegExp.md +1 -1
- package/docs/{functions → api/functions}/isSameString.md +1 -1
- package/docs/{functions → api/functions}/isSectionString.md +1 -1
- package/docs/{functions → api/functions}/isSentenceEnding.md +1 -1
- package/docs/{functions → api/functions}/isSepLineString.md +1 -1
- package/docs/{functions → api/functions}/isStrWrapped.md +1 -1
- package/docs/{functions → api/functions}/isSubdirectory.md +2 -2
- package/docs/{functions → api/functions}/isTitleString.md +1 -1
- package/docs/{functions → api/functions}/isValidFilename.md +1 -1
- package/docs/{functions → api/functions}/isValidFilepath.md +1 -1
- package/docs/{functions → api/functions}/isWebStream.md +1 -1
- package/docs/api/functions/joinSplitWords.md +46 -0
- package/docs/{functions → api/functions}/jsonFilterToWhere.md +1 -1
- package/docs/{functions → api/functions}/jsonToMarkdownStr.md +9 -1
- package/docs/{functions → api/functions}/loadAIConfig.md +1 -1
- package/docs/{functions → api/functions}/loadConfig.md +1 -1
- package/docs/{functions → api/functions}/loadConfigFile.md +1 -1
- package/docs/{functions → api/functions}/loadFileFromPaths.md +1 -1
- package/docs/{functions → api/functions}/loadTextFromPaths.md +1 -1
- package/docs/{functions → api/functions}/lrucache.md +1 -1
- package/docs/{functions → api/functions}/makeToolFuncCancelable.md +1 -1
- package/docs/{functions → api/functions}/matchUrlProtocol.md +1 -1
- package/docs/{functions → api/functions}/memoize.md +1 -1
- package/docs/api/functions/mergeArray.md +57 -0
- package/docs/{functions → api/functions}/messagesToText.md +1 -1
- package/docs/api/functions/normalizePath.md +21 -0
- package/docs/{functions → api/functions}/paramsSizeToScaleStr.md +1 -1
- package/docs/{functions → api/functions}/parseCommand.md +1 -1
- package/docs/{functions → api/functions}/parseDateFormat.md +1 -1
- package/docs/{functions → api/functions}/parseISO.md +1 -1
- package/docs/{functions → api/functions}/parseJsJson.md +1 -1
- package/docs/{functions → api/functions}/parseJsJsonSimpleSync.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArgInfo.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArgumentInfos.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArguments.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArgumentsAsArgInfos.md +1 -1
- package/docs/{functions → api/functions}/parseYaml.md +1 -1
- package/docs/api/functions/pruneSubdirectories.md +35 -0
- package/docs/api/functions/pruneSubdirectoriesInPlace.md +38 -0
- package/docs/{functions → api/functions}/quoteStr.md +1 -1
- package/docs/{functions → api/functions}/readFilenamesRecursiveSync.md +1 -1
- package/docs/{functions → api/functions}/readTextFileChunks.md +1 -1
- package/docs/{functions → api/functions}/readTextFileChunksEx.md +1 -1
- package/docs/{functions → api/functions}/readableFromAsyncIterable.md +1 -1
- package/docs/{functions → api/functions}/registerCoreTools.md +1 -1
- package/docs/{functions → api/functions}/registerYamlTag.md +1 -1
- package/docs/{functions → api/functions}/removeMarkdownBold.md +1 -1
- package/docs/{functions → api/functions}/removeMarkdownBoldAndItalic.md +1 -1
- package/docs/{functions → api/functions}/removeMarkdownItalic.md +1 -1
- package/docs/{functions → api/functions}/replaceWithPlaceholder.md +1 -1
- package/docs/{functions → api/functions}/restoreFromPlacehoders.md +1 -1
- package/docs/{functions → api/functions}/sanitizeFilename.md +1 -1
- package/docs/{functions → api/functions}/sanitizeFilepath.md +1 -1
- package/docs/{functions → api/functions}/saveConfigFile.md +1 -1
- package/docs/{functions → api/functions}/scaleStrToParamsSize.md +1 -1
- package/docs/{functions → api/functions}/shutdown.md +1 -1
- package/docs/{functions → api/functions}/simplifyObjectArguments.md +1 -1
- package/docs/api/functions/sleep.md +36 -0
- package/docs/{functions → api/functions}/sortedValues.md +1 -1
- package/docs/{functions → api/functions}/splitChunks.md +1 -1
- package/docs/{functions → api/functions}/splitParagraph.md +1 -1
- package/docs/{functions → api/functions}/splitSentence.md +1 -1
- package/docs/api/functions/splitWords.md +42 -0
- package/docs/{functions → api/functions}/stringifyYaml.md +1 -1
- package/docs/{functions → api/functions}/stripConsoleColor.md +1 -1
- package/docs/{functions → api/functions}/textToDate.md +1 -1
- package/docs/{functions → api/functions}/throwError.md +3 -3
- package/docs/{functions → api/functions}/toDate.md +1 -1
- package/docs/{functions → api/functions}/toDateTime.md +1 -1
- package/docs/{functions → api/functions}/toRegExp.md +1 -1
- package/docs/{functions → api/functions}/trimStartOfStreamHelper.md +1 -1
- package/docs/{functions → api/functions}/truncTo.md +1 -1
- package/docs/{functions → api/functions}/truncateByToken.md +1 -1
- package/docs/{functions → api/functions}/truncateToTokenLimit.md +1 -1
- package/docs/{functions → api/functions}/truncateToTokenLimitEx.md +1 -1
- package/docs/{functions → api/functions}/uuid.md +1 -1
- package/docs/{functions → api/functions}/uuidParse.md +1 -1
- package/docs/{functions → api/functions}/uuidStringify.md +1 -1
- package/docs/{functions → api/functions}/uuidValidate.md +1 -1
- package/docs/{functions → api/functions}/uuidVersion.md +1 -1
- package/docs/{functions → api/functions}/uuidv1.md +9 -5
- package/docs/{functions → api/functions}/uuidv4.md +9 -5
- package/docs/{functions → api/functions}/uuidv5.md +9 -5
- package/docs/api/functions/wait.md +45 -0
- package/docs/{functions → api/functions}/wrapEventEmitter.md +1 -1
- package/docs/{functions → api/functions}/xxhash.md +1 -1
- package/docs/{functions → api/functions}/xxhash32.md +1 -1
- package/docs/{functions → api/functions}/xxhash64.md +1 -1
- package/docs/{functions → api/functions}/xxhashAsStr.md +1 -1
- package/docs/api/functions/yieldExec.md +27 -0
- package/docs/{globals.md → api/globals.md} +50 -1
- package/docs/api/interfaces/AIChatAssistantMessageParam.md +129 -0
- package/docs/api/interfaces/AIChatContentPartImage.md +29 -0
- package/docs/api/interfaces/AIChatContentPartText.md +25 -0
- package/docs/api/interfaces/AIChatMessageParamBase.md +68 -0
- package/docs/api/interfaces/AIChatMessageToolCall.md +41 -0
- package/docs/{interfaces → api/interfaces}/AIChatSystemMessageParam.md +9 -9
- package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +37 -0
- package/docs/api/interfaces/AIChatToolChoiceObject.md +25 -0
- package/docs/api/interfaces/AIChatToolFunc.md +41 -0
- package/docs/api/interfaces/AIChatToolFuncParam.md +37 -0
- package/docs/api/interfaces/AIChatToolMessageParam.md +113 -0
- package/docs/api/interfaces/AIChatToolParam.md +25 -0
- package/docs/api/interfaces/AIChatToolTypeObject.md +17 -0
- package/docs/api/interfaces/AIChatUserMessageParam.md +137 -0
- package/docs/api/interfaces/AIChoiceConfig.md +65 -0
- package/docs/api/interfaces/AIResult.md +65 -0
- package/docs/{interfaces → api/interfaces}/AIStreamParser.md +2 -2
- package/docs/api/interfaces/AIStreamParserOptions.md +21 -0
- package/docs/api/interfaces/BaseFunc.md +299 -0
- package/docs/api/interfaces/BaseFuncItem.md +221 -0
- package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +25 -0
- package/docs/api/interfaces/BinarySemaphoreOptions.md +57 -0
- package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +25 -0
- package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +37 -0
- package/docs/api/interfaces/CancelableAbilityOptions.md +113 -0
- package/docs/api/interfaces/ClientFuncItem.md +326 -0
- package/docs/api/interfaces/EventClientFuncParams.md +51 -0
- package/docs/api/interfaces/EventServerFuncParams.md +73 -0
- package/docs/{interfaces → api/interfaces}/FewShotPromptTemplateOptions.md +24 -12
- package/docs/api/interfaces/FuncItem.md +281 -0
- package/docs/api/interfaces/FuncParam.md +51 -0
- package/docs/api/interfaces/FuncParams.md +28 -0
- package/docs/api/interfaces/Funcs.md +15 -0
- package/docs/api/interfaces/HashAlgoParams.md +33 -0
- package/docs/api/interfaces/IClientToolTransport.md +155 -0
- package/docs/api/interfaces/IFileMetaInfo.md +65 -0
- package/docs/api/interfaces/IPubSubClientTransport.md +70 -0
- package/docs/api/interfaces/IPubSubServerTransport.md +241 -0
- package/docs/api/interfaces/IReadTextFileChunksOptions.md +143 -0
- package/docs/api/interfaces/IServerToolTransport.md +159 -0
- package/docs/api/interfaces/IToolTransport.md +73 -0
- package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +99 -0
- package/docs/api/interfaces/JsonFilter.md +13 -0
- package/docs/api/interfaces/ParseObjectArgumentOptions.md +89 -0
- package/docs/api/interfaces/ProbabilityItem.md +41 -0
- package/docs/api/interfaces/PromptExampleSelectorOptions.md +34 -0
- package/docs/{interfaces → api/interfaces}/PromptTemplateOptions.md +15 -7
- package/docs/api/interfaces/PubSubClient.md +27 -0
- package/docs/api/interfaces/PubSubClientStream.md +196 -0
- package/docs/api/interfaces/PubSubServerSession.md +103 -0
- package/docs/api/interfaces/RemoteFuncItem.md +316 -0
- package/docs/api/interfaces/ReplacePlacehoderOptions.md +41 -0
- package/docs/api/interfaces/ResClientFuncParams.md +37 -0
- package/docs/api/interfaces/ResServerFuncParams.md +77 -0
- package/docs/api/interfaces/RpcMethodsClientFuncParams.md +25 -0
- package/docs/api/interfaces/RpcMethodsServerFuncParams.md +61 -0
- package/docs/api/interfaces/SanitizeFilenameOptions.md +25 -0
- package/docs/api/interfaces/SectionStringOptions.md +25 -0
- package/docs/api/interfaces/SemaphoreOptions.md +89 -0
- package/docs/api/interfaces/SemaphoreTaskItem.md +73 -0
- package/docs/api/interfaces/ServerFuncItem.md +339 -0
- package/docs/api/interfaces/ServerFuncParams.md +42 -0
- package/docs/api/interfaces/SplitSentenceOptions.md +41 -0
- package/docs/{interfaces → api/interfaces}/StreamCallbacksAndOptions.md +5 -5
- package/docs/{interfaces → api/interfaces}/TaskAbortControllers.md +1 -1
- package/docs/{interfaces → api/interfaces}/TaskPromise.md +6 -6
- package/docs/api/interfaces/ToolFuncPackage.md +57 -0
- package/docs/{namespaces → api/namespaces}/EventStates/variables/ABORT.md +1 -1
- package/docs/{namespaces → api/namespaces}/EventStates/variables/CONTINUE.md +1 -1
- package/docs/{namespaces → api/namespaces}/EventStates/variables/DONE.md +1 -1
- package/docs/{namespaces → api/namespaces}/EventStates/variables/STOPPED.md +1 -1
- package/docs/{namespaces → api/namespaces}/uuidv5/variables/DNS.md +1 -1
- package/docs/{namespaces → api/namespaces}/uuidv5/variables/URL.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatContentPart.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatMessageParam.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatRole.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatToolChoiceParam.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIMessageType.md +1 -1
- package/docs/api/type-aliases/AIModelNameRule.md +14 -0
- package/docs/api/type-aliases/AIModelNameRuleFn.md +28 -0
- package/docs/api/type-aliases/AIModelNameRules.md +13 -0
- package/docs/{type-aliases → api/type-aliases}/AITextGenerationFinishReason.md +1 -1
- package/docs/api/type-aliases/ActionName.md +13 -0
- package/docs/api/type-aliases/ArrayMergeWay.md +11 -0
- package/docs/api/type-aliases/AsyncTaskId.md +11 -0
- package/docs/{type-aliases → api/type-aliases}/BeforeShutdownListener.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/EventErrorListenerFn.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/EventListenerFn.md +1 -1
- package/docs/api/type-aliases/FuncParamType.md +13 -0
- package/docs/{type-aliases → api/type-aliases}/PromptExamples.md +1 -1
- package/docs/api/type-aliases/PubSubClientId.md +14 -0
- package/docs/api/type-aliases/PubSubCtx.md +37 -0
- package/docs/api/type-aliases/RpcMethodHandler.md +34 -0
- package/docs/{type-aliases → api/type-aliases}/SemaphoreIsReadyFuncType.md +1 -1
- package/docs/api/type-aliases/TFunc.md +33 -0
- package/docs/{variables → api/variables}/AIChatRoles.md +1 -1
- package/docs/{variables → api/variables}/AIMessageTypes.md +1 -1
- package/docs/{variables → api/variables}/AITextGenerationFinishReasons.md +1 -1
- package/docs/{variables → api/variables}/AbortErrorCode.md +1 -1
- package/docs/api/variables/ActionNames.md +13 -0
- package/docs/{variables → api/variables}/AlreadyExistsErrorCode.md +1 -1
- package/docs/api/variables/ArrayMergeWay.md +25 -0
- package/docs/api/variables/ArrayMergeWaySymbol.md +11 -0
- package/docs/api/variables/ClientToolFuncSchema.md +83 -0
- package/docs/{variables → api/variables}/DEFAULT_CONFIG_NAME.md +1 -1
- package/docs/{variables → api/variables}/DefaultAsyncSemaphoreCapacity.md +1 -1
- package/docs/api/variables/EventBusName.md +11 -0
- package/docs/api/variables/EventName.md +11 -0
- package/docs/{variables → api/variables}/FilenameReservedRegex.md +1 -1
- package/docs/api/variables/FuncMetaSymbol.md +15 -0
- package/docs/{variables → api/variables}/InternalErrorCode.md +1 -1
- package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES.md +1 -1
- package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES_MAP.md +1 -1
- package/docs/{variables → api/variables}/NotFoundErrorCode.md +1 -1
- package/docs/{variables → api/variables}/NotImplementedErrorCode.md +1 -1
- package/docs/api/variables/PASSING_SCORE.md +13 -0
- package/docs/api/variables/RStreamErrCode.md +11 -0
- package/docs/api/variables/RemoteToolFuncSchema.md +84 -0
- package/docs/api/variables/ResponseRStreamErrCode.md +11 -0
- package/docs/api/variables/RpcMethodsClientToolSchema.md +49 -0
- package/docs/api/variables/RpcMethodsServerToolSchema.md +21 -0
- package/docs/{variables → api/variables}/SHUTDOWN_SIGNALS.md +1 -1
- package/docs/{variables → api/variables}/SSEChannelAlreadyClosedErrCode.md +1 -1
- package/docs/api/variables/SecondaryCache.md +11 -0
- package/docs/api/variables/ServerToolFuncSchema.md +83 -0
- package/docs/api/variables/StrangeHumanName.md +11 -0
- package/docs/api/variables/ToolAsyncCancelableBit.md +11 -0
- package/docs/api/variables/ToolAsyncMultiTaskBit.md +11 -0
- package/docs/api/variables/ToolAsyncPriorityBit.md +11 -0
- package/docs/{variables → api/variables}/ToolFuncSchema.md +14 -1
- package/docs/{variables → api/variables}/WindowsReservedNameRegex.md +1 -1
- package/docs/api/variables/base32768.md +11 -0
- package/docs/{variables → api/variables}/defaultTemplateFormat.md +1 -1
- package/docs/api/variables/event.md +11 -0
- package/docs/api/variables/eventClient.md +11 -0
- package/docs/api/variables/eventServer.md +11 -0
- package/docs/api/variables/lrucache.md +11 -0
- package/docs/{variables → api/variables}/mimeType.md +1 -1
- package/docs/{variables → api/variables}/uuidNIL.md +1 -1
- package/docs/pubsub.md +326 -0
- package/docs/server_client_tools.md +88 -0
- package/docs/toolFunc.md +183 -0
- package/docs/transport.md +137 -0
- package/package.json +37 -39
- package/dist/chunk-OYDBRUZJ.mjs +0 -1
- package/dist/index-BkwhCK1q.d.mts +0 -899
- package/dist/index-BkwhCK1q.d.ts +0 -899
- package/docs/README.md +0 -250
- package/docs/classes/AlreadyExistsError.md +0 -346
- package/docs/classes/BaseError.md +0 -359
- package/docs/classes/NotFoundError.md +0 -346
- package/docs/classes/NotImplementationError.md +0 -346
- package/docs/classes/ReadableStreamError.md +0 -366
- package/docs/classes/ResClientTools.md +0 -2451
- package/docs/classes/ResServerTools.md +0 -2427
- package/docs/classes/SSEChannel.md +0 -270
- package/docs/classes/ToolFunc.md +0 -2201
- package/docs/classes/YamlTypeBaseObject.md +0 -31
- package/docs/enumerations/AsyncFeatureBits.md +0 -33
- package/docs/enumerations/AsyncFeatures.md +0 -33
- package/docs/enumerations/ErrorCode.md +0 -177
- package/docs/enumerations/HashAlgorithm.md +0 -97
- package/docs/functions/canonicalize.md +0 -21
- package/docs/functions/initShutdown.md +0 -15
- package/docs/functions/wait.md +0 -21
- package/docs/interfaces/AIChatAssistantMessageParam.md +0 -129
- package/docs/interfaces/AIChatContentPartImage.md +0 -29
- package/docs/interfaces/AIChatContentPartText.md +0 -25
- package/docs/interfaces/AIChatMessageParamBase.md +0 -68
- package/docs/interfaces/AIChatMessageToolCall.md +0 -41
- package/docs/interfaces/AIChatToolChoiceFuncObject.md +0 -37
- package/docs/interfaces/AIChatToolChoiceObject.md +0 -25
- package/docs/interfaces/AIChatToolFunc.md +0 -41
- package/docs/interfaces/AIChatToolFuncParam.md +0 -37
- package/docs/interfaces/AIChatToolMessageParam.md +0 -113
- package/docs/interfaces/AIChatToolParam.md +0 -25
- package/docs/interfaces/AIChatToolTypeObject.md +0 -17
- package/docs/interfaces/AIChatUserMessageParam.md +0 -137
- package/docs/interfaces/AIChoiceConfig.md +0 -65
- package/docs/interfaces/AIResult.md +0 -65
- package/docs/interfaces/AIStreamParserOptions.md +0 -21
- package/docs/interfaces/BaseFunc.md +0 -157
- package/docs/interfaces/BaseFuncItem.md +0 -101
- package/docs/interfaces/BinarySemaphoreAcquireOptions.md +0 -25
- package/docs/interfaces/BinarySemaphoreOptions.md +0 -57
- package/docs/interfaces/BinarySemaphoreReleaseOptions.md +0 -25
- package/docs/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
- package/docs/interfaces/CancelableAbilityOptions.md +0 -113
- package/docs/interfaces/ClientFuncItem.md +0 -175
- package/docs/interfaces/EventClientFuncParams.md +0 -51
- package/docs/interfaces/EventServerFuncParams.md +0 -67
- package/docs/interfaces/FuncItem.md +0 -143
- package/docs/interfaces/FuncParam.md +0 -61
- package/docs/interfaces/FuncParams.md +0 -13
- package/docs/interfaces/Funcs.md +0 -13
- package/docs/interfaces/HashAlgoParams.md +0 -33
- package/docs/interfaces/IFileMetaInfo.md +0 -65
- package/docs/interfaces/IReadTextFileChunksOptions.md +0 -143
- package/docs/interfaces/ITruncateToTokenLimitOptions.md +0 -99
- package/docs/interfaces/JsonFilter.md +0 -13
- package/docs/interfaces/ParseObjectArgumentOptions.md +0 -89
- package/docs/interfaces/PromptExampleSelectorOptions.md +0 -34
- package/docs/interfaces/RemoteFuncItem.md +0 -164
- package/docs/interfaces/ReplacePlacehoderOptions.md +0 -41
- package/docs/interfaces/ResClientFuncParams.md +0 -37
- package/docs/interfaces/ResServerFuncParams.md +0 -69
- package/docs/interfaces/SanitizeFilenameOptions.md +0 -25
- package/docs/interfaces/SectionStringOptions.md +0 -25
- package/docs/interfaces/SemaphoreOptions.md +0 -89
- package/docs/interfaces/SemaphoreTaskItem.md +0 -73
- package/docs/interfaces/ServerFuncItem.md +0 -183
- package/docs/interfaces/ServerFuncParams.md +0 -35
- package/docs/interfaces/SplitSentenceOptions.md +0 -41
- package/docs/interfaces/ToolFuncPackage.md +0 -47
- package/docs/type-aliases/AIModelNameRule.md +0 -11
- package/docs/type-aliases/AIModelNameRuleFn.md +0 -21
- package/docs/type-aliases/AIModelNameRules.md +0 -11
- package/docs/type-aliases/ActionName.md +0 -11
- package/docs/type-aliases/AsyncTaskId.md +0 -11
- package/docs/type-aliases/FuncParamType.md +0 -11
- package/docs/type-aliases/TFunc.md +0 -25
- package/docs/variables/ActionNames.md +0 -11
- package/docs/variables/ClientToolFuncSchema.md +0 -101
- package/docs/variables/EventBusName.md +0 -11
- package/docs/variables/EventName.md +0 -11
- package/docs/variables/PASSING_SCORE.md +0 -11
- package/docs/variables/RStreamErrCode.md +0 -11
- package/docs/variables/RemoteToolFuncSchema.md +0 -101
- package/docs/variables/ResponseRStreamErrCode.md +0 -11
- package/docs/variables/SecondaryCache.md +0 -11
- package/docs/variables/ServerToolFuncSchema.md +0 -101
- package/docs/variables/ToolAsyncCancelableBit.md +0 -11
- package/docs/variables/ToolAsyncMultiTaskBit.md +0 -11
- package/docs/variables/ToolAsyncPriorityBit.md +0 -11
- package/docs/variables/base32768.md +0 -11
- package/docs/variables/event.md +0 -11
- package/docs/variables/eventClient.md +0 -11
- package/docs/variables/eventServer.md +0 -11
- package/docs/variables/lrucache.md +0 -11
- /package/docs/{_media → api/_media}/LICENSE-MIT +0 -0
- /package/docs/{namespaces → api/namespaces}/EventStates/README.md +0 -0
- /package/docs/{namespaces → api/namespaces}/uuidv5/README.md +0 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# ToolFunc: Client-Server Communication
|
|
2
|
+
|
|
3
|
+
This guide provides a comprehensive overview of the `ai-tool` transport layer, a powerful system designed to facilitate communication between server-side functions and client-side applications. It enables seamless Remote Procedure Calls (RPC) by abstracting the underlying network protocol.
|
|
4
|
+
|
|
5
|
+
This system is composed of two main parts:
|
|
6
|
+
|
|
7
|
+
1. **Tools (`ServerTools`/`ClientTools`):** Classes that define the functions to be executed.
|
|
8
|
+
2. **The Transport Layer:** The underlying bridge that handles network communication.
|
|
9
|
+
|
|
10
|
+
**Prerequisite:** This document assumes you have a basic understanding of the `ToolFunc` framework. If not, please review the [`toolFunc.md`](./toolFunc.md) first.
|
|
11
|
+
|
|
12
|
+
## 1. `ServerTools`: Defining Backend Functions
|
|
13
|
+
|
|
14
|
+
`ServerTools` is the base class for any function you want to make available for remote clients. It extends `ToolFunc`, inheriting all its features, but is specifically designed to be discovered and executed via the transport layer.
|
|
15
|
+
|
|
16
|
+
Think of a `ServerTools` instance as a single, network-addressable endpoint for a specific function.
|
|
17
|
+
|
|
18
|
+
### Basic Example
|
|
19
|
+
|
|
20
|
+
Here is the most basic example of defining a server tool. Note that at this stage, it's just a definition; it can't be reached by a client until a transport is set up.
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { ServerTools } from '@isdk/ai-tool';
|
|
24
|
+
|
|
25
|
+
// Define a tool that can be called remotely
|
|
26
|
+
ServerTools.register({
|
|
27
|
+
name: 'getUserProfile',
|
|
28
|
+
description: 'Fetches a user profile by ID.',
|
|
29
|
+
params: { id: { type: 'string' } },
|
|
30
|
+
func: async ({ id }: { id: string }) => {
|
|
31
|
+
// In a real app, you'd fetch this from a database
|
|
32
|
+
return { id, name: 'Jane Doe', email: 'jane.doe@example.com' };
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## 2. The Transport Layer: Bridging Client and Server
|
|
38
|
+
|
|
39
|
+
The transport layer's primary purpose is to **decouple your tool's business logic from the network protocol**. It acts as a bridge, allowing a client to execute a function on a server as if it were a local method.
|
|
40
|
+
|
|
41
|
+
The transport layer makes `ServerTools` accessible over a network and allows `ClientTools` to call them.
|
|
42
|
+
|
|
43
|
+
- **The Server Transport (`IServerToolServerTransport`)**
|
|
44
|
+
- Its job is to listen for incoming network requests (e.g., over HTTP).
|
|
45
|
+
- It finds the correct registered `ServerTools` instance by its name.
|
|
46
|
+
- It executes the tool and sends the result back in a response.
|
|
47
|
+
|
|
48
|
+
- **The Client Transport (`IClientToolTransport`)**
|
|
49
|
+
- Its job is to connect to a server's `apiRoot`.
|
|
50
|
+
- It uses a `mount()` helper to fetch all available tool definitions from the server and automatically create local proxy `ClientTools` for them.
|
|
51
|
+
|
|
52
|
+
### End-to-End Transport Example
|
|
53
|
+
|
|
54
|
+
This example shows how to use the `Fastify` (server) and `HttpClient` (client) transports to bring the `getUserProfile` tool online.
|
|
55
|
+
|
|
56
|
+
**Server-Side Setup:**
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
// server.ts
|
|
60
|
+
import { ServerTools, FastifyServerToolTransport } from '@isdk/ai-tool';
|
|
61
|
+
|
|
62
|
+
// (Your ServerTools.register call from above)
|
|
63
|
+
|
|
64
|
+
// 1. Create a server transport instance.
|
|
65
|
+
const serverTransport = new FastifyServerToolTransport();
|
|
66
|
+
|
|
67
|
+
// 2. Mount the ServerTools class. The transport finds all registered tools
|
|
68
|
+
// and exposes them under the '/api' prefix.
|
|
69
|
+
serverTransport.mount(ServerTools, '/api');
|
|
70
|
+
|
|
71
|
+
// 3. Start the server.
|
|
72
|
+
serverTransport.start({ port: 3000 });
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Client-Side Setup:**
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
// client.ts
|
|
79
|
+
import { ClientTools, HttpClientToolTransport } from '@isdk/ai-tool';
|
|
80
|
+
|
|
81
|
+
async function main() {
|
|
82
|
+
const apiRoot = 'http://localhost:3000/api';
|
|
83
|
+
|
|
84
|
+
// 1. Create a client transport pointing to the server.
|
|
85
|
+
const clientTransport = new HttpClientToolTransport(apiRoot);
|
|
86
|
+
|
|
87
|
+
// 2. Mount ClientTools. This crucial step connects to the server,
|
|
88
|
+
// fetches the definitions for all available ServerTools (like 'getUserProfile'),
|
|
89
|
+
// and creates the local ClientTools proxies.
|
|
90
|
+
await clientTransport.mount(ClientTools);
|
|
91
|
+
|
|
92
|
+
// 3. Get the proxy tool and run it as if it were local.
|
|
93
|
+
const getUserProfile = ClientTools.get('getUserProfile');
|
|
94
|
+
const profile = await getUserProfile.run({ id: '123' });
|
|
95
|
+
|
|
96
|
+
console.log(profile);
|
|
97
|
+
}
|
|
98
|
+
main();
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## 3. Advanced Tool Types & Transport Interaction
|
|
102
|
+
|
|
103
|
+
The framework provides specialized subclasses of `ServerTools` for common API patterns. A key concept is that the **transport layer remains agnostic** to these types. It always just finds a tool by its name and executes its main `func`. The tool itself is responsible for any internal logic, like routing to sub-methods.
|
|
104
|
+
|
|
105
|
+
### `RpcMethodsServerTool`
|
|
106
|
+
|
|
107
|
+
This class allows you to group multiple related functions into a single tool, like methods on a class.
|
|
108
|
+
|
|
109
|
+
- **How it works:** You define methods in your class with a `$` prefix (e.g., `$add`, `$subtract`). The tool's main `func` acts as a dispatcher, using an `act` parameter from the client to call the correct internal method.
|
|
110
|
+
- **Transport Interaction:** The transport is unaware of this. It just calls the main `func` of the `calculator` tool. The tool's internal dispatcher does the rest.
|
|
111
|
+
|
|
112
|
+
**Example:**
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
// tools/CalculatorTool.ts
|
|
116
|
+
import { RpcMethodsServerTool } from '@isdk/ai-tool';
|
|
117
|
+
|
|
118
|
+
export class CalculatorTool extends RpcMethodsServerTool {
|
|
119
|
+
$add({ a, b }: { a: number, b: number }) { return a + b; }
|
|
120
|
+
$subtract({ a, b }: { a: number, b: number }) { return a - b; }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// server.ts - You would register this tool:
|
|
124
|
+
// new CalculatorTool('calculator').register();
|
|
125
|
+
|
|
126
|
+
// client.ts - The client-side proxy would have .add() and .subtract() methods:
|
|
127
|
+
// const sum = await calculator.add({ a: 10, b: 5 });
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### `ResServerTools`
|
|
131
|
+
|
|
132
|
+
This class extends `RpcMethodsServerTool` to provide a conventional, resource-oriented (CRUD) API.
|
|
133
|
+
|
|
134
|
+
- **How it works:** It maps standard method names like `get`, `list`, `post`, `put`, and `delete` to different HTTP verbs and URL patterns.
|
|
135
|
+
- **Transport Interaction:** Just like with `RpcMethodsServerTool`, the transport remains agnostic. For example, a `GET /api/myResource/123` request is routed by the `Fastify` transport to the `myResource` tool. The tool's internal logic then identifies the `GET` verb and the `id` parameter and calls its own `get()` method.
|
|
136
|
+
|
|
137
|
+
This architecture provides a clean, powerful, and extensible way to build and consume APIs, clearly separating your business logic from the complexities of network communication.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@isdk/ai-tool",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"author": "Riceball LEE <snowyu.lee@gmail.com>",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -22,63 +22,61 @@
|
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@isdk/common-error": "^0.
|
|
26
|
-
"@isdk/util": "^0.3.
|
|
27
|
-
"@
|
|
25
|
+
"@isdk/common-error": "^0.2.0",
|
|
26
|
+
"@isdk/util": "^0.3.2",
|
|
27
|
+
"@huggingface/transformers": "^3.7.2",
|
|
28
28
|
"abstract-error": "^2.0.0",
|
|
29
|
-
"base32768": "^
|
|
29
|
+
"base32768": "^5.0.0",
|
|
30
30
|
"custom-ability": "^2.0.1",
|
|
31
31
|
"custom-factory": "2.3.0",
|
|
32
32
|
"date-fns": "^4.1.0",
|
|
33
|
-
"events-ex": "^2.0
|
|
34
|
-
"eventsource-parser": "^3.0.
|
|
33
|
+
"events-ex": "^2.1.0",
|
|
34
|
+
"eventsource-parser": "^3.0.6",
|
|
35
35
|
"hash-wasm": "^4.12.0",
|
|
36
36
|
"jschardet": "^3.1.4",
|
|
37
|
-
"json-canonicalize": "^
|
|
38
|
-
"load-config-file": "2.
|
|
37
|
+
"json-canonicalize": "^2.0.0",
|
|
38
|
+
"load-config-file": "2.1.0",
|
|
39
39
|
"lodash-es": "^4.17.21",
|
|
40
40
|
"memoizee": "^0.4.17",
|
|
41
|
-
"mime-type": "^5.0.
|
|
42
|
-
"
|
|
43
|
-
"property-manager": "^
|
|
41
|
+
"mime-type": "^5.0.3",
|
|
42
|
+
"package-directory": "^8.1.0",
|
|
43
|
+
"property-manager": "^3.0.3",
|
|
44
44
|
"secondary-cache": "^2.0.1",
|
|
45
|
-
"secure-json-parse": "^
|
|
46
|
-
"util-ex": "2.
|
|
47
|
-
"uuid": "^11.0
|
|
45
|
+
"secure-json-parse": "^4.0.0",
|
|
46
|
+
"util-ex": "2.3.0",
|
|
47
|
+
"uuid": "^11.1.0",
|
|
48
48
|
"xxhashjs": "^0.2.2",
|
|
49
|
-
"yaml": "^2.
|
|
49
|
+
"yaml": "^2.8.1",
|
|
50
50
|
"yaml-types": "^0.4.0",
|
|
51
|
-
"zod": "^3.24.1",
|
|
52
|
-
"zod-to-json-schema": "^3.24.1",
|
|
53
51
|
"@isdk/detect-text-language": "0.1.2",
|
|
54
|
-
"@isdk/template-engines": "0.6.
|
|
52
|
+
"@isdk/template-engines": "0.6.5"
|
|
55
53
|
},
|
|
56
54
|
"devDependencies": {
|
|
57
|
-
"@antfu/eslint-config": "
|
|
55
|
+
"@antfu/eslint-config": "~4.10.1",
|
|
58
56
|
"@types/jest": "^29.5.14",
|
|
59
57
|
"@types/lodash-es": "^4.17.12",
|
|
60
|
-
"@types/memoizee": "^0.4.
|
|
61
|
-
"@types/node": "^
|
|
58
|
+
"@types/memoizee": "^0.4.12",
|
|
59
|
+
"@types/node": "^24.3.0",
|
|
62
60
|
"@types/uuid": "^10.0.0",
|
|
63
61
|
"@types/xxhashjs": "^0.2.4",
|
|
64
|
-
"@typescript-eslint/eslint-plugin": "
|
|
62
|
+
"@typescript-eslint/eslint-plugin": "~8.41.0",
|
|
65
63
|
"esbuild-plugin-wasm": "^1.1.0",
|
|
66
|
-
"eslint": "^9.
|
|
67
|
-
"eslint-config-prettier": "^
|
|
64
|
+
"eslint": "^9.34.0",
|
|
65
|
+
"eslint-config-prettier": "^10.1.8",
|
|
68
66
|
"eslint-plugin-tsdoc": "^0.4.0",
|
|
69
|
-
"eventsource": "^
|
|
70
|
-
"fastify": "^5.
|
|
71
|
-
"prettier": "^3.
|
|
72
|
-
"terser": "^5.
|
|
73
|
-
"tsup": "^8.
|
|
74
|
-
"tsx": "^4.
|
|
75
|
-
"type-fest": "^4.
|
|
67
|
+
"eventsource": "^4.0.0",
|
|
68
|
+
"fastify": "^5.5.0",
|
|
69
|
+
"prettier": "^3.6.2",
|
|
70
|
+
"terser": "^5.43.1",
|
|
71
|
+
"tsup": "^8.5.0",
|
|
72
|
+
"tsx": "^4.20.5",
|
|
73
|
+
"type-fest": "^4.41.0",
|
|
76
74
|
"typedoc": "^0.27.7",
|
|
77
75
|
"typedoc-plugin-markdown": "^4.4.2",
|
|
78
|
-
"typescript": "
|
|
79
|
-
"vite": "^
|
|
80
|
-
"vite-plugin-wasm": "^3.
|
|
81
|
-
"vitest": "^2.
|
|
76
|
+
"typescript": "~5.7.3",
|
|
77
|
+
"vite": "^7.1.4",
|
|
78
|
+
"vite-plugin-wasm": "^3.5.0",
|
|
79
|
+
"vitest": "^3.2.4"
|
|
82
80
|
},
|
|
83
81
|
"bug": "https://github.com/isdk/ai-tool.js/issues",
|
|
84
82
|
"description": "AI tools",
|
|
@@ -105,9 +103,9 @@
|
|
|
105
103
|
"scripts": {
|
|
106
104
|
"build-fast": "tsup",
|
|
107
105
|
"build": "pnpm run build-fast --dts-resolve --dts && pnpm run doc:md",
|
|
108
|
-
"clean": "rm -fr web
|
|
106
|
+
"clean": "rm -fr docs/api web dist",
|
|
109
107
|
"doc": "typedoc --plugin none --out web",
|
|
110
|
-
"doc:md": "typedoc --plugin typedoc-plugin-markdown --out docs",
|
|
108
|
+
"doc:md": "typedoc --plugin typedoc-plugin-markdown --out docs/api",
|
|
111
109
|
"style": "pnpm run format -c && pnpm run lint",
|
|
112
110
|
"style:fix": "pnpm run format:fix && npm run lint:fix",
|
|
113
111
|
"format": "prettier \"**/*.{ts,tsx,js,jsx,css,scss,sass,less,md}\"",
|
|
@@ -115,7 +113,7 @@
|
|
|
115
113
|
"lint": "eslint .",
|
|
116
114
|
"lint:fix": "pnpm run lint --fix",
|
|
117
115
|
"test": "FORCE_COLOR=1 vitest run",
|
|
118
|
-
"release": "pnpm run clean && pnpm run build && git add -f docs && git ci -m 'docs: update API docs' && pnpm dlx commit-and-tag-version -s",
|
|
116
|
+
"release": "pnpm run clean && pnpm run build && git add -f docs/api && git ci -m 'docs: update API docs' && pnpm dlx commit-and-tag-version -s",
|
|
119
117
|
"release.alpha": "npm run release -- --prerelease alpha"
|
|
120
118
|
}
|
|
121
119
|
}
|
package/dist/chunk-OYDBRUZJ.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{EventEmitter as t}from"events-ex";import{AdvancePropertyManager as e}from"property-manager";import{_createFunction as n}from"util-ex";import{AbortError as i,AbortErrorCode as r,AlreadyExistsError as s,AlreadyExistsErrorCode as o,BaseError as a,CommonError as c,createError as u,ErrorCode as h,InternalErrorCode as f,NotFoundErrorCode as l,NotFoundError as m,NotImplementedErrorCode as p,NotImplementationError as d,throwError as y}from"@isdk/common-error";import{createAbilityInjector as w}from"custom-ability";import{toRegExp as v}from"util-ex";var g=.618,b=["get","post","put","delete","patch","list","res"],k={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,i,r)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}};import{format as $,parse as x,parseISO as E}from"date-fns";import{formatISO as S,parseISO as A,toDate as T}from"date-fns";var j="MMMM d, y 'at' h:m:s b 'GMT'x";function O(t){let e;try{"string"==typeof t?e=E(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function N(t,e=j){return x(t,e,new Date)}function I(t,e=j){return $(t,e)}var C=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],R=["human","ai","generic","system","tool"],M=["user","assistant","system","tool","tool_calls"];function z(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=O(t);n&&(e+=" ["+I(n)+"]")}e+=" "+n.content+"\n"}return e}import{StringTemplate as L,EnvStringTemplate as _,FStringTemplate as X,GolangStringTemplate as F,expandEnv as P,expandObjEnv as D,defaultTemplateFormat as B,getEnvVairables as q,createHfValueFunc as G}from"@isdk/template-engines";import{StringTemplate as U}from"@isdk/template-engines";function J(t){return Object.keys(t).sort().map((e=>t[e]))}var W=class extends U{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof U?t.examplePrompt:U.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=J(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),i=this.templateFormat;return await U.format({template:n,data:t,templateFormat:i})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};function H(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}U.register(W,{name:"fewshot",aliases:["few_shot"]});var Z=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{Z=t}));var K=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var i;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(i=t,Z?i:H(i))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}};import{detectTextLanguage as Q}from"@isdk/detect-text-language";var V=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,Y=/([A-Z][a-z]{1,2}\.)\s(\w)/g,tt=/(\.[a-zA-Z]\.)\s(\w)/g,et=new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),nt=new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g"),it=/(```)([\s\S]*?)(```)/g,rt=">>>CODE_BLOCK<<<",st=/([*_`]{1,3})(\S.*?\S)\1/,ot=/>>> INLINE_BLOCK (\d+) <<</,at=1e4;function ct(t,e,n){const i="$1"+e+"$2";let r=t;for(let t=0;t<n.length;t++)r=r.replace(n[t],i);return r}function ut(t,{best:e=!0,completeSentence:n,isMarkdown:i,ignoreEmptyLine:r}={}){const s=[],o=[];let a,c=0;for(;c++<at&&(a=it.exec(t));){const e=a[0];s.push(e),t=t.replace(e,"\n"+rt+(s.length-1)+"\n")}for(c=0;c++<at&&(a=st.exec(t));){const e=a[0];o.push(e),t=t.replace(e,">>> INLINE_BLOCK "+(o.length-1)+" <<<")}if(i){const e=t.split("\n");for(let t=0;t<e.length;t++){const n=e[t];pt(n,{isMarkdown:i,nextLine:e[t+1]})&&(s.push(n),e[t]=rt+(s.length-1))}t=e.join("\n")}const u=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let h=[];for(let t=0;t<u.length;t++){let n=u[t].trimEnd();if(!n){!i&&r||h.push("");continue}if(n.startsWith(rt)){h.push(s[Number(n.slice(16))]);continue}if(i&&pt(n,{isMarkdown:i,nextLine:u[t+1]})){h.push(n);continue}if(!e){h.push(n);continue}let a=ct(n,"@",[Y,tt]),c=Array.from(a.matchAll(V)),f=[];if(c.length)for(let t=0;t<c.length;t++)f.push(ct(c[t][0]," ",[et,nt]));else f.push(n);h.push(...f.map((t=>vt(o,t))))}return n&&(h=ht(h,{isMarkdown:i,ignoreEmptyLine:r})),h}function ht(t,{isMarkdown:e,ignoreEmptyLine:n}={}){const i=[];let r=0,s="";for(n=!e&&n;r<t.length;){let c=t[r];if(c){let u;if(n){const n=bt(t,r+1);u=mt(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else u=mt(t[r+1],{isMarkdown:e,nextLine:t[r+2]});o=c,a={isMarkdown:e,nextLine:t[r+1]},lt(o)||mt(o,a)||""===t[r+1]||u?(s&&(c=ft(s,c),s=""),i.push(c)):(s&&(c=ft(s,c)),s=c)}else n||i[i.length-1]&&i.push(c);r++}var o,a;return s&&i.push(s),i}function ft(t,e){const n=t+" "+e,i=Q(n,{isoCode:!0});return i&&!gt(i)?(wt(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function lt(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function mt(t,e){let n=pt(t,e);return n||(n=dt(t)),n||(n=yt(t)),n}function pt(t,e){if(!t)return null;let n=/^\s*第?\s*[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十百千萬万\d]+\s*([章節节编回部篇卷幕场場辑集段册冊期片題]|片段|段落|篇[章目]|小[节節]|(子)?部分|卷[册冊]|[单單]元|章[节節回]|[.、])[ \t]*(?<title>.*)(?=\n|$)/.exec(t);if(n||(n=/^\s*(Chapter|Book|Article|Part|Paragraph|Subsection|Subpart|Volume|Episode|Issue|Unit|Section|Segment|Act|Scene)\s*\d+.*(?=\n|$)/i.exec(t)),!n&&e?.isMarkdown){n=/^[ \t]{0,3}(#+)\s+(?<title>\S.*)$/.exec(t);const i=/^[ \t]{0,3}([-=]+)(?=\n|$)/;!n&&e.nextLine&&!i.test(t)&&/^[ \t]{0,3}\S/.test(t)&&i.test(e.nextLine)&&(n=/^\s*(?<title>.*)(?=\n|$)/.exec(t))}return n}function dt(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function yt(t){return/^[-=_]{3,}$/.exec(t)}function wt(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function vt(t,e){let n,i=0;for(;i++<at&&(n=ot.exec(e));){const i=Number(n[1]);e=e.replace(n[0],t[i])}return e}function gt(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function bt(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function kt(t,e){const n=/(?!\\)([*_])\1(?![ \t]|\1)(.+?)(?<!\\)\1{2}/;let i;for(;(i=n.exec(t))&&(t=t.slice(0,i.index)+i[2]+t.slice(i.index+i[0].length),!e););return t}function $t(t,e){const n=/(?!\\)([*_])(?![ \t]|\1)(.+?)(?<!\\)\1/;let i;for(;(i=n.exec(t))&&(t=t.slice(0,i.index)+i[2]+t.slice(i.index+i[0].length),!e););return t}function xt(t,e){return t=$t(t=kt(t,e),e)}function Et(t,e){const n=[],i=[],r=t.split("\n");for(let t=0;t<r.length;t++){let s=r[t];const o=0===s.trim().length;o||pt(s,{...e,nextLine:r[t+1]})?(i.length&&n.push([...i]),i.length=0,o||i.push(s)):i.push(s)}return i.length&&n.push([...i]),n}function St(t,e=2,n=.5){const i=10**e;return Math.trunc((t+Number.EPSILON+n/i)*i)/i}async function At(t){return new Promise((e=>setTimeout(e,t)))}import{createAbilityInjector as Tt}from"custom-ability";import{EventEmitter as jt,eventable as Ot,states as Nt,wrapEventEmitter as It}from"events-ex";var Ct="event",Rt="event-bus";var Mt=Tt((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Rt)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.on(e,n)}once(e,n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.once(e,n)}off(e,n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.off(e,n)}emit(e,...n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):i.emit.call(this,e,this.name,...n)}emitError(e,...n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emitAsync.call(this,e,this.name,...n)}}}),!0);function zt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Lt=498,_t=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let n,i;this.active||y("Channel closed","SSEChannel",498);let r=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(r=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",n="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:r,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!r||zt(t.events,r))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,n){this.active||y("Channel closed","SSEChannel",498);const i={req:t,res:e,events:n},r=this.options.maxStreamDuration;let s="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";r>0&&(s+=", s-maxage="+(Math.floor(r/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":s,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>zt(i.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),i.res.write(a),this.clients.add(i),r>0&&setTimeout((()=>{i.res.writableEnded||this.unsubscribe(i)}),r),i.res.on("close",(()=>this.unsubscribe(i))),i}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}};function Xt(t){return t instanceof ReadableStream||t instanceof WritableStream}var Ft=600,Pt=601,Dt=class extends a{constructor(t,e=600){super(t,500)}};function Bt(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:i}=await e.read();if(!n){const e=(new TextDecoder).decode(i);t.error(new Dt(`Response error: ${e}`,601))}}})}return new ReadableStream({start(t){t.error(new Dt("Response error: No response body",601))}})}function qt(){return new ReadableStream({start(t){t.close()}})}import{createParser as Gt}from"eventsource-parser";function Ut(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Gt({onEvent:n=>{if("data"in n&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const i=t?t(n.data,{event:n.event}):n.data;i&&e.enqueue(i)}}})},transform(t){n.feed(e.decode(t))}})}function Jt(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Wt(t,e){if(!t.ok)return Bt(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ut(e))}function Ht(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:i}=await e.next();n?t.close():t.enqueue(i)},async cancel(t){await(e.return?.(t))}})}function Zt(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=i=>{n.call(t,i),e.onError&&e.onError(i)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let i;e.onTransform&&(i=await e.onTransform(t,n)),i||(i=t),n.enqueue(i)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}import{v1 as Kt,v5 as Qt,v4 as Vt}from"uuid";import*as Yt from"base32768";import{v1 as te,v4 as ee,v5 as ne,stringify as ie,parse as re,validate as se,version as oe,NIL as ae}from"uuid";var ce={1:Kt,4:Vt,5:Qt};function ue(t=1,e){const n=ce[t];return e?Yt.encode(n(null,[])):n()}import he from"xxhashjs";import*as fe from"base32768";import{canonicalize as le}from"json-canonicalize";import{createMD5 as me,createRIPEMD160 as pe,createSHA1 as de,createSHA224 as ye,createSHA256 as we,createSHA512 as ve,createXXHash128 as ge,createXXHash32 as be,createXXHash64 as ke}from"hash-wasm";var $e=588213,xe=(t=>(t[t.md5=1]="md5",t[t.sha1=2]="sha1",t[t.ripemd=3]="ripemd",t[t.sha256=8]="sha256",t[t.sha384=9]="sha384",t[t.sha512=10]="sha512",t[t.sha224=11]="sha224",t[t.xxhash=111]="xxhash",t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t[t.xxhash128=113]="xxhash128",t))(xe||{}),Ee={1:me,2:de,8:we,10:ve,11:ye,3:pe,112:be,111:ke,113:ge},{h32:Se,h64:Ae}=he;function Te(t,e=16){return"object"==typeof t&&(t=le(t)),Se(t.normalize(),$e).toString(e)}function je(t,e=16){return"object"==typeof t&&(t=le(t)),Ae(t.normalize(),$e).toString(e)}function Oe(t,e=111,n=$e){let i;return t.buffer&&(t=t.buffer),112!==e?(i=Ae(t,n),i=new Uint16Array([i._a00,i._a16,i._a32,i._a48]),i=new Uint8Array(i.buffer)):(i=Se(t,n),i=new Uint16Array([i._low,i._high]),i=new Uint8Array(i.buffer)),i}function Ne(t,e=111,n=$e){return fe.encode(Oe(t,e,n))}import{canonicalize as Ie}from"json-canonicalize";import*as Ce from"base32768";var Re=Ce;async function Me(t,{hashAlgo:e=111,seed:n=$e,outputType:i="string"}={}){const r=await Ee[e](n);r.init();const s=t.getReader();for(;;){const{done:t,value:e}=await s.read();if(t)break;r.update(e)}return"string"!==i?r.digest(i):Ce.encode(r.digest("binary"))}async function ze(t,{hashAlgo:e=111,seed:n=$e,outputType:i="string"}={}){const r=await Ee[e](n);r.init(),r.update(t);return"string"!==i?r.digest(i):Ce.encode(r.digest("binary"))}import{extNameLevel as Le,FilenameReservedRegex as _e,getMultiLevelExtname as Xe,isValidFilename as Fe,isValidFilepath as Pe,sanitizeFilename as De,sanitizeFilepath as Be,WindowsReservedNameRegex as qe}from"@isdk/util";import{isRegExpStr as Ge,toRegExp as Ue}from"util-ex";function Je(t,e){if("string"!=typeof t)throw new c("modelName must be a string","isModelNameMatched",h.InvalidArgument);switch(typeof e){case"string":if(Ge(e)){const n=(e=Ue(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if(Ge(n)){const i=(e=Ue(n)).exec(t);if(i)return i}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function We(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}import{pick as He}from"lodash-es";import{newFunction as Ze}from"util-ex";import{get as Ke,omitBy as Qe}from"lodash-es";import{newFunction as Ve}from"util-ex";async function Ye(t,e,n){return rn(yn(t,e,n),e,n)}function tn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function en(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t),i=n.filter((t=>!isNaN(parseInt(t))));if(1===e.length)void 0!==t[0]&&(t=[t[0]]);else if(n.every((t=>!isNaN(parseInt(t))))&&tn(n.map((t=>parseInt(t)))))t=Object.values(t);else if("0"===i[0]&&tn(i.map((t=>parseInt(t))))){const n=e.filter((([t,e])=>isNaN(parseInt(t))));t=e.filter((([t,e])=>!isNaN(parseInt(t)))).map((([t,e])=>e));let i=0;const r=[];for(;i<n.length&&n[i][1]===t[i];)r.push(i),i++;for(;r.length;)n.splice(r.pop(),1);t={args:t,kvArgs:Object.fromEntries(n)}}else t={args:[],kvArgs:t}}return Array.isArray(t)&&(t={args:t}),t}function nn(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every((t=>!isNaN(parseInt(t))))?t=n.sort(((t,e)=>parseInt(t)-parseInt(e))).map((e=>t[e])):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function rn(t,e,n){if(t.length){const i=await Promise.all(t.map(((t,i)=>dn(t,i,e,n)))),r=n?.returnArrayOnly;let s;if(i?.length){s=Sn(`{${i.map((t=>t)).join(",")}}`,e)}return s&&!r&&(s=nn(s)),s}}function sn(t,e,n,i){const[r,s]=t;if(!r&&"|"===s[0])return"choice: {"+function(t,e,n){const i=yn(t,e,{...n,delimiter:":"}),r={},s=i.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(r[n])throw new Error("Only one "+n+" is allowed");return r[n]=!0,e}{if("|"===e[0]){if(r.items)throw new Error("Only one items is allowed");return r.items=!0,"items:["+function(t,e='"'){return t.map((t=>hn(t,e)))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(r.maxPick)throw new Error("Only one maxPick is allowed");return r.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return r.type=!0,'type:"'+e+'"';if(cn(e)){if(r.separator)throw new Error("Only one separator is allowed");return r.separator=!0,"separator:"+e}}}));return s}(s,n,i)+"}"}async function on([t,e],n,i,r){let s,o;if(i||(i={}),t){const t=e.split(":");s=t[0].trim(),o=t[1].trim()}else o=e,s=n+"";const a={template:o,data:{...Qe(i,((t,e)=>!e||"_"===e[0]||"function"==typeof t)),...r?.templateData}};r?.templateFormat&&(a.templateFormat=r.templateFormat);const c=await L.formatIf(a);if(c)return o=cn(c)?c:JSON.stringify(c),s+":"+o}async function an(t,e,n,i){let r=sn(t,0,n,i);return r||(r=await on(t,e,n,i)),r}function cn(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function un(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}function hn(t,e='"'){return cn(t)?t:e+t+e}function fn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var ln=["true","false","null","undefined","NaN","Infinity"];async function mn(t,e,n){const i=Ve("async expression",[],`return ${t};`,jn(e));let r;try{r=await i.call(this)}catch(t){if(n||!(t instanceof ReferenceError))throw t}switch(typeof r){case"number":case"boolean":case"undefined":return r;case"function":return i.toString();default:return JSON.stringify(r)}}async function pn(t,e,n){let i=t;if(["true","false"].includes(t.toLowerCase()))i=i.toLowerCase();else if(!(r=t,un(r)||!Number.isNaN(parseFloat(r))||ln.includes(r)||xn(r)||e&&void 0!==Ke(e,t)||xn(t)))try{i=n?.skipExpression?fn(t):await mn.call(this,t,e,n?.preserveUnresolvedName)}catch(e){i=fn(t)}var r;return i}async function dn(t,e,n,i){const[r,s]=t,o=i?.argProcessor,a=i?.ignoreIndexNamed;if("function"==typeof o){const r=await o(t,e,n,i);if(r)return r}if(r){const t=s.indexOf(":");return s.slice(0,t).trim()+":"+await pn(s.slice(t+1).trim(),n,i)}{const t=s.trim();if(n&&void 0!==Ke(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await pn(s.trim(),n,i)}}function yn(t,e,n){const i=n?.delimiter??",",r=n?.assigner??"=";let s=[],o=!1,a="",c="",u=!1,h="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==i||o||h)if("\\"===n)c+=n,e++,c+=t[e];else if("("!==n&&"["!==n||o)if(h&&n===h)h="",c+=n;else if("{"!==n||o)'"'===n||"'"===n?(o&&n===a?o=!1:o||(o=!0,a=n),c+=n):n!==r||o||u||!/^[\p{L}\p{N}_ ]+$/u.test(c)?c+=n:(c+=":",u=!0);else{let i,r=e,s=!1,o="",a=-1;for(;r<t.length&&("}"!==(i=t[r])||s||a>0);)"\\"===i?r++:"{"!==i||s?"}"!==i||s?'"'!==i&&"'"!==i||(s&&n===o?s=!1:s||(s=!0,o=n)):a--:a++,r++;r<t.length&&(c+=t.substring(e,r+1),e=r)}else h="("===n?")":"]",c+=n;else c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c]),c="",u=!1}return c&&(c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c])),s}async function wn(t,e,n){const i=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!i){if(n?.raiseError)throw new Error("Invalid command format");return}const[,r,s]=i;let o;return s&&(o=await Ye(s,e,n)),{command:r.trim(),args:o}}var vn="__PlacEhoLdeR_";function gn(t,e){let n=e?.startChar?Array.isArray(e.startChar)?e.startChar:[e.startChar]:['"',"'"],i=e?.endChar?Array.isArray(e.endChar)?e.endChar:[e.endChar]:n;if(n.length!==i.length)throw new Error("start and end characters must have the same length");const r=e?.placeholder??vn,s=n.every(((t,e)=>t===i[e])),o=e?.placehoders??[];if(s){n=n.map((t=>"\\"+t));const e=new RegExp(`(?<!\\\\)(${n.join("|")}).*?(?<!\\\\)\\1`);let i;for(;null!==(i=e.exec(t));){const e=`${r}${o.length}`;t=t.replace(i[0],e),o.push(i[0])}}else{n=n.map((t=>"\\"+t)),i=i.map((t=>"\\"+t));for(let e=0;e<n.length;e++){const s=new RegExp(`(?<!\\\\)${n[e]}.*?(?<!\\\\)${i[e]}`);let a;for(;null!==(a=s.exec(t));){const e=`${r}${o.length}`;t=t.replace(a[0],e),o.push(a[0])}}}return[t,o]}function bn(t,e,n){const i=n?.placeholder??vn;return e.reduce(((t,e,n)=>t.replace(new RegExp(i+n,"g"),e)),t)}var kn="[a-zA-Z_$][a-zA-Z_\\d$]*",$n=new RegExp(`^\\s*(\\(\\s*\\)|${kn}|\\(${`${kn}\\s*(,\\s*${kn})*`}\\))\\s*=>`);function xn(t){return $n.test(t)}async function En(t,e){if(e&&(e=jn(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await Ye(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return Sn(t,e)}function Sn(t,e){if(e&&(e=jn(e)),e){const n=Object.keys(e);if(n.length){const i=Object.values(e);let r=0;for(;r++<100;)try{return Ze("expression",n,`return ${t}`)(...i)}catch(t){if(!(t instanceof ReferenceError))throw t;{const e=/(.+)\s+is not defined/.exec(t.message);if(!e)throw t;n.push(e[1]),i.push(void 0)}}}}return Ze("expression",[],`return ${t}`)()}var An=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Tn=t=>An.test(t);function jn(t){if(t){const e=Object.keys(t),n=e.length,i=e.filter((e=>Tn(e)&&null!==t[e]));if(n===i.length)return t;if(i.length)return t=He(t,i)}}function On(t){return t?Nn(t,[],{dot:""}):[]}function Nn(t,e,{dot:n=".",visited:i=new Set}={}){return i.has(t)?[e.join("")]:Array.isArray(t)?(i.add(t),t.flatMap(((t,n)=>Nn(t,[...e,`[${n}]`],{dot:".",visited:i})))):(r=t)&&r.constructor===Object?(i.add(t),Object.entries(t).flatMap((([t,r])=>Nn(r,[...e,n+t],{dot:".",visited:i})))):[e.join("")];var r}function In(t){if(t<2)throw new c("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",h.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Cn from"path";import*as Rn from"fs";import Mn from"mime-type/with-db";import zn from"jschardet";function Ln(t){const e=Rn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function _n(t,e,n,i){const r=i?.signal,s=i?.exclude;let o;if(Cn.isAbsolute(t)?o=Ln(t)?t:Xn(Cn.basename(t),[Cn.dirname(t)],{extNames:n,exclude:s,signal:r}):(e||(e=["."]),o=Xn(t,e,{extNames:n,exclude:s,signal:r})),!o)throw new m(t,"loadFileFromPaths");{const t=o;o=Rn.readFileSync(o),i&&(i.filepath=t)}return o}function Xn(t,e,{extNames:n,signal:i,exclude:r=[]}){let s;const o=n?n.map((e=>Xe(t,Le(e)))):void 0;"string"==typeof r&&(r=[r]);for(const a of e){if(i?.aborted)throw i.reason;const e=Cn.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const i=e+(o[t]!==n[t]?n[t]:"");if(!r.includes(i)&&Ln(i)){s=i;break}}else if(!r.includes(e)&&Ln(e)){s=e;break}}return s}function Fn(t,e,n,i,r){let s;"string"==typeof i?(s=i,i=void 0):s=i?.encoding;return Pn(_n(t,e,n,i),s)}function Pn(t,e){void 0===e&&(e=Jn(t)??"utf8");return new TextDecoder(e).decode(t)}function Dn(t,e){const n=[],i="string"==typeof t?[{dir:t,level:0}]:[...t.map((t=>({dir:t,level:0})))],r=new Set,s=e?.signal,o=e?.isFileMatched,a=e?.level,c=e?.resolveSymlinks??!0;let u=0;for(;i.length>0;){if(s?.aborted)throw s.reason;const t=i.pop(),e=c?Bn(t.dir):t.dir,h=Cn.resolve(e);if(r.has(h))continue;r.add(h);const f=Rn.statSync(e,{throwIfNoEntry:!1});if(f?.isDirectory()){u=t.level+1;const r=Rn.readdirSync(e,{withFileTypes:!0});for(let t=0;t<r.length;t++){let s=r[t],h=Cn.join(e,s.name);const f=h;if(s.isSymbolicLink()){const t=Cn.dirname(h);h=Rn.readlinkSync(h),h=Cn.resolve(t,h),s=Rn.statSync(h)}if(s.isDirectory())(!a||u<a)&&(o&&!o(h,s)||i.push({dir:h,level:u}));else if(s.isFile()&&(!o||o(h,s))){const t=c?h:f;n.includes(t)||n.push(t)}}}}return n}function Bn(t){const e=Rn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Rn.readlinkSync(t)),t}async function qn(t,e){return Me(ReadableStream.from(Rn.createReadStream(t)),e)}async function Gn(t){const e=Cn.basename(t);t=Cn.resolve(t);const n=await Rn.promises.stat(t),i=n.mtime,r=n.ctime,s=n.size,o=Un(s),a=await qn(t,{hashAlgo:o}),c=Mn.lookup(t);return{name:e,mtime:i,ctime:r,size:s,hash:xe[o]+":"+a,mimeType:c,id:"file://"+t}}function Un(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function Jn(t,e){return zn.detect(t,e).encoding}import{statSync as Wn}from"fs";import Hn from"path";import{ConfigFile as Zn,registerYamlTag as Kn,traverseFolderSync as Qn}from"@isdk/util";import{regexp as Vn}from"yaml-types";import{mimeType as Yn}from"mime-type/with-db";import{ConfigFile as ti,registerYamlTag as ei,parseYaml as ni,stringifyYaml as ii}from"@isdk/util";function ri(t,e){const n=[],i=e?.after,r=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,s=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return Qn(t,((t,e)=>{if(r?.includes(t)||!e.isFile())return;const o=Hn.extname(t),a=Wn(t);if(s.includes(o)){if(i?.hasOwnProperty(t)&&a.mtimeMs<=i[t])return;n.push(t)}})),n}function si(t,e){return ri(t,e).map((t=>Zn.loadSync(t))).filter((t=>void 0!==t))}function oi(t,e,n=1){return Zn.saveSync(t,e,{extLevel:n})}function ai(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function ci(t,e){return t.map((t=>fi(t,e))).join(" AND ")}function ui(t,e){return t.map((t=>fi(t,e))).join(" OR ")}function hi(t,e){const n=[];return Object.keys(e).forEach((i=>{const r=e[i];switch(i){case"$lt":case"<":n.push(`${t} < ${ai(r)}`);break;case"<=":case"$lte":n.push(`${t} <= ${ai(r)}`);break;case"$gt":case">":n.push(`${t} > ${ai(r)}`);break;case"$gte":case">=":n.push(`${t} >= ${ai(r)}`);break;case"$ne":case"!=":n.push(`${t} != ${ai(r)}`);break;case"=":case"$eq":n.push(`${t} = ${ai(r)}`);break;case"$in":n.push(`${t} IN (${r.map((t=>ai(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${r.map((t=>ai(t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${r.source}'`);break;case"$like":n.push(`${t} LIKE '${r}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${r}'`);break;case"$glob":n.push(`${t} GLOB '${r}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${r}'`);break;default:throw new Error(`Unsupported condition operator: ${i}`)}})),n.join(" AND ")}function fi(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(ci(t,e));else for(const[i,r]of Object.entries(t))if("$and"===i)n.push(`(${ci(t[i],e)})`);else if("$or"===i)n.push(`(${ui(t[i],e)})`);else{const t=typeof r;if(null==r)n.push(`${e(i)} IS NULL`);else if(r instanceof Date)n.push(`${e(i)}='${r.toISOString()}'`);else if("object"!==t||Array.isArray(r))if("string"===t)n.push(`${e(i)}='${r}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${i}`);n.push(`${e(i)}=${r}`)}else n.push(hi(e(i),r))}return n.length>1?n.join(" AND "):n[0]}function li(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function mi(t,e=0){let n,i=t*10**e;return t>=1e12?(i=Math.round(i/1e12),n="T"):t>=1e9?(i=Math.round(i/1e9),n="B"):t>=1e6?(i=Math.round(i/1e6),n="M"):t>=1e3?(i=Math.round(i/1e3),n="K"):(i=Math.round(i),n=""),i/=10**e,i.toFixed(e)+n}function pi(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new c("Invalid formatted parameter size string.","scaleToSize",h.InvalidArgument);const n=parseFloat(e[1]),i=e[2]?.toLowerCase();switch(i){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function di(t,e){const n=e?.level||0,i=e?.visiting||new Set,r=e?.objectTag||"*",s=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":i.has(t)?o=["[Circular]"]:(i.add(t),o=Array.isArray(t)?t.map((t=>s+c(t))):Object.entries(t).map((([t,e])=>r+" `"+t+"`:"+c(e))));break;case"string":return t;default:return JSON.stringify(t)}else o=["null"];return o.length?a+o.join("\n"+a):"";function c(t){return(null!=t&&"object"==typeof t?"\n":" ")+di(t,{level:n+1,visiting:i})}}Kn(Vn);var yi=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}};import{isAsync as wi}from"util-ex";import{EventEmitter as vi}from"events-ex";function gi(t=0){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var bi=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=gi(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this[n]=t,++e<=this._capacity&&(this._length=e),n}unshift(t){let e=this._length;this.checkCapacity(++e);const n=this._capacity,i=(this._front-1&n-1^n)-n;return this[i]=t,this._front=i,e<=this._capacity&&(this._length=e),i}pop(t){let e=this._length;if(0===e)return;let n=this._front+e-1&this._capacity-1,i=this[n];for(;--e>0&&t&&null==i;)n--,i=this[n];return this[n]=void 0,this._length=e,i}shift(t){let e=this._length;if(0===e)return;let n=this._front,i=this[n];for(;--e>0&&t&&null==i;)n=n+1&this._capacity-1,i=this[n];return this[n]=void 0,this._front=n+1&this._capacity-1,this._length=e,i}get size(){return this._length}get(t){let e;if(t===(0|t)){const n=this._length;t<0&&(t+=n),t>=0&&t<n&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,n=this._capacity;for(let i=0;i<t;++i)this[e+i&n-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const n=this._front,i=this._capacity-1,r=n+t&i,s=this[r];if(t<e/2)this.copyWithin(n+1&i,n,n+t&i),this[n]=void 0,this._front=n+1&i;else{this.copyWithin(r,r+1&i,n+e&i);this[n+e-1&i]=void 0}return this._length=e-1,s}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(gi(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,i=this._length;if(n+i>e){!function(t,e,n,i,r){for(let s=0;s<r;++s)n[s+i]=t[s+e],t[s+e]=void 0}(this,0,this,e,n+i&e-1)}}};import{AbortError as ki}from"@isdk/common-error";var $i=32;function xi(t){return"function"==typeof t}function Ei(){return"1"}var Si=class{constructor(t={}){const{initFn:e=Ei,pauseFn:n,resumeFn:i,capacity:r=$i}=t;if(xi(n)!==xi(i))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new bi(r),this.emitter=new vi,this.useDefaultTokens=e===Ei,this.pauseFn=n,this.resumeFn=i,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,n=this.waiting.shift(!0);n?this._dispatchTask(n,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const n=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(n,t),n}_dispatchTask(t,e){const{resolve:n}=t;n(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,n=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push(t),i=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[n]=void 0;const t=e.reason instanceof Error?e.reason:new ki(e.reason||"aborted");e.alreadyRejected=!0,i(t)})),n};let i=this.tryAcquire(t);const r=i&&wi(i),s=e=>new Promise(((i,r)=>{const s={...t,resolve:i,reject:r,token:e};void 0===e?n(s):this._dispatchTask(s,{...t,token:e})}));return r?i.then((t=>s(t))):s(i)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new ki(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},Ai=class extends Si{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new bi(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&wi(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}};function Ti(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const i=new Ai(n?1:t),r=n?e/t:e;return async function(){await i.acquire(),setTimeout((()=>i.release()),r)}}import{AbortError as ji}from"@isdk/common-error";var Oi=class{constructor(){this._isSignaled=!1,this.waitQueue=[]}get signaled(){return this._isSignaled}signal(t){if(this._isSignaled)return;this._isSignaled=!0,this._signalValue=t;const e=this.waitQueue.slice();for(this.waitQueue.length=0;e.length>0;){const t=e.shift();t?.resolve(this._signalValue)}}reset(){this._isSignaled=!1,this._signalValue=void 0,this.waitQueue.length=0}abort(t){if(this.waitQueue.length){const e=this.waitQueue.slice();this.waitQueue.length=0;const n=new ji(t);for(;e.length>0;){const{reject:t}=e.shift();t(n)}}}async wait(){return new Promise(((t,e)=>{this._isSignaled?t(this._signalValue):this.waitQueue.push({resolve:t,reject:e})}))}};import{createAbilityInjector as Ni}from"custom-ability";import{defineProperty as Ii}from"util-ex";var Ci,Ri=0,Mi=1,zi=2,Li=(t=>(t[t.MultiTask=0]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Li||{}),_i=((Ci=_i||{})[Ci.MultiTask=1]="MultiTask",Ci[Ci.Cancelable=2]="Cancelable",Ci[Ci.Priority=4]="Priority",Ci),Xi=class extends AbortController{constructor(t){super(),Ii(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new i(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new i(e.reason||"aborted")}}},Fi=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,n=this.__task_semaphore;return e>0&&!n&&(t&&(t=t.bind(this)),n=this.__task_semaphore=new Ai(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),yi.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),yi.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new c("Missing taskId",this.name+".isAborted",h.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new c("Missing taskId",this.name+".getRunningTask",h.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const n=this.super,i=this.self||this;return t=n?n.call(i,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const i=this.hasAsyncFeature(0);if(!i&&n&&this.getRunningTask())throw new c("The task is running",this.name,h.TooManyRequests);const r=t?.aborter||new Xi(this);if(!(r instanceof Xi)){if(!(r instanceof AbortController))throw new c("aborter should be an AbortController",this.name,h.InvalidArgument);Object.setPrototypeOf(r,new Xi(this))}if(i){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),r.id=e,t[e]=r}else this.__task_aborter=r;const s=t?.timeout;return s>0&&(r.timeoutId=setTimeout((()=>{r.timeoutId=void 0,this.abort("timeout",{timeout:s})}),s)),r.signal.addEventListener("abort",(()=>{const t=r.timeoutId;t&&(r.timeoutId=void 0,clearTimeout(t));const e=r.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{r.streamController?.error(e.reason)}})),r}$cleanMultiTaskAborter(t,e){const n=this.super,i=this.self||this;n?n.call(i,t,e):i._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,n){const i=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=i);let r=t(e,i).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(i)},n=Zt({onStart:t=>{Ii(i,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=i.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(i);return t})).catch((t=>{throw this.cleanTaskAborter(i),t})).finally((()=>{i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=void 0)}));return r.task=i,r}runAsyncCancelableTask(t={},e,n){let i=this.createTaskPromise(e,t,n);const r=this.getSemaphore(n?.isReadyFn);if(r){const t=i,e=t.task;i=r.acquire({signal:e.signal}).then((()=>t)).finally((()=>{r.release()})),i.task=e}return i}abort(t,e){let n=this.__task_aborter;if(n){const i=n;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new c("Missing data.taskId",this.name+".abort",h.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,i)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Fi.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Fi.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Pi=Ni(Fi,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=_i.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=n}});function Di(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let i,r=0;for(;null!==(i=n.exec(t));)r++;return r}import Bi from"memoizee";import{canonicalize as qi}from"json-canonicalize";function Gi(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const i=e?.normalizer;return Bi(t,{...e,normalizer:t=>{if(i){const e=i(t);if("string"===e)return e;e&&(t=e)}return Ne(qi(t))}})}import Ui from"path";import{packageDirectorySync as Ji}from"pkg-dir";function Wi(t){const e=Ji({cwd:t});if(e)return e;const n=t.split(Ui.sep);let i=n.lastIndexOf("dist");if(i>0)return n.slice(0,i).join(Ui.sep);if(i=n.lastIndexOf("src"),i>0)return n.slice(0,i).join(Ui.sep);throw new Error("can not find package directory")}import Hi from"path";function Zi(t,e){try{const n=Hi.relative(Hi.resolve(t),Hi.resolve(e));return!n.startsWith("..")&&!Hi.isAbsolute(n)}catch{return!1}}function Ki(t,e){return e?.some((e=>Zi(e,t)))}function Qi(t,e){for(const n of e)Ki(n,t)||t.push(n);return t}import{isRegExp as Vi,isRegExpStr as Yi}from"util-ex";function tr(t){return Yi(t)||Vi(t)}function er(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}import nr from"path";import{fileURLToPath as ir}from"url";import{AutoTokenizer as rr}from"@xenova/transformers";var sr=ir(import.meta.url),or=nr.dirname(sr),ar=nr.join(Wi(or),".cache"),cr=new Map,ur={"deepseek-ai/DeepSeek-V2-Lite-Chat":"deepseek2","Qwen/Qwen2.5-0.5B":"Qwen2.5","Xenova/gpt-4":"gpt-4 / gpt-3.5-turbo / text-embedding-ada-002","Xenova/text-davinci-003":"text-davinci-003 / text-davinci-002","Xenova/gpt-3":"gpt-3","Xenova/grok-1-tokenizer":"Grok-1","Xenova/claude-tokenizer":"Claude","Xenova/mistral-tokenizer-v3":"Mistral v3","Xenova/mistral-tokenizer-v1":"Mistral v1","Xenova/gemma-tokenizer":"Gemma","Xenova/gemma2-tokenizer":"Gemma2","Xenova/llama3-tokenizer-new":"Llama 3","unsloth/Llama-3.2-1B-Instruct":"Llama 3.2","Xenova/llama-tokenizer":"LLaMA / Llama 2","Xenova/c4ai-command-r-v01-tokenizer":"Cohere Command-R","Xenova/t5-small":"T5","Xenova/bert-base-cased":"bert-base-cased"},hr={deepseek2:"deepseek-ai/DeepSeek-V2-Lite-Chat","qwen2.5":"Qwen/Qwen2.5-0.5B","gpt-4":"Xenova/gpt-4","gpt-3.5-turbo":"Xenova/gpt-4","text-embedding-ada-002":"Xenova/gpt-4","text-davinci-003":"Xenova/text-davinci-003","text-davinci-002":"Xenova/text-davinci-003","gpt-3":"Xenova/gpt-3","grok-1":"Xenova/grok-1-tokenizer",claude:"Xenova/claude-tokenizer",mistral:"Xenova/mistral-tokenizer-v3",mistral3:"Xenova/mistral-tokenizer-v3",mistral1:"Xenova/mistral-tokenizer-v1",gemma:"Xenova/gemma-tokenizer",gemma2:"Xenova/gemma2-tokenizer",llama3:"Xenova/llama3-tokenizer-new",llama2:"Xenova/llama-tokenizer",llama:"Xenova/llama-tokenizer","llama3.2":"unsloth/Llama-3.2-1B-Instruct","cohere-command-r":"Xenova/c4ai-command-r-v01-tokenizer",t5:"Xenova/t5-small","bert-cased":"Xenova/bert-base-cased"};async function fr(t){let e=cr.get(t);return e||(e=rr.from_pretrained(t,{cache_dir:ar}),cr.set(t,e)),e}async function lr(t,e="qwen2.5"){hr[e]&&(e=hr[e]);return(await fr(e)).encode(t)}async function mr(t,e="qwen2.5"){return(await lr(t,e)).length}function pr(t,e){const n=e?.capitalize??!0;let i=e?.delimiter??/[_-]/g;i instanceof RegExp&&(i.flags.includes("g")||(i=new RegExp(i.source,i.flags+"g")));let r=(t=t.replace(i," ")).split(" ").map((t=>t.trim())).filter(Boolean);return n&&(r=r.map((t=>t.charAt(0).toUpperCase()+t.slice(1)))),t=r.join(" ")}async function dr(t,e){let n,i=1984,r=!0,s=!1,o=!0,a=mr,u=!0;if(e&&(n=e.modelId,e.size>=0&&(i=e.size),void 0!==e.corrected&&(r=e.corrected),void 0!==e.completeSentence&&(s=e.completeSentence),void 0!==e.truncLastSection&&(o=e.truncLastSection),"function"==typeof e.countLLMTokens&&(a=e.countLLMTokens),void 0!==e.bySentence&&(u=e.bySentence)),!u)throw new d("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(i>0){let u=await a(t,n);const h=e?.sentences??ut(t,e);if(u>i)for(u=await a(h.join("\n"),n);u>i&&h.length;){const e=h.pop();if(e){if(u-=await a(e+"\n",n),s||r)t=h.join("\n");else{const n=t.lastIndexOf(e);if(-1===n)throw new c(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n)}if(u<=1)throw new c(`Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");if(u<=i&&o){const e=h[h.length-1];if(e&&mt(e)){if(u-await a(e,n)>9){const n=t.lastIndexOf(e);if(-1===n)throw new c(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n).trimEnd()}}}}else u--}else t=h.join("\n")}if(!t)throw new c(`Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");return t}async function yr(t,e){let n,i=1984,r=!0,s=mr,o=!0;if(e&&(n=e.modelId,e.size>=0&&(i=e.size),void 0!==e.truncLastSection&&(r=e.truncLastSection),"function"==typeof e.countLLMTokens&&(s=e.countLLMTokens),void 0!==e.bySentence&&(o=e.bySentence)),!o)throw new d("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(i>0){const e=(t=t.slice()).join("\n");let o=await s(e,n);if(o>i)for(;o>i&&t.length;){const e=t.pop();if(e){if(o-=await s(e,n),o<=1)throw new c(`Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");if(o<=i&&r){const e=t[t.length-1];if(e&&mt(e)){o-await s(e,n)>9&&t.pop()}}}}}if(!t.length)throw new c(`Empty. Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");return t}async function wr(t,e){let n,i=1984,r=mr;if(e&&(n=e.modelId,"function"==typeof e.countLLMTokens&&(e.size>=0&&(i=e.size),r=e.countLLMTokens)),i>0){await r(t,n)}}import vr from"fs";async function*gr(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,i=e.modelId,r=e.metaInfo?.size??(await vr.promises.stat(t)).size;let s=Math.trunc(r/2);if(s<=n){let r=Pn(await vr.promises.readFile(t));if(s=await mr(r,i),s<=n)yield r;else do{const t=await dr(r,{...e,modelId:i,size:n});yield t,r=r.slice(t.length)}while(r)}else{const r=ReadableStream.from(vr.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await r.read();if(t)break;s+=Pn(o);const a=ut(s,e);let c=a.pop();if(c){const t=s.lastIndexOf(c);c=s.slice(t),s=s.slice(0,t)}if(s.length>=n){const t=await dr(s,{...e,modelId:i,size:n,sentences:a});s=s.slice(t.length),yield t}for(;s.length>n;){const t=ut(s,e),r=await dr(s,{...e,modelId:i,size:n,sentences:t});s=s.slice(r.length),yield r}void 0!==c&&(s+=c)}for(;s;){const t=ut(s,e),r=await dr(s,{...e,modelId:i,size:n,sentences:t});s=s.slice(r.length),yield r}}}async function*br(t,e){const n=e?.size??1984,i=e?.modelId,r=e?.metaInfo?.size??(await vr.promises.stat(t)).size;let s=Math.trunc(r/2);if(s<=n){let r=Pn(await vr.promises.readFile(t));if(s=await mr(r,i),s<=n)yield ut(r,e);else{let t=ut(r,e);do{const r=await yr(t,{...e,modelId:i,size:n});yield r,t=t.slice(r.length)}while(t.length)}}else{const r=ReadableStream.from(vr.createReadStream(t)).getReader();let s="";const o=e?.completeSentence,a=e?.corrected,c=!o&&!a;let u;for(;;){const{done:t,value:o}=await r.read();if(t)break;s+=Pn(o),u=ut(s,e);let a=u.pop();if(s.length>=n){const t=await yr(u,{...e,modelId:i,size:n});s=c?s.slice(t.length):u.join("\n"),u=u.slice(t.length),s=u.join("\n"),yield t}for(;s.length>n;){const t=await yr(u,{...e,modelId:i,size:n});u=u.slice(t.length),s=u.join("\n"),yield t}a&&u.push(a)}if(u)for(;u.length;){const t=await yr(u,{...e,modelId:i,size:n});u=u.slice(t.length),yield t}}}async function kr(t,e){const n=e?.size??1984,i=e?.modelId;let r=ut(t,e);const s=[];if(await mr(t,i)<=n)s.push(r);else do{const t=await yr(r,{...e,modelId:i,size:n});s.push(t),r=r.slice(t.length)}while(r.length);return s}import{YAMLMap as $r}from"yaml";var xr=class{constructor(t){t&&Object.assign(this,t)}};function Er(t,e){const n={tag:t,collection:"map",nodeClass:class extends $r{constructor(){super(...arguments),this.tag=t}toJSON(t,n){n={...n,mapAsMap:!1};const i=super.toJSON(t,n);return new e(i)}},identify:t=>t instanceof e};return n}function Sr(t,e){let n=t.length===e.length;if(n){const i=Oe(t),r=Oe(e);n=i.every(((t,e)=>t===r[e]))}return n}import{defaultsDeep as Ar,omit as Tr}from"lodash-es";import jr from"path";var Or=".ai";function Nr(t,e=["."]){if(jr.isAbsolute(t))return ti.loadSync(t);const n=e.map((e=>ti.loadSync(jr.resolve(e,t)))).filter(Boolean);return Ar({},...n.reverse())}function Ir(t,e){const n={...process.env,...e};return D(t,{processEnv:n,parsed:n})}function Cr(t,e){let n=ti.loadSync(jr.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:[jr.join(e.dataDir,"brain")],agentDirs:[jr.join(e.dataDir,"agent")],promptDirs:[jr.join(e.dataDir,"prompt")],chatsDir:jr.join(e.dataDir,"log","chats"),inputsDir:jr.join(e.dataDir,"log","inputs")});const i=Mr(e);for(const[t,e]of Object.entries(i))n[t]=e;Ir(n,n);const r=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Ir(Nr(t,r),n);return Ar(s,Tr(n,Object.keys(i)))}function Rr(t){return Cr(".ai",t)}function Mr(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:jr.dirname(t.options.root)}}function zr(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Ir(t,e)}var{exit:Lr}=process,_r=!1,Xr=!1,Fr=["SIGINT","SIGTERM","exit"],Pr=[],Dr=(t,e)=>t.forEach((t=>process.once(t,e)));async function Br(t="shutdown",e=0){if(!_r){_r=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of Pr)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return Lr(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function qr(t){if(Xr||Gr(),!Pr.some((e=>e===t)))return Pr.push(t),t}function Gr(){var t;Xr||(Xr=!0,process.exit=t=>{_r||Br(void 0,t).then()},Dr(Fr,(t=3e5,()=>{setTimeout((()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),Lr(1))),t).unref()})),Dr(Fr,Br))}var Ur=class t extends e{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const i=this.get(n);let r=i.tags;if("string"==typeof r){if(r===t){e=i;break}}else if(Array.isArray(r)&&r.indexOf(t)>=0){e=i;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const i=this.get(n);let r=i.tags;"string"==typeof r?r===t&&e.push(i):Array.isArray(r)&&r.indexOf(t)>=0&&e.push(i)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),yi.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new m(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new m(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const n=this.get(t);if(n)return n.runWithPos(...e);throw new m(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new m(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let i=!!this.get(e);if(i)i=!1;else{if(!(n instanceof t))return i=new this(n),i.register();if(this.items[e]=n,n.alias){const t=n.alias;if("string"==typeof t)this.aliases[t]&&y(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const n of t)this.aliases[n]&&y(`Alias ${n} already exists for ${e}`),this.aliases[n]=e}i=n}return i}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const i of e){const e=n[i];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let i=Math.min(n.length,t.length);for(let r=0;r<i;r++)e[n[r]]=t[r];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let i=Math.min(n.length,this.params.length);for(let r=0;r<i;r++)e.push(t[n[r]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);y("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),yi.has(e,t)}isStream(t){return this.stream}},Jr={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,i,r,s){let o=t;const a=typeof t;return s.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=n(t,e.scope)),o}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};Ur.defineProperties(Ur,Jr);var Wr=class extends Ur{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Hr=new Wr(Rt);import{Cache as Zr}from"secondary-cache";import{LRUCache as Kr}from"secondary-cache";var Qr=Zr;function Vr({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function Yr(t,e){let n=Ur.get(t);return n||(n=new Ur(t,{func:Vr,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new Zr(e)),n}var ts=Yr("lrucache"),es=class t extends Ur{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else y("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const i=this.get(n),r=e[n];i?i instanceof t?i.assign(r):y(`${n} already registered as ${i.constructor.name}`,"ClientTools"):this.register(r)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,n){const i={...this.fetchOptions},r=["post","put","patch"];let s;e||(e=this.action||"post"),"res"===e&&(e="get"),i.headers&&i.headers["Content-Type"]||!r.includes(e)||(i.headers={"Content-Type":"application/json",...i.headers}),t?.stream&&!i.headers.Connection&&(i.headers.Connection="keep-alive"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,i.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(i.body=JSON.stringify(t),s=n),i.headers&&!r.includes(e)&&delete i.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${s}`,i);if(!o.ok){throw await this.errorFrom(o)}return o}async errorFrom(t){let e,n=t.status,i=t.statusText,r=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(i=t.error),t.name&&(r=t.name),t.data&&(e=t.data,e.name=r,e.what&&(e.msg=i,i=e.what)),t.message&&(i=i+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return u(i,r,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ns={...k};es.defineProperties(es,ns);var is=class extends es{async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},rs={methods:{type:"array",assign(t,e,n,i,r){r?.isExported||e.assignMethods(t)}}};is.defineProperties(is,rs);var ss=class extends is{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||y("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},os=class extends ss{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Ct,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",n=`${this.apiRoot}/${this.name}${e}`,i=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{i.addEventListener(t,e)})),this._esEvents=t,i}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},as=new os(Ct);import{getAllNames as cs}from"util-ex";var us=class t extends Ur{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let i=this.items[n];(i instanceof t||i.isApi)&&(i.allowExportFunc||(i=i.toJSON(),delete i.func),e[n]=i)}return e}func({}){}},hs={...k};us.defineProperties(us,hs);var fs=class extends us{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);cs(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new m(e,this.name)}};fs.defineProperties(fs,{methods:{type:"array"}});var ls=class extends fs{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=b}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},ms=Hr.runSync(),ps=class t extends ls{constructor(){super(...arguments),this.name=Ct,this.description="subscribe server sent event",this.result="event",this.depends={[Rt]:Hr}}static get sse(){return this._sse||(this._sse=new _t),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,i){return t.sse.subscribe(e,n,i)}static alreadyForward(e){const n=ms.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||ms.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)ms.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};y("event is required","sub",h.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};y("event is required","unsub",h.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}y("event or data is required","pub",h.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},ds=new ps(Ct);function ys(){Hr.register(),ts.register()}export{g as PASSING_SCORE,b as ActionNames,k as RemoteToolFuncSchema,i as AbortError,r as AbortErrorCode,s as AlreadyExistsError,o as AlreadyExistsErrorCode,a as BaseError,c as CommonError,u as createError,h as ErrorCode,f as InternalErrorCode,l as NotFoundErrorCode,m as NotFoundError,p as NotImplementedErrorCode,d as NotImplementationError,y as throwError,x as parseDateFormat,O as toDateTime,N as textToDate,I as dateToText,S as formatISO,A as parseISO,T as toDate,C as AITextGenerationFinishReasons,R as AIMessageTypes,M as AIChatRoles,z as messagesToText,J as sortedValues,W as FewShotPromptTemplate,K as PromptExampleSelector,L as StringTemplate,_ as EnvStringTemplate,X as FStringTemplate,F as GolangStringTemplate,P as expandEnv,D as expandObjEnv,B as defaultTemplateFormat,q as getEnvVairables,G as createHfValueFunc,ut as splitSentence,ht as completeSentences,ft as concatText,lt as isSentenceEnding,mt as isSectionString,pt as isTitleString,dt as isListItemString,yt as isSepLineString,wt as isPunctuationChar,gt as isLangUsingSpaces,bt as findIndexNonEmptyFrom,kt as removeMarkdownBold,$t as removeMarkdownItalic,xt as removeMarkdownBoldAndItalic,Et as splitParagraph,St as truncTo,At as wait,Ct as EventName,Rt as EventBusName,Mt as backendEventable,jt as EventEmitter,Ot as eventable,Nt as states,It as wrapEventEmitter,Lt as SSEChannelAlreadyClosedErrCode,_t as SSEChannel,Xt as isWebStream,Ft as RStreamErrCode,Pt as ResponseRStreamErrCode,Dt as ReadableStreamError,Bt as getResponseErrorReadableStream,qt as createEmptyReadableStream,Ut as createEventStreamTransformer,Jt as trimStartOfStreamHelper,Wt as AIStream,Ht as readableFromAsyncIterable,Zt as createCallbacksTransformer,ue as uuid,te as v1,ee as v4,ne as v5,ie as stringify,re as parse,se as validate,oe as version,ae as NIL,xe as HashAlgorithm,Te as xxhash32,je as xxhash64,Oe as xxhash,Ne as xxhashAsStr,Ie as canonicalize,Re as base32768,Me as hashStream,ze as hash,Le as extNameLevel,_e as FilenameReservedRegex,Xe as getMultiLevelExtname,Fe as isValidFilename,Pe as isValidFilepath,De as sanitizeFilename,Be as sanitizeFilepath,qe as WindowsReservedNameRegex,Je as isModelNameMatched,We as getAllEnumKeys,Ye as parseObjectArguments,en as ObjectArgsToArgsInfo,nn as simplifyObjectArguments,rn as parseObjectArgumentInfos,sn as ChoiceArgProcessor,on as TemplateArgProcessor,an as AIArgProcessor,cn as isQuoted,un as isStrWrapped,hn as ensureQuoted,fn as quoteStr,dn as parseObjectArgInfo,yn as parseObjectArgumentsAsArgInfos,wn as parseCommand,gn as replaceWithPlaceholder,bn as restoreFromPlacehoders,En as parseJsJson,Sn as parseJsJsonSimpleSync,jn as filterValidFnScope,On as getKeysPath,In as createEndWithRepetitionDetector,Ln as fileIsExists,_n as loadFileFromPaths,Fn as loadTextFromPaths,Pn as decodeCharset,Dn as readFilenamesRecursiveSync,Bn as getRealFilepath,qn as hashFile,Gn as getFileMetaInfo,Un as getHashAlgoBySize,Jn as detectCharset,ri as getConfigFileNames,si as getConfigs,oi as saveConfigFile,Yn as mimeType,ti as ConfigFile,ei as registerYamlTag,ni as parseYaml,ii as stringifyYaml,fi as jsonFilterToWhere,li as matchUrlProtocol,mi as paramsSizeToScaleStr,pi as scaleStrToParamsSize,di as jsonToMarkdownStr,yi as IntSet,$i as DefaultAsyncSemaphoreCapacity,Si as BinarySemaphore,Ai as Semaphore,Ti as RateLimit,Oi as SignalGate,Ri as ToolAsyncMultiTaskBit,Mi as ToolAsyncCancelableBit,zi as ToolAsyncPriorityBit,Li as AsyncFeatureBits,_i as AsyncFeatures,Xi as TaskAbortController,Fi as CancelableAbility,Pi as makeToolFuncCancelable,Di as countRegexMatches,Gi as memoize,Wi as getPackageDir,Zi as isSubdirectory,Ki as hasDirectoryIn,Qi as assignDirs,tr as isRegExp,er as stripConsoleColor,ur as LLM_TOKENIZER_NAMES,hr as LLM_TOKENIZER_NAMES_MAP,fr as getLLMTokenizer,lr as encodeLLMTokens,mr as countLLMTokens,pr as formatTextWithSpace,dr as truncateToTokenLimit,yr as truncateToTokenLimitEx,wr as truncateByToken,gr as readTextFileChunks,br as readTextFileChunksEx,kr as splitChunks,xr as YamlTypeBaseObject,Er as createYamlObjectTag,Sr as isSameString,Or as DEFAULT_CONFIG_NAME,Nr as loadConfigFile,Ir as expandConfig,Cr as loadConfig,Rr as loadAIConfig,Mr as getXDGConfigs,zr as expandPath,Fr as SHUTDOWN_SIGNALS,Br as shutdown,qr as beforeShutdown,Gr as initShutdown,w as createAbilityInjector,v as toRegExp,Ur as ToolFunc,Jr as ToolFuncSchema,es as ClientTools,ns as ClientToolFuncSchema,us as ServerTools,hs as ServerToolFuncSchema,Wr as EventToolFunc,Hr as event,Qr as SecondaryCache,Vr as _lrucache,Yr as createLRUCache,ts as lrucache,Kr as LRUCache,ss as ResClientTools,os as EventClient,as as eventClient,ls as ResServerTools,ps as EventServer,ds as eventServer,ys as registerCoreTools};
|