UNPKG

chaite

Version:

core for chatgpt-plugin and karin-plugin-chatgpt

1,597 lines (1,475 loc) 76.6 kB
/// <reference types="node" /> import { EventEmitter } from 'events'; import { UserMessage as UserMessage$1, SendMessageOption as SendMessageOption$1, ChatPreset as ChatPreset$1, ModelResponse as ModelResponse$1 } from 'src'; import { AsyncLocalStorage } from 'async_hooks'; import EventEmitter$1 from 'node:events'; type Feature = 'chat' | 'visual' | 'tool' | 'embedding'; /** * other roles like developer or function should be handled by different implementations */ type Role = 'system' | 'user' | 'assistant' | 'tool' | 'developer'; interface MessageContent { type: 'text' | 'image' | 'audio' | 'video' | 'tool' | 'reasoning'; } interface TextContent extends MessageContent { type: 'text'; /** * Content of text */ text: string; } interface ReasoningContent extends MessageContent { type: 'reasoning'; /** * thinking text */ text: string; } interface ImageContent extends MessageContent { type: 'image'; /** * Either a URL of the image or the base64 encoded image data */ image: string; mimeType?: string; } interface AudioContent extends MessageContent { type: 'audio'; /** * Base64 encoded audio data */ data: string; format: 'mp3' | 'wav'; } type History = { id: string; parentId: string | null; }; interface IMessage { role: Role; content: MessageContent[]; toolCalls?: ToolCall[]; } /** * 模型返回的工具调用,role是assistant */ interface ToolCall { id: string; type: 'function'; function: FunctionCall; } type ArgumentValue = string | number | boolean | ArgumentValue[]; type FunctionCall = { name: string; /** * raw可能是JSON字符串,需要反序列化一次 */ arguments: Record<string, ArgumentValue | Record<string, ArgumentValue>>; }; /** * 用户发送的消息,可能有文本和多模态消息 */ interface UserMessage extends IMessage { role: 'user'; content: Array<TextContent | ImageContent | AudioContent>; } interface SystemMessage extends IMessage { role: 'system'; content: TextContent[]; } interface DeveloperMessage extends IMessage { role: 'developer'; content: TextContent[]; } /** * 模型返回的消息,包括文本以及可能的工具调用 */ interface AssistantMessage extends IMessage { role: 'assistant'; content: Array<MessageContent>; toolCalls?: ToolCall[]; } interface ReasoningPart { reasoning_content?: string; reasoning?: string; thinking_content?: string; thinking?: string; think?: string; } /** * 客户端执行工具调用的函数结果 */ interface ToolCallResultMessage extends IMessage { role: 'tool'; content: ToolCallResult[]; } interface ToolCallResult extends MessageContent { type: 'tool'; tool_call_id?: string; content: string; name?: string; } type HistoryMessage = History & IMessage; interface ModelResponse { id?: string; model?: string; contents: MessageContent[]; usage?: ModelUsage; } interface ModelUsage { promptTokens?: number; completionTokens?: number; totalTokens?: number; cachedTokens?: number; reasoningTokens?: number; } interface ModelResponseChunk { id?: string; model?: string; delta: MessageContent[]; toolCall?: ToolCall[]; } interface EmbeddingResult { embeddings: Array<number>[]; } interface CloudAPIResponse<T> { code: number; data: T; msg: string; } interface PaginationResult<T> { items: T[]; pagination: { currentPage: number; pageSize: number; totalItems: number; totalPages: number; hasNextPage: boolean; hasPreviousPage: boolean; }; type: string; } interface CloudSharingService<T extends AbstractShareable<unknown>> { setUser(user: User): void; getUser(): User | null; authenticate(apiKey: string): Promise<User | null>; upload(model: Serializable): Promise<T | null>; download(shareId: string): Promise<T | null>; initializeTransfer(model: Serializable): Promise<string | null>; list(filter: Filter, query: string, searchOption: SearchOption): Promise<PaginationResult<T>>; delete(shareId: string): Promise<boolean>; } type FilterValue = string | number | boolean | FilterValue[]; type Filter = Record<string, FilterValue | Record<string, FilterValue>>; interface SearchOption { searchFields?: string[]; page?: number; pageSize?: number; } interface User { username: string; user_id: string | number; api_key?: string; github?: string; email?: string; google?: string; linux_do?: string; apple?: string; microsoft?: string; } interface Serializable { toString(): string; } interface DeSerializable<T> { fromString(str: string): T; } interface CloudModel { modelType: 'settings' | 'executable'; code?: string; name: string; id: string; cloudId?: string; embedded: boolean; description: string; uploader: User; updatedAt: string; createdAt: string; md5: string; toFormatedString(verbose?: boolean): string; } type Shareable<T> = Serializable & DeSerializable<T> & CloudModel; declare abstract class AbstractShareable<T> implements Shareable<T> { constructor(params?: Partial<AbstractShareable<T>>); modelType: 'settings' | 'executable'; code?: string; createdAt: string; description: string; embedded: boolean; id: string; cloudId?: string; name: string; uploader: User; updatedAt: string; fromString(str: string): T; toString(): string; toFormatedString(verbose?: boolean): string; md5: string; } interface Wait { ready(): Promise<void>; } declare class ProcessorDTO extends AbstractShareable<ProcessorDTO> { constructor(params: Partial<ProcessorDTO>); type: 'pre' | 'post'; fromString(str: string): ProcessorDTO; toFormatedString(_verbose?: boolean): string; } interface Processor { type: 'pre' | 'post'; name: string; } /** * 继承这个来实现一个前处理器 */ declare abstract class PreProcessor implements Processor { type: 'pre'; abstract process(message: UserMessage): Promise<UserMessage>; name: string; id: string; } /** * 继承这个来实现一个后处理器 */ declare abstract class PostProcessor implements Processor { type: 'post'; abstract process(message: AssistantMessage): Promise<AssistantMessage>; name: string; id: string; } /** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ declare enum HarmBlockMethod { HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", SEVERITY = "SEVERITY", PROBABILITY = "PROBABILITY" } /** Required. The harm block threshold. */ declare enum HarmBlockThreshold { HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", BLOCK_NONE = "BLOCK_NONE", OFF = "OFF" } /** Required. Harm category. */ declare enum HarmCategory { HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY" } /** Safety settings. */ declare interface SafetySetting { /** Determines if the harm block method uses probability or probability and severity scores. */ method?: HarmBlockMethod; /** Required. Harm category. */ category?: HarmCategory; /** Required. The harm block threshold. */ threshold?: HarmBlockThreshold; } declare class SendMessageOption implements Serializable, DeSerializable<SendMessageOption> { constructor(option: Partial<SendMessageOption>); static create(options?: SendMessageOption | Partial<SendMessageOption>): SendMessageOption; model?: string; temperature?: number; maxToken?: number; /** * 将系统提示词覆盖 */ systemOverride?: string; /** * 本轮对话禁用历史 */ disableHistoryRead?: boolean; /** * 禁用本轮对话存储到历史 */ disableHistorySave?: boolean; /** * 对话ID。如果不传则默认为第一次对话 */ conversationId?: string; /** * 上一条消息的ID,如果不传则默认为第一次对话 */ parentMessageId?: string; /** * 流模式 */ stream?: boolean; enableReasoning?: boolean; reasoningEffort?: 'high' | 'medium' | 'low'; reasoningBudgetTokens?: number; toolChoice?: ToolChoice; postProcessorIds?: string[]; preProcessorIds?: string[]; toolGroupId?: string[]; responseModalities?: string[]; safetySettings?: SafetySetting[]; /** * 流模式的回调 * @param chunk */ onChunk?(chunk: ModelResponseChunk): Promise<void>; /** * 工具调用轮次,如果有其他非tool_call类消息会被丢弃最后不会返回,但是可以通过onMessageWithToolCall来处理 * @param message */ onMessageWithToolCall?(message: MessageContent): Promise<void>; fromString(str: string): SendMessageOption; toString(): string; } interface ToolChoice { type: 'none' | 'any' | 'auto' | 'specified'; tools?: string[]; } interface EmbeddingOption { model: string; dimensions?: number; } type ClientType = 'openai' | 'gemini' | 'claude'; interface IClient { name: ClientType; features: Feature[]; tools: Tool[]; baseUrl: string; apiKey: string | string[]; multipleKeyStrategy: MultipleKeyStrategy; historyManager: HistoryManager; postProcessors?: PostProcessor[]; preProcessors?: PreProcessor[]; sendMessage(message: UserMessage | undefined, options?: SendMessageOption | Partial<SendMessageOption>): Promise<ModelResponse>; sendMessageWithHistory(history: IMessage[], options?: SendMessageOption | Partial<SendMessageOption>): Promise<IMessage & { usage: ModelUsage; }>; getEmbedding(text: string | string[], options: EmbeddingOption): Promise<EmbeddingResult>; logger: ILogger; } interface HistoryManager { name: string; saveHistory(message: HistoryMessage, conversationId: string): Promise<void>; getHistory(messageId?: string, conversationId?: string): Promise<HistoryMessage[]>; deleteConversation(conversationId: string): Promise<void>; getOneHistory(messageId: string, conversationId: string): Promise<HistoryMessage | undefined>; } declare abstract class AbstractHistoryManager implements HistoryManager { name: string; abstract saveHistory(message: HistoryMessage, conversationId: string): Promise<void>; abstract getHistory(messageId?: string, conversationId?: string): Promise<HistoryMessage[]>; abstract deleteConversation(conversationId: string): Promise<void>; abstract getOneHistory(messageId: string, conversationId: string): Promise<HistoryMessage | undefined>; } declare class DefaultChannelLoadBalancer implements ChannelsLoadBalancer { constructor(); getChannel(name: string, channels: Channel[]): Promise<Channel>; private groupByPriority; private selectByWeight; /** * 获取渠道列表及其分配的数量 * generated by qwen-2.5-max * * @param modelName 模型名称 * @param channels 渠道列表 * @param totalQuantity 总数量 * @returns 返回一个包含渠道及其分配数量的数组 */ getChannels(modelName: string, channels: Channel[], totalQuantity: number): Promise<{ channel: Channel; quantity: number; }[]>; } /** * 渠道 * 每个渠道对应一个adapter,并记录客户端的options */ declare class Channel extends AbstractShareable<Channel> implements Wait { constructor(params: Partial<Channel>); init(): Promise<void>; ready(): Promise<void>; adapterType: ClientType; options: BaseClientOptions; models: string[]; type: ClientType; weight: number; priority: number; status: 'enabled' | 'disabled'; disabledReason?: string; statistics: ChannelStatistics; fromString(str: string): Channel; toString(): string; toFormatedString(verbose?: boolean): string; } /** * 对话模式预设,最终使用的 */ declare class ChatPreset extends AbstractShareable<ChatPreset> { constructor(params?: Partial<ChatPreset>); prefix: string; local: boolean; namespace?: string; sendMessageOption: SendMessageOption; /** * 携带群聊上下文 */ groupContext?: 'disable' | 'enabled' | 'use_system'; /** * 禁止系统prompt */ disableSystemInstructions?: boolean; toString(): string; fromString(str: string): ChatPreset; toFormatedString(verbose?: boolean): string; } interface EventMessage { sender: { user_id: string; nickname?: string; card?: string; }; group: { group_id: number; }; } interface UserModeSelector { getChatPreset(e: EventMessage): Promise<ChatPreset>; } declare abstract class AbstractUserModeSelector implements UserModeSelector { abstract getChatPreset(e: EventMessage): Promise<ChatPreset>; } declare class AbstractClient implements IClient { options: BaseClientOptions; constructor(options: BaseClientOptions | Partial<BaseClientOptions>, context?: ChaiteContext); fullfillProcessors(preIds?: string[], postIds?: string[]): Promise<{ pre: PreProcessor[]; post: PostProcessor[]; }>; fullfillTools(toolGroupIds?: string[]): Promise<Tool[]>; sendMessage(message: UserMessage | undefined, options: SendMessageOption | Partial<SendMessageOption>): Promise<ModelResponse>; _sendMessage(_histories: IMessage[], _apiKey: string, _options: SendMessageOption): Promise<HistoryMessage & { usage: ModelUsage; }>; sendMessageWithHistory(history: IMessage[], options?: SendMessageOption | Partial<SendMessageOption>): Promise<IMessage & { usage: ModelUsage; }>; apiKey: string | string[]; baseUrl: string; features: Feature[]; multipleKeyStrategy: MultipleKeyStrategy; name: ClientType; tools: Tool[]; logger: ILogger; historyManager: HistoryManager; context: ChaiteContext; postProcessors?: PostProcessor[]; preProcessors?: PreProcessor[]; getEmbedding(_text: string | string[], _options: EmbeddingOption): Promise<EmbeddingResult>; } type OpenAIClientOptions = BaseClientOptions; declare class OpenAIClient extends AbstractClient { constructor(options: OpenAIClientOptions | Partial<OpenAIClientOptions>, context?: ChaiteContext); _sendMessage(histories: IMessage[], apiKey: string, options: SendMessageOption): Promise<HistoryMessage & { usage: ModelUsage; }>; getEmbedding(text: string | string[], options: EmbeddingOption): Promise<EmbeddingResult>; } type GeminiClientOptions = BaseClientOptions; declare class GeminiClient extends AbstractClient { constructor(options: GeminiClientOptions | Partial<GeminiClientOptions>, context?: ChaiteContext); _sendMessage(histories: IMessage[], apiKey: string, options: SendMessageOption): Promise<HistoryMessage & { usage: ModelUsage; }>; getEmbedding(text: string | string[], options: EmbeddingOption): Promise<EmbeddingResult>; } declare class ClaudeClient extends AbstractClient { constructor(options: GeminiClientOptions | Partial<GeminiClientOptions>, context?: ChaiteContext); _sendMessage(histories: IMessage[], apiKey: string, options: SendMessageOption): Promise<HistoryMessage & { usage: ModelUsage; }>; } declare function createClient(name: ClientType, options: BaseClientOptions | Partial<BaseClientOptions>, context?: ChaiteContext): IClient; declare const MultipleKeyStrategyChoice: { RANDOM: MultipleKeyStrategy; ROUND_ROBIN: MultipleKeyStrategy; CONVERSATION_HASH: MultipleKeyStrategy; }; type MultipleKeyStrategy = 'random' | 'round-robin' | 'conversation-hash'; declare class BaseClientOptions implements Serializable, DeSerializable<BaseClientOptions>, Wait { features: Feature[]; tools: Tool[]; baseUrl: string; apiKey: string | string[]; multipleKeyStrategy?: MultipleKeyStrategy; proxy?: string; historyManager: HistoryManager; logger?: ILogger; postProcessorIds?: string[]; private postProcessors?; preProcessorIds?: string[]; private preProcessors?; constructor(options?: Partial<BaseClientOptions>); static create(options: BaseClientOptions | Partial<BaseClientOptions>): BaseClientOptions; private initPromise; ready(): Promise<void>; setHistoryManager(historyManager: HistoryManager): void; setLogger(logger: ILogger): void; getPostProcessors(): PostProcessor[]; getPreProcessors(): PreProcessor[]; init(): Promise<void>; toString(): string; fromString(str: string): BaseClientOptions; } interface ILogger { debug(msg: object | string, ...args: never[]): void; info(msg: object | string, ...args: never[]): void; warn(msg: object | string, ...args: never[]): void; error(msg: object | string, ...args: never[]): void; } declare const DefaultLogger: { readonly name: string; readonly enableColors: boolean; formatDate(): string; formatMessage(level: string, msg: object | string, args: never[]): string; debug(msg: object | string, ...args: never[]): void; error(msg: object | string, ...args: never[]): void; info(msg: object | string, ...args: never[]): void; warn(msg: object | string, ...args: never[]): void; }; declare class ChaiteContext { constructor(logger?: ILogger); logger?: ILogger; private options?; private historyMessages?; private event?; private data?; private client?; setHistoryMessages(histories: HistoryMessage[]): void; getHistoryMessages(): HistoryMessage[] | undefined; setOptions(options: SendMessageOption): void; getOptions(): SendMessageOption | undefined; setEvent(event: EventMessage): void; getEvent(): EventMessage | undefined; setData(data: Record<string, any>): void; getData(): Record<string, any> | undefined; setClient(client: AbstractClient): void; getClient(): AbstractClient | undefined; } interface Into<U> { into(): U; } interface From<T> { from(value: T): this; } interface RAGResult { content: string; score: number; } interface Vectorizer { /** * 将文本转换为向量 * @param text 输入文本 * @returns 文本的向量表示 */ textToVector(text: string): Promise<number[]>; /** * 批量将文本转换为向量 * @param texts 输入文本数组 * @returns 文本向量数组 */ batchTextToVector(texts: string[]): Promise<number[][]>; } type CloudAPIType = 'tool' | 'processor' | 'chat-preset' | 'channel' | 'tool-group' | 'trigger'; type CustomConfigValueType = string | number | boolean | object | undefined | null | CustomConfigValueType[]; type CustomConfig = Record<string, CustomConfigValueType | Record<string, CustomConfigValueType>>; interface Function { name: string; description: string; parameters: Parameter; } interface Parameter { type: 'object'; properties: Record<string, Property>; required: string[]; } interface Property { type: 'string' | 'number' | 'boolean' | 'array' | 'object'; description: string | null; } interface Tool { name: Function['name']; type: 'function'; function: Function; run(args: Record<string, ArgumentValue | Record<string, ArgumentValue>>, chaiteContext?: ChaiteContext): Promise<string>; } declare class ToolDTO extends AbstractShareable<ToolDTO> { constructor(params: Partial<ToolDTO>); status: 'enabled' | 'disabled'; permission: 'public' | 'private' | 'onetime'; toFormatedString(_verbose?: boolean): string; fromString(str: string): ToolDTO; } /** * 工具组,与若干个工具关联 */ interface ToolsGroup { id: string; name: string; description: string; toolIds: string[]; isDefault?: boolean; } declare class ToolsGroupDTO extends AbstractShareable<ToolsGroupDTO> implements ToolsGroup { constructor(params: Partial<ToolsGroupDTO>); toolIds: string[]; isDefault?: boolean | undefined; toFormatedString(_verbose?: boolean): string; } /** * js写的工具可以继承这个抽象类 */ declare abstract class CustomTool implements Tool { constructor(); type: "function"; function: Function; run(_args: Record<string, ArgumentValue | Record<string, ArgumentValue>>, _context?: ChaiteContext): Promise<string>; name: Function["name"]; } type ParserType = 'docx' | 'xlsx' | 'pptx' | 'pdf' | 'txt' | 'other'; type TypePredicate<T> = (value: unknown) => value is T; interface Parser<T> { type: ParserType; supportedExtensions: ValidExtension[]; isCompatibleType: TypePredicate<T>; parse(document: T): Promise<string>; } type ValidExtension = `.${string}` | string; type FilePath = `${string}${ValidExtension}`; declare class DocumentPathParser implements Parser<FilePath> { isCompatibleType(value: unknown): value is string; supportedExtensions: ValidExtension[]; type: ParserType; parse(document: FilePath): Promise<string>; } declare class DocumentFileParser implements Parser<Buffer> { isCompatibleType(value: unknown): value is Buffer; supportedExtensions: ValidExtension[]; type: ParserType; parse(document: Buffer): Promise<string>; } declare class ChannelStatistics implements Serializable, DeSerializable<ChannelStatistics> { callTimes?: number; useToken?: number; perModel: Record<string, Omit<ChannelStatistics, 'perModel'>>; fromString(str: string): ChannelStatistics; toString(): string; } interface ChannelsLoadBalancer { getChannel(model: string, channels: Channel[]): Promise<Channel | null>; getChannels(model: string, channels: Channel[], totalQuantity: number): Promise<{ channel: Channel; quantity: number; }[]>; } /** * 基本存储接口 */ interface BasicStorage<T> { getName(): string; getItem(key: string): Promise<T | null>; setItem(key: string, value: T): Promise<string>; removeItem(key: string): Promise<void>; listItems(): Promise<T[]>; listItemsByEqFilter(filter: Record<string, unknown>): Promise<T[]>; listItemsByInQuery(query: Array<{ field: string; values: unknown[]; }>): Promise<T[]>; clear(): Promise<void>; } declare abstract class ChaiteStorage<T> implements BasicStorage<T> { abstract getItem(key: string): Promise<T | null>; abstract setItem(key: string, value: T): Promise<string>; abstract removeItem(key: string): Promise<void>; abstract listItems(): Promise<T[]>; abstract listItemsByEqFilter(filter: Record<string, unknown>): Promise<T[]>; abstract listItemsByInQuery(query: Array<{ field: string; values: unknown[]; }>): Promise<T[]>; abstract clear(): Promise<void>; getName(): string; } interface UserState { userId: number | string; nickname?: string; card?: string; conversations: Conversation[]; settings: UserSettings; current: { conversationId?: string; messageId?: string; }; } interface Conversation { id: string; name: string; lastMessageId: string; } interface UserSettings { preset: string; model: string; temperature: number; maxToken: number; systemOverride: string; enableReasoning: boolean; reasoningEffort: 'high' | 'medium' | 'low'; reasoningBudgetTokens: number; toolChoice: ToolChoice; } declare class ChaiteResponse<T> { private code; private data; private message; constructor(code: number, data: T, message: string); static ok<T>(data: T): ChaiteResponse<T>; static okm<T>(data: T, msg: string): ChaiteResponse<T>; static fail<T>(data: T, msg: string): ChaiteResponse<T>; static failc<T>(data: T, msg: string, code: number): ChaiteResponse<T>; } /** The callback executed by a Job */ // eslint-disable-next-line @typescript-eslint/no-invalid-void-type type JobCallback = (fireDate: Date) => void | Promise<any>; /** The Spec that is used as parms for schedule to deside when it needs to be ran */ type Spec = RecurrenceRule | RecurrenceSpecDateRange | RecurrenceSpecObjLit | Date | string | number; /** Scheduler jobs. */ declare class Job extends EventEmitter { readonly name: string; /** * Use the function scheduleJob() to create new Job objects. * * @internal * @param name either an optional name for this Job or this Job's callback * @param job either this Job's callback or an optional callback function * @param callback optional callback that is executed right before the JobCallback */ constructor(name: string | JobCallback, job?: JobCallback | (() => void), callback?: () => void); /** * Adds an Invocation to this job. For internal use. * @internal * @return whether the invocation could be added */ trackInvocation(invocation: Invocation): boolean; /** * Removes an Invocation from the tracking list of this Job. For internal use. * @internal * @return boolean whether the invocation was successful. Removing an Invocation that doesn't exist, returns false. */ stopTrackingInvocation(invocation: Invocation): boolean; /** * @internal * @return the number of currently running instances of this Job. */ triggeredJobs(): number; /** * Set the number of currently running Jobs. * @internal */ setTriggeredJobs(triggeredJobs: number): void; /** * Cancel all pending Invocations of this Job. * @param reschedule whether to reschedule the canceled Invocations. */ cancel(reschedule?: boolean): boolean; /** * Cancel the next Invocation of this Job. * @param reschedule whether to reschedule the canceled Invocation. * @return whether cancelation was successful */ cancelNext(reschedule?: boolean): boolean; /** * Changes the scheduling information for this Job. * @return whether the reschedule was successful */ reschedule(spec: Spec): boolean; /** The Date on which this Job will be run next. */ nextInvocation(): Date; /** A list of all pending Invocations. */ pendingInvocations: Invocation[]; /** Run this Job immediately. */ invoke(): void; /** Schedule this Job to be run on the specified date. */ runOnDate(date: Date): void; /** Set scheduling information */ schedule(spec: Spec): boolean; } declare class Range { constructor(start?: number, end?: number, step?: number); /** Whether the class contains the specified value. */ contains(value: number): boolean; } type Recurrence = number | Range | string; type RecurrenceSegment = Recurrence | Recurrence[]; type Timezone = string; declare class RecurrenceRule { /** * Day of the month. */ date: RecurrenceSegment; dayOfWeek: RecurrenceSegment; hour: RecurrenceSegment; minute: RecurrenceSegment; month: RecurrenceSegment; second: RecurrenceSegment; year: RecurrenceSegment; tz: Timezone; constructor( year?: RecurrenceSegment, month?: RecurrenceSegment, date?: RecurrenceSegment, dayOfWeek?: RecurrenceSegment, hour?: RecurrenceSegment, minute?: RecurrenceSegment, second?: RecurrenceSegment, tz?: Timezone, ); nextInvocationDate(base: Date): Date; isValid(): boolean; } /** * Recurrence rule specification using a date range and cron expression. */ interface RecurrenceSpecDateRange { /** * Starting date in date range. */ start?: Date | string | number | undefined; /** * Ending date in date range. */ end?: Date | string | number | undefined; /** * Cron expression string. */ rule: string; /** * Timezone */ tz?: Timezone | undefined; } /** * Recurrence rule specification using object literal syntax. */ interface RecurrenceSpecObjLit { /** * Day of the month. */ date?: RecurrenceSegment | undefined; dayOfWeek?: RecurrenceSegment | undefined; hour?: RecurrenceSegment | undefined; minute?: RecurrenceSegment | undefined; month?: RecurrenceSegment | undefined; second?: RecurrenceSegment | undefined; year?: RecurrenceSegment | undefined; /** * Timezone */ tz?: Timezone | undefined; } declare class Invocation { fireDate: Date; job: Job; recurrenceRule: RecurrenceRule; timerID: number; constructor(job: Job, fireDate: Date, recurrenceRule: RecurrenceRule); } declare class TriggerDTO extends AbstractShareable<TriggerDTO> { constructor(params: Partial<TriggerDTO>); status: 'enabled' | 'disabled'; isOneTime?: boolean; fromString(str: string): TriggerDTO; toFormatedString(verbose?: boolean): string; } interface Trigger { name: string; isOneTime?: boolean; register(context: ChaiteContext): Promise<void>; unregister(): Promise<void>; queryLLM(message: UserMessage$1, options: SendMessageOption$1 & { chatPreset?: ChatPreset$1; }): Promise<ModelResponse$1>; } declare abstract class BaseTrigger implements Trigger { name: string; isOneTime?: boolean; private triggerExecuted; constructor(params: { name: string; isOneTime?: boolean; }); protected abstract registerImpl(context: ChaiteContext): Promise<void>; protected abstract unregisterImpl(): Promise<void>; register(context: ChaiteContext): Promise<void>; unregister(): Promise<void>; protected checkOneTimeAndCleanup(): Promise<boolean>; protected triggerAction(action: () => Promise<void>): Promise<void>; queryLLM(message: UserMessage$1, options: SendMessageOption$1 & { chatPreset?: ChatPreset$1; }): Promise<ModelResponse$1>; } declare abstract class CronTrigger extends BaseTrigger { protected cronExpression: string; protected cronJob?: Job; constructor(params: { name: string; description: string; cronExpression: string; isOneTime?: boolean; }); protected registerImpl(context: ChaiteContext): Promise<void>; protected unregisterImpl(): Promise<void>; unregister(): Promise<void>; protected abstract execute(context: ChaiteContext): Promise<void>; } declare abstract class EventTrigger extends BaseTrigger { protected bot: any; protected eventName: string; protected eventHandler: (...args: any[]) => void; private isRegistered; constructor(params: { id: string; name: string; description: string; eventName: string; bot: any; isOneTime?: boolean; }); register(context: ChaiteContext): Promise<void>; unregister(): Promise<void>; protected abstract handleEvent(...args: any[]): Promise<void>; } type ExecutableSShareableType = 'tool' | 'processor'; /** * T是DTO * C是T对应的可执行的实例类型 * @interface ExecutableShareableManager */ declare abstract class ExecutableShareableManager<T extends Shareable<T>, C> { private type; private storage; private watcher; /** * 存储示例名称和文件名的映射 * @private */ protected instanceMap: Map<string, string>; /** * codeDirectory是存放实际代码的目录 * @private */ protected codeDirectory: string; cloudService?: CloudSharingService<T>; protected constructor(type: ExecutableSShareableType, codeDirectory: string, storage: BasicStorage<T>); setCloudService(cloudService: CloudSharingService<T>): void; /** * 只有可执行类型的实例才需要,如工具、处理器等。设置类不需要 * @private */ initialize(): Promise<void>; private setupFileWatcher; private scanInstances; /** * 返回实例名字们 * @returns 实例名字列表 */ listInstanceNames(): Promise<string[]>; listInstances(): Promise<T[]>; getInstanceT(id: string): Promise<T | null>; /** * 获取实例对象而非Shareable DTO * @param name */ getInstance(name: string): Promise<C | undefined>; /** * 新增或更新 * 有id就是更新,靠storage实现去控制,这里不管 * @param instance * @return id */ addInstance(instance: T): Promise<string>; addInstanceCode(name: string, code: string): Promise<void>; upsertInstanceT(t: T): Promise<string>; getInstanceTByCloudId(cloudId: string): Promise<T[]>; renameFile(id: string, oldName: string, newName: string): Promise<void>; deleteInstance(id: string): Promise<void>; /** * 序列化实例,返回DTO * @param name */ abstract serializeInstance(name: string): Promise<T | null>; private checkCloudService; shareToCloud(id: string): Promise<string | undefined>; listFromCloud(filter: Filter, query: string, searchOption: SearchOption): Promise<PaginationResult<T & { downloaded: string; }>>; getFromCloud(shareId: string): Promise<T | null>; shareP2P(name: string): Promise<string | null>; dispose(): Promise<void>; } type NonExecutableSShareableType = 'chat-preset' | 'tool-settings' | 'channel' | 'tools-group'; declare abstract class NonExecutableShareableManager<T extends Shareable<T>> { protected type: NonExecutableSShareableType; protected storage: BasicStorage<T>; cloudService?: CloudSharingService<T>; protected constructor(type: NonExecutableSShareableType, storage: BasicStorage<T>); setCloudService(cloudService: CloudSharingService<T>): void; addInstance(instance: T): Promise<string>; deleteInstance(key: string): Promise<void>; listInstances(): Promise<T[]>; getInstance(key: string): Promise<T | null>; upsertInstance(t: T): Promise<string>; getInstanceByCloudId(cloudId: string): Promise<T[]>; private checkCloudService; shareToCloud(key: string): Promise<string | undefined>; shareP2P(key: string): Promise<string | null>; getFromCloud(shareId: string): Promise<T | null>; listFromCloud(filter: Filter, query: string, searchOption: SearchOption): Promise<PaginationResult<T & { id: string; }>>; deleteFromCloud(key: string): Promise<void>; } declare class ToolManager extends ExecutableShareableManager<ToolDTO, Tool> { private static instance; private constructor(); setCloudService(cloudService: CloudSharingService<ToolDTO>): void; static init(toolsDirectory: string, storage: BasicStorage<ToolDTO>): Promise<ToolManager>; static getInstance(): Promise<ToolManager | null>; serializeInstance(name: string): Promise<ToolDTO | null>; } declare function getKey(apiKeys: string[] | string, strategy: MultipleKeyStrategy): Promise<string>; declare const asyncLocalStorage: AsyncLocalStorage<ChaiteContext>; declare function useEvent(): Promise<EventMessage | undefined>; /** * 表示构造函数的类型 */ type AbstractConstructor<T> = abstract new (...args: unknown[]) => T; /** * 将JS代码保存到指定目录并导入其默认导出 * * @param {string} jsContent - JS代码内容 * @param {string} modulesDir - 保存模块的目录 * @param {string} fileName - 文件名(不含路径) * @param {Function} AbstractClass - 抽象类,用于检查实例是否继承自它 * @returns {Promise<T | null>} 如果默认导出继承自AbstractClass则返回该实例,否则返回null */ declare function saveAndLoadModule<T>(jsContent: string, modulesDir: string, fileName: string, AbstractClass: AbstractConstructor<T>): Promise<T | null>; declare function getLogger(): ILogger; /** * 解析 JavaScript 代码中的 class 变量 name 的值 * @param {string} code - 输入的 JavaScript 代码 * @returns {string|null} - 解析出的 class 的 name 值,或者 null 如果没有找到 */ declare function extractClassName(code: string): string | null; interface KVStore { get(key: string): Promise<string>; set(key: string, value: string): Promise<void>; delete(key: string): Promise<void>; } declare class KVHistoryManager implements HistoryManager { private kvStore; name: string; constructor(kvStore: KVStore, name: string); private getConversationKey; private getMessageKey; saveHistory(message: HistoryMessage, conversationId: string): Promise<void>; getHistory(messageId?: string, conversationId?: string): Promise<HistoryMessage[]>; deleteConversation(conversationId: string): Promise<void>; getOneHistory(messageId: string, conversationId: string): Promise<HistoryMessage | undefined>; } type HistoryCache = Map<string, Map<string, HistoryMessage>>; declare class InMemoryHistoryManager extends AbstractHistoryManager { cache: HistoryCache; constructor(); saveHistory(message: HistoryMessage, conversationId: string): Promise<void>; getHistory(messageId?: string, conversationId?: string): Promise<HistoryMessage[]>; deleteConversation(conversationId: string): Promise<void>; getOneHistory(messageId: string, conversationId: string): Promise<HistoryMessage | undefined>; name: string; } // TypeScript Version: 4.7 type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; interface RawAxiosHeaders { [key: string]: AxiosHeaderValue; } type MethodsHeaders = Partial<{ [Key in Method as Lowercase<Key>]: AxiosHeaders; } & {common: AxiosHeaders}>; type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean); type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any; declare class AxiosHeaders { constructor( headers?: RawAxiosHeaders | AxiosHeaders | string ); [key: string]: any; set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders; get(headerName: string, parser: RegExp): RegExpExecArray | null; get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue; has(header: string, matcher?: AxiosHeaderMatcher): boolean; delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; clear(matcher?: AxiosHeaderMatcher): boolean; normalize(format: boolean): AxiosHeaders; concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders; toJSON(asStrings?: boolean): RawAxiosHeaders; static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; static accessor(header: string | string[]): AxiosHeaders; static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders; setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentType(parser?: RegExp): RegExpExecArray | null; getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentType(matcher?: AxiosHeaderMatcher): boolean; setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentLength(parser?: RegExp): RegExpExecArray | null; getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentLength(matcher?: AxiosHeaderMatcher): boolean; setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getAccept(parser?: RegExp): RegExpExecArray | null; getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasAccept(matcher?: AxiosHeaderMatcher): boolean; setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getUserAgent(parser?: RegExp): RegExpExecArray | null; getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentEncoding(parser?: RegExp): RegExpExecArray | null; getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getAuthorization(parser?: RegExp): RegExpExecArray | null; getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; getSetCookie(): string[]; [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>; } type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization'; type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream'; type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & { [Key in CommonRequestHeadersList]: AxiosHeaderValue; } & { 'Content-Type': ContentType }>; type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding'; type RawCommonResponseHeaders = { [Key in CommonResponseHeadersList]: AxiosHeaderValue; } & { "set-cookie": string[]; }; type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>; type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; interface AxiosRequestTransformer { (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; } interface AxiosResponseTransformer { (this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any; } interface AxiosAdapter { (config: InternalAxiosRequestConfig): AxiosPromise; } interface AxiosBasicCredentials { username: string; password: string; } interface AxiosProxyConfig { host: string; port: number; auth?: AxiosBasicCredentials; protocol?: string; } declare enum HttpStatusCode { Continue = 100, SwitchingProtocols = 101, Processing = 102, EarlyHints = 103, Ok = 200, Created = 201, Accepted = 202, NonAuthoritativeInformation = 203, NoContent = 204, ResetContent = 205, PartialContent = 206, MultiStatus = 207, AlreadyReported = 208, ImUsed = 226, MultipleChoices = 300, MovedPermanently = 301, Found = 302, SeeOther = 303, NotModified = 304, UseProxy = 305, Unused = 306, TemporaryRedirect = 307, PermanentRedirect = 308, BadRequest = 400, Unauthorized = 401, PaymentRequired = 402, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, ProxyAuthenticationRequired = 407, RequestTimeout = 408, Conflict = 409, Gone = 410, LengthRequired = 411, PreconditionFailed = 412, PayloadTooLarge = 413, UriTooLong = 414, UnsupportedMediaType = 415, RangeNotSatisfiable = 416, ExpectationFailed = 417, ImATeapot = 418, MisdirectedRequest = 421, UnprocessableEntity = 422, Locked = 423, FailedDependency = 424, TooEarly = 425, UpgradeRequired = 426, PreconditionRequired = 428, TooManyRequests = 429, RequestHeaderFieldsTooLarge = 431, UnavailableForLegalReasons = 451, InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, GatewayTimeout = 504, HttpVersionNotSupported = 505, VariantAlsoNegotiates = 506, InsufficientStorage = 507, LoopDetected = 508, NotExtended = 510, NetworkAuthenticationRequired = 511, } type Method = | 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK'; type ResponseType = | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' | 'formdata'; type responseEncoding = | 'ascii' | 'ASCII' | 'ansi' | 'ANSI' | 'binary' | 'BINARY' | 'base64' | 'BASE64' | 'base64url' | 'BASE64URL' | 'hex' | 'HEX' | 'latin1' | 'LATIN1' | 'ucs-2' | 'UCS-2' | 'ucs2' | 'UCS2' | 'utf-8' | 'UTF-8' | 'utf8' | 'UTF8' | 'utf16le' | 'UTF16LE'; interface TransitionalOptions { silentJSONParsing?: boolean; forcedJSONParsing?: boolean; clarifyTimeoutError?: boolean; } interface GenericAbortSignal { readonly aborted: boolean; onabort?: ((...args: any) => any) | null; addEventListener?: (...args: any) => any; removeEventListener?: (...args: any) => any; } interface FormDataVisitorHelpers { defaultVisitor: SerializerVisitor; convertValue: (value: any) => any; isVisitable: (value: any) => boolean; } interface SerializerVisitor { ( this: GenericFormData, value: any, key: string | number, path: null | Array<string | number>, helpers: FormDataVisitorHelpers ): boolean; } interface SerializerOptions { visitor?: SerializerVisitor; dots?: boolean; metaTokens?: boolean; indexes?: boolean | null; } // tslint:disable-next-line interface FormSerializerOptions extends SerializerOptions { } interface ParamEncoder { (value: any, defaultEncoder: (value: any) => any): any; } interface CustomParamsSerializer { (params: Record<string, any>, options?: ParamsSerializerOptions): string; } interface ParamsSerializerOptions extends SerializerOptions { encode?: ParamEncoder; serialize?: CustomParamsSerializer; } type MaxUploadRate = number; type MaxDownloadRate = number; type BrowserProgressEvent = any; interface AxiosProgressEvent { loaded: number; total?: number; progress?: number; bytes: number; rate?: number; estimated?: number; upload?: boolean; download?: boolean; event?: BrowserProgressEvent; lengthComputable: boolean; } type Milliseconds = number; type AxiosAdapterName = 'fetch' | 'xhr' | 'http' | (string & {}); type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; type AddressFamily = 4 | 6 | undefined; interface LookupAddressEntry { address: string; family?: AddressFamily; } type LookupAddress = string | LookupAddressEntry; interface AxiosRequestConfig<D = any> { url?: string; method?: Method | string; baseURL?: string; allowAbsoluteUrls?: boolean; transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; params?: any; paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer; data?: D; timeout?: Milliseconds; timeoutErrorMessage?: string; withCredentials?: boolean; adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; auth?: AxiosBasicCredentials; responseType?: ResponseType; responseEncoding?: responseEncoding | string; xsrfCookieName?: string; xsrfHeaderName?: string; onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; maxContentLength?: number; validateStatus?: ((status: number) => boolean) | null; maxBodyLength?: number; maxRedirects?: number; maxRate?: number | [MaxUploadRate, MaxDownloadRate]; beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>, statusCode: HttpStatusCode}) => void; socketPath?: string | null; transport?: any; httpAgent?: any; httpsAgent?: any; proxy?: AxiosProxyConfig | false; cancelToken?: CancelToken; decompress?: boolean; transitional?: TransitionalOptions; signal?: GenericAbortSignal; insecureHTTPParser?: boolean; env?: { FormData?: new (...args: any[]) => object; }; formSerializer?: FormSerializerOptions; family?: AddressFamily; lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) | ((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>); withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined); fetchOptions?: Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'> | Record<string, any>; } interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> { headers: AxiosRequestHeaders; } interface HeadersDefaults { common: RawAxiosRequestHeaders; delete: RawAxiosRequestHeaders; get: RawAxiosRequestHeaders; head: RawAxiosRequestHeaders; post: RawAxiosRequestHeaders; put: RawAxiosRequestHeaders; patch: RawAxiosRequestHeaders; options?: RawAxiosRequestHeaders; purge?: RawAxiosRequestHeaders; link?: RawAxiosRequestHeaders; unlink?: RawAxiosRequestHeaders; } interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> { headers: HeadersDefaults; } interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> { headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>; } interface AxiosResponse<T = any, D = any> { data: T; status: number; statusText: string; headers: RawAxiosResponseHeaders | AxiosResponseHeaders; config: InternalAxiosRequestConfig<D>; request?: any; } declare class AxiosError<T = unknown, D = any> extends Error { constructor( message?: string, code?: string, config?: InternalAxiosRequestConfig<D>, request?: any, response?: AxiosResponse<T, D> ); config?: InternalAxiosRequestConfig<D>; code?: string; request?: any; response?: AxiosResponse<T, D>; isAxiosError: boolean; status?: number; toJSON: () => object; cause?: Error; static from<T = unknown, D = any>( error: Error | unknown, code?: string, config?: InternalAxiosRequestConfig<D>, request?: any, response?: AxiosResponse<T, D>, customProps?: object, ): AxiosError<T, D>; static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; static readonly ERR_NETWORK = "ERR_NETWORK"; static readonly ERR_DEPRECATED = "ERR_DEPRECATED"; static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; static readonly E