koishi-plugin-chatluna 1.3.13 → 1.3.15

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.
@@ -22,4 +22,4 @@ export type CreateOpenAIAgentParams = {
22
22
  };
23
23
  export declare function createOpenAIAgent({ llm, tools, prompt }: CreateOpenAIAgentParams): RunnableSequence<{
24
24
  steps: AgentStep[];
25
- }, AgentAction | AgentFinish | AgentAction[]>;
25
+ }, AgentAction | AgentAction[] | AgentFinish>;
@@ -12,7 +12,7 @@ export declare class OpenAIFunctionsAgentOutputParser extends AgentActionOutputP
12
12
  lc_namespace: string[];
13
13
  static lc_name(): string;
14
14
  parse(text: string): Promise<AgentAction | AgentFinish>;
15
- parseResult(generations: ChatGeneration[]): Promise<FunctionsAgentAction | AgentFinish>;
15
+ parseResult(generations: ChatGeneration[]): Promise<AgentFinish | FunctionsAgentAction>;
16
16
  /**
17
17
  * Parses the output message into a FunctionsAgentAction or AgentFinish
18
18
  * object.
@@ -72,7 +72,7 @@ export type CreateReactAgentParams = {
72
72
  */
73
73
  export declare function createReactAgent({ llm, tools, prompt, streamRunnable, instructions }: CreateReactAgentParams): AgentRunnableSequence<{
74
74
  steps: AgentStep[];
75
- }, import("koishi-plugin-chatluna/llm-core/agent").AgentFinish | import("koishi-plugin-chatluna/llm-core/agent").AgentAction[]>;
75
+ }, import("koishi-plugin-chatluna/llm-core/agent").AgentAction[] | import("koishi-plugin-chatluna/llm-core/agent").AgentFinish>;
76
76
  /**
77
77
  * Construct the scratchpad that lets the agent continue its thought process.
78
78
  * @param intermediateSteps
@@ -584,7 +584,7 @@ var ChatInterface = class {
584
584
  }
585
585
  async processChat(arg, wrapper) {
586
586
  try {
587
- if (this.ctx.chatluna.config.infiniteContext) {
587
+ if (this.ctx.chatluna.currentConfig.infiniteContext) {
588
588
  const manager = this._ensureInfiniteContextManager();
589
589
  await manager?.compressIfNeeded(wrapper);
590
590
  }
@@ -615,7 +615,7 @@ var ChatInterface = class {
615
615
  if (messageContent.trim().length > 0) {
616
616
  await this.chatHistory.addMessage(arg.message);
617
617
  let saveMessage = responseMessage;
618
- if (!this.ctx.chatluna.config.rawOnCensor) {
618
+ if (!this.ctx.chatluna.currentConfig.rawOnCensor) {
619
619
  saveMessage = displayResponse;
620
620
  }
621
621
  if (Array.isArray(response.parallelIntermediateSteps) && response.parallelIntermediateSteps.length > 0) {
@@ -885,7 +885,7 @@ var ChatInterface = class {
885
885
  chatHistory: this._chatHistory,
886
886
  conversationId: this._input.conversationId,
887
887
  preset: this._input.preset,
888
- threshold: this.ctx.chatluna.config.infiniteContextThreshold
888
+ threshold: this.ctx.chatluna.currentConfig.infiniteContextThreshold
889
889
  });
890
890
  }
891
891
  return this._infiniteContextManager;
@@ -578,7 +578,7 @@ var ChatInterface = class {
578
578
  }
579
579
  async processChat(arg, wrapper) {
580
580
  try {
581
- if (this.ctx.chatluna.config.infiniteContext) {
581
+ if (this.ctx.chatluna.currentConfig.infiniteContext) {
582
582
  const manager = this._ensureInfiniteContextManager();
583
583
  await manager?.compressIfNeeded(wrapper);
584
584
  }
@@ -609,7 +609,7 @@ var ChatInterface = class {
609
609
  if (messageContent.trim().length > 0) {
610
610
  await this.chatHistory.addMessage(arg.message);
611
611
  let saveMessage = responseMessage;
612
- if (!this.ctx.chatluna.config.rawOnCensor) {
612
+ if (!this.ctx.chatluna.currentConfig.rawOnCensor) {
613
613
  saveMessage = displayResponse;
614
614
  }
615
615
  if (Array.isArray(response.parallelIntermediateSteps) && response.parallelIntermediateSteps.length > 0) {
@@ -879,7 +879,7 @@ var ChatInterface = class {
879
879
  chatHistory: this._chatHistory,
880
880
  conversationId: this._input.conversationId,
881
881
  preset: this._input.preset,
882
- threshold: this.ctx.chatluna.config.infiniteContextThreshold
882
+ threshold: this.ctx.chatluna.currentConfig.infiniteContextThreshold
883
883
  });
884
884
  }
885
885
  return this._infiniteContextManager;
@@ -1198,6 +1198,7 @@ var ChatLunaService = class extends import_koishi4.Service {
1198
1198
  _messageTransformer;
1199
1199
  _renderer;
1200
1200
  _promptRenderer;
1201
+ config;
1201
1202
  async installPlugin(plugin) {
1202
1203
  const platformName = plugin.platformName;
1203
1204
  if (this._plugins[platformName]) {
@@ -1823,7 +1824,7 @@ var ChatInterfaceWrapper = class {
1823
1824
  const reasoningContent = aiMessage.additional_kwargs?.reasoning_content;
1824
1825
  const reasoningTime = aiMessage.additional_kwargs?.reasoning_time;
1825
1826
  const additionalReplyMessages = [];
1826
- if (reasoningContent != null && reasoningContent.length > 0 && this._service.config.showThoughtMessage) {
1827
+ if (reasoningContent != null && reasoningContent.length > 0 && this._service.currentConfig.showThoughtMessage) {
1827
1828
  additionalReplyMessages.push({
1828
1829
  content: `Thought for ${reasoningTime / 1e3} seconds:
1829
1830
 
@@ -1968,7 +1969,7 @@ ${reasoningContent}`
1968
1969
  this._platformToConversations.delete(platform);
1969
1970
  }
1970
1971
  async _createChatInterface(room) {
1971
- const config = this._service.config;
1972
+ const config = this._service.currentConfig;
1972
1973
  const chatInterface = new import_app.ChatInterface(this._service.ctx.root, {
1973
1974
  chatMode: room.chatMode,
1974
1975
  botName: config.botNames[0],
@@ -1,211 +1,127 @@
1
- import {
2
- Awaitable,
3
- Computed,
4
- Context,
5
- Dict,
6
- Schema,
7
- Service,
8
- Session
9
- } from 'koishi'
10
- import { ChatInterface } from 'koishi-plugin-chatluna/llm-core/chat/app'
11
- import { Cache } from '../cache'
12
- import { ChatChain } from '../chains/chain'
13
- import { ChatLunaLLMChainWrapper } from 'koishi-plugin-chatluna/llm-core/chain/base'
14
- import { BasePlatformClient } from 'koishi-plugin-chatluna/llm-core/platform/client'
15
- import {
16
- ClientConfig,
17
- ClientConfigPool
18
- } from 'koishi-plugin-chatluna/llm-core/platform/config'
19
- import { ChatLunaChatModel } from 'koishi-plugin-chatluna/llm-core/platform/model'
20
- import { PlatformService } from 'koishi-plugin-chatluna/llm-core/platform/service'
21
- import {
22
- ChatLunaTool,
23
- CreateChatLunaLLMChainParams,
24
- CreateVectorStoreFunction,
25
- PlatformClientNames
26
- } from 'koishi-plugin-chatluna/llm-core/platform/types'
27
- import { PresetService } from 'koishi-plugin-chatluna/preset'
28
- import { ConversationRoom, Message } from '../types'
29
- import { MessageTransformer } from './message_transform'
30
- import { ChatEvents } from './types'
31
- import * as fetchType from 'undici/types/fetch'
32
- import { ClientOptions, WebSocket } from 'ws'
33
- import { ClientRequestArgs } from 'http'
34
- import { Config } from '../config'
35
- import { DefaultRenderer, Renderer } from 'koishi-plugin-chatluna'
36
- import type { PostHandler } from '../utils/types'
37
- import { ChatLunaPromptRenderService } from './prompt_renderer'
38
- import { ComputedRef } from '@vue/reactivity'
39
- import { Embeddings } from '@langchain/core/embeddings'
40
- export declare class ChatLunaService extends Service {
41
- readonly ctx: Context
42
- currentConfig: Config
43
- private _plugins
44
- private _chatInterfaceWrapper
45
- private readonly _chain
46
- private readonly _keysCache
47
- private readonly _preset
48
- private readonly _platformService
49
- private readonly _messageTransformer
50
- private readonly _renderer
51
- private readonly _promptRenderer
52
- constructor(ctx: Context, config: Config)
53
- installPlugin(plugin: ChatLunaPlugin): Promise<void>
54
- awaitLoadPlatform(
55
- plugin: ChatLunaPlugin | string,
56
- timeout?: number
57
- ): Promise<void>
58
-
59
- uninstallPlugin(plugin: ChatLunaPlugin | string): void
60
- getPlugin(
61
- platformName: string
62
- ): ChatLunaPlugin<ClientConfig, ChatLunaPlugin.Config>
63
-
1
+ import { Awaitable, Computed, Context, Dict, Schema, Service, Session } from 'koishi';
2
+ import { ChatInterface } from 'koishi-plugin-chatluna/llm-core/chat/app';
3
+ import { Cache } from '../cache';
4
+ import { ChatChain } from '../chains/chain';
5
+ import { ChatLunaLLMChainWrapper } from 'koishi-plugin-chatluna/llm-core/chain/base';
6
+ import { BasePlatformClient } from 'koishi-plugin-chatluna/llm-core/platform/client';
7
+ import { ClientConfig, ClientConfigPool } from 'koishi-plugin-chatluna/llm-core/platform/config';
8
+ import { ChatLunaChatModel } from 'koishi-plugin-chatluna/llm-core/platform/model';
9
+ import { PlatformService } from 'koishi-plugin-chatluna/llm-core/platform/service';
10
+ import { ChatLunaTool, CreateChatLunaLLMChainParams, CreateVectorStoreFunction, PlatformClientNames } from 'koishi-plugin-chatluna/llm-core/platform/types';
11
+ import { PresetService } from 'koishi-plugin-chatluna/preset';
12
+ import { ConversationRoom, Message } from '../types';
13
+ import { MessageTransformer } from './message_transform';
14
+ import { ChatEvents } from './types';
15
+ import * as fetchType from 'undici/types/fetch';
16
+ import { ClientOptions, WebSocket } from 'ws';
17
+ import { ClientRequestArgs } from 'http';
18
+ import { Config } from '../config';
19
+ import { DefaultRenderer, Renderer } from 'koishi-plugin-chatluna';
20
+ import type { PostHandler } from '../utils/types';
21
+ import { ChatLunaPromptRenderService } from './prompt_renderer';
22
+ import { ComputedRef } from '@vue/reactivity';
23
+ import { Embeddings } from '@langchain/core/embeddings';
24
+ export declare class ChatLunaService extends Service<Config> {
25
+ readonly ctx: Context;
26
+ private _plugins;
27
+ private _chatInterfaceWrapper;
28
+ private readonly _chain;
29
+ private readonly _keysCache;
30
+ private readonly _preset;
31
+ private readonly _platformService;
32
+ private readonly _messageTransformer;
33
+ private readonly _renderer;
34
+ private readonly _promptRenderer;
35
+ config: Config;
36
+ constructor(ctx: Context, config: Config);
37
+ installPlugin(plugin: ChatLunaPlugin): Promise<void>;
38
+ awaitLoadPlatform(plugin: ChatLunaPlugin | string, timeout?: number): Promise<void>;
39
+ uninstallPlugin(plugin: ChatLunaPlugin | string): void;
40
+ getPlugin(platformName: string): ChatLunaPlugin<ClientConfig, ChatLunaPlugin.Config>;
64
41
  /**
65
42
  * @internal
66
43
  */
67
- chat(
68
- session: Session,
69
- room: ConversationRoom,
70
- message: Message,
71
- event: ChatEvents,
72
- stream?: boolean,
73
- variables?: Record<string, any>,
74
- postHandler?: PostHandler,
75
- requestId?: string
76
- ): Promise<Message>
77
-
78
- stopChat(room: ConversationRoom, requestId: string): Promise<boolean>
79
- queryInterfaceWrapper(
80
- room: ConversationRoom,
81
- autoCreate?: boolean
82
- ): ChatInterfaceWrapper
83
-
84
- clearChatHistory(room: ConversationRoom): Promise<void>
85
- compressContext(room: ConversationRoom): Promise<boolean>
86
- getCachedInterfaceWrapper(): ChatInterfaceWrapper
87
- clearCache(room: ConversationRoom): Promise<boolean>
88
- createChatModel(
89
- platform: string,
90
- modelName: string
91
- ): Promise<ComputedRef<ChatLunaChatModel | undefined>>
92
-
93
- createChatModel(
94
- fullModelName: string
95
- ): Promise<ComputedRef<ChatLunaChatModel | undefined>>
96
-
97
- createEmbeddings(
98
- platformName: string,
99
- modelName: string
100
- ): Promise<ComputedRef<Embeddings | undefined>>
101
-
102
- createEmbeddings(
103
- fullModelName: string
104
- ): Promise<ComputedRef<Embeddings | undefined>>
105
-
106
- get platform(): PlatformService
107
- get cache(): Cache<'chatluna/keys', string>
108
- get preset(): PresetService
109
- get chatChain(): ChatChain
110
- get messageTransformer(): MessageTransformer
111
- get renderer(): DefaultRenderer
112
- get promptRenderer(): ChatLunaPromptRenderService
113
- protected stop(): Promise<void>
114
- private _createTempDir
115
- private _defineDatabase
116
- private _createChatInterfaceWrapper
117
- static inject: string[]
44
+ chat(session: Session, room: ConversationRoom, message: Message, event: ChatEvents, stream?: boolean, variables?: Record<string, any>, postHandler?: PostHandler, requestId?: string): Promise<Message>;
45
+ stopChat(room: ConversationRoom, requestId: string): Promise<boolean>;
46
+ queryInterfaceWrapper(room: ConversationRoom, autoCreate?: boolean): ChatInterfaceWrapper;
47
+ clearChatHistory(room: ConversationRoom): Promise<void>;
48
+ compressContext(room: ConversationRoom): Promise<boolean>;
49
+ getCachedInterfaceWrapper(): ChatInterfaceWrapper;
50
+ clearCache(room: ConversationRoom): Promise<boolean>;
51
+ createChatModel(platform: string, modelName: string): Promise<ComputedRef<ChatLunaChatModel | undefined>>;
52
+ createChatModel(fullModelName: string): Promise<ComputedRef<ChatLunaChatModel | undefined>>;
53
+ createEmbeddings(platformName: string, modelName: string): Promise<ComputedRef<Embeddings | undefined>>;
54
+ createEmbeddings(fullModelName: string): Promise<ComputedRef<Embeddings | undefined>>;
55
+ get platform(): PlatformService;
56
+ get cache(): Cache<"chatluna/keys", string>;
57
+ get preset(): PresetService;
58
+ get chatChain(): ChatChain;
59
+ get messageTransformer(): MessageTransformer;
60
+ get renderer(): DefaultRenderer;
61
+ get promptRenderer(): ChatLunaPromptRenderService;
62
+ protected stop(): Promise<void>;
63
+ private _createTempDir;
64
+ private _defineDatabase;
65
+ private _createChatInterfaceWrapper;
66
+ static inject: string[];
118
67
  }
119
- export declare class ChatLunaPlugin<
120
- R extends ClientConfig = ClientConfig,
121
- T extends ChatLunaPlugin.Config = ChatLunaPlugin.Config
122
- > {
123
- protected ctx: Context
124
- readonly config: T
125
- platformName: PlatformClientNames
126
- private _supportModels
127
- readonly platformConfigPool: ClientConfigPool<R>
128
- private _platformService
129
- constructor(
130
- ctx: Context,
131
- config: T,
132
- platformName: PlatformClientNames,
133
- createConfigPool?: boolean
134
- )
135
-
136
- parseConfig(f: (config: T) => R[]): void
137
- private createRunnableConfig
138
- initClient(): Promise<void>
139
- get supportedModels(): readonly string[]
140
- registerToService(): void
141
- registerClient(func: () => BasePlatformClient, platformName?: string): void
142
- registerVectorStore(name: string, func: CreateVectorStoreFunction): void
143
- registerTool(name: string, tool: ChatLunaTool): void
144
- registerChatChainProvider(
145
- name: string,
146
- description: Dict<string>,
147
- func: (params: CreateChatLunaLLMChainParams) => ChatLunaLLMChainWrapper
148
- ): void
149
-
150
- registerRenderer(
151
- name: string,
152
- renderer: (ctx: Context, config: Config) => Renderer
153
- ): void
154
-
155
- fetch(
156
- info: fetchType.RequestInfo,
157
- init?: fetchType.RequestInit,
158
- proxy?: string
159
- ): Promise<fetchType.Response>
160
-
161
- ws(url: string, options?: ClientOptions | ClientRequestArgs): WebSocket
68
+ export declare class ChatLunaPlugin<R extends ClientConfig = ClientConfig, T extends ChatLunaPlugin.Config = ChatLunaPlugin.Config> {
69
+ protected ctx: Context;
70
+ readonly config: T;
71
+ platformName: PlatformClientNames;
72
+ private _supportModels;
73
+ readonly platformConfigPool: ClientConfigPool<R>;
74
+ private _platformService;
75
+ constructor(ctx: Context, config: T, platformName: PlatformClientNames, createConfigPool?: boolean);
76
+ parseConfig(f: (config: T) => R[]): void;
77
+ private createRunnableConfig;
78
+ initClient(): Promise<void>;
79
+ get supportedModels(): readonly string[];
80
+ registerToService(): void;
81
+ registerClient(func: () => BasePlatformClient, platformName?: string): void;
82
+ registerVectorStore(name: string, func: CreateVectorStoreFunction): void;
83
+ registerTool(name: string, tool: ChatLunaTool): void;
84
+ registerChatChainProvider(name: string, description: Dict<string>, func: (params: CreateChatLunaLLMChainParams) => ChatLunaLLMChainWrapper): void;
85
+ registerRenderer(name: string, renderer: (ctx: Context, config: Config) => Renderer): void;
86
+ fetch(info: fetchType.RequestInfo, init?: fetchType.RequestInit, proxy?: string): Promise<fetchType.Response>;
87
+ ws(url: string, options?: ClientOptions | ClientRequestArgs): WebSocket;
162
88
  }
163
89
  type ChatHubChatBridgerInfo = {
164
- chatInterface: ChatInterface
165
- room: ConversationRoom
166
- }
90
+ chatInterface: ChatInterface;
91
+ room: ConversationRoom;
92
+ };
167
93
  declare class ChatInterfaceWrapper {
168
- private _service
169
- private _conversations
170
- private _modelQueue
171
- private _conversationQueue
172
- private _platformService
173
- private _requestIdMap
174
- private _platformToConversations
175
- constructor(_service: ChatLunaService)
176
- chat(
177
- session: Session,
178
- room: ConversationRoom,
179
- message: Message,
180
- event: ChatEvents,
181
- stream: boolean,
182
- requestId: string,
183
- variables?: Record<string, any>,
184
- postHandler?: PostHandler
185
- ): Promise<Message>
186
-
187
- stopChat(requestId: string): boolean
188
- query(room: ConversationRoom, create?: boolean): Promise<ChatInterface>
189
- clearChatHistory(room: ConversationRoom): Promise<void>
190
- compressContext(room: ConversationRoom): Promise<boolean>
191
- clearCache(room: ConversationRoom): Promise<boolean>
192
- getCachedConversations(): [string, ChatHubChatBridgerInfo][]
193
- delete(room: ConversationRoom): Promise<void>
194
- dispose(platform?: string): void
195
- private _createChatInterface
94
+ private _service;
95
+ private _conversations;
96
+ private _modelQueue;
97
+ private _conversationQueue;
98
+ private _platformService;
99
+ private _requestIdMap;
100
+ private _platformToConversations;
101
+ constructor(_service: ChatLunaService);
102
+ chat(session: Session, room: ConversationRoom, message: Message, event: ChatEvents, stream: boolean, requestId: string, variables?: Record<string, any>, postHandler?: PostHandler): Promise<Message>;
103
+ stopChat(requestId: string): boolean;
104
+ query(room: ConversationRoom, create?: boolean): Promise<ChatInterface>;
105
+ clearChatHistory(room: ConversationRoom): Promise<void>;
106
+ compressContext(room: ConversationRoom): Promise<boolean>;
107
+ clearCache(room: ConversationRoom): Promise<boolean>;
108
+ getCachedConversations(): [string, ChatHubChatBridgerInfo][];
109
+ delete(room: ConversationRoom): Promise<void>;
110
+ dispose(platform?: string): void;
111
+ private _createChatInterface;
196
112
  }
197
113
  export declare namespace ChatLunaPlugin {
198
114
  interface Config {
199
- chatConcurrentMaxSize?: number
200
- chatTimeLimit?: Computed<Awaitable<number>>
201
- timeout?: number
202
- configMode: string
203
- maxRetries: number
204
- proxyMode: string
205
- proxyAddress: string
115
+ chatConcurrentMaxSize?: number;
116
+ chatTimeLimit?: Computed<Awaitable<number>>;
117
+ timeout?: number;
118
+ configMode: string;
119
+ maxRetries: number;
120
+ proxyMode: string;
121
+ proxyAddress: string;
206
122
  }
207
- const Config: Schema<ChatLunaPlugin.Config>
123
+ const Config: Schema<ChatLunaPlugin.Config>;
208
124
  }
209
- export * from './prompt_renderer'
210
- export * from './types'
211
- export * from './message_transform'
125
+ export * from './prompt_renderer';
126
+ export * from './types';
127
+ export * from './message_transform';
@@ -1223,6 +1223,7 @@ var ChatLunaService = class extends Service {
1223
1223
  _messageTransformer;
1224
1224
  _renderer;
1225
1225
  _promptRenderer;
1226
+ config;
1226
1227
  async installPlugin(plugin) {
1227
1228
  const platformName = plugin.platformName;
1228
1229
  if (this._plugins[platformName]) {
@@ -1848,7 +1849,7 @@ var ChatInterfaceWrapper = class {
1848
1849
  const reasoningContent = aiMessage.additional_kwargs?.reasoning_content;
1849
1850
  const reasoningTime = aiMessage.additional_kwargs?.reasoning_time;
1850
1851
  const additionalReplyMessages = [];
1851
- if (reasoningContent != null && reasoningContent.length > 0 && this._service.config.showThoughtMessage) {
1852
+ if (reasoningContent != null && reasoningContent.length > 0 && this._service.currentConfig.showThoughtMessage) {
1852
1853
  additionalReplyMessages.push({
1853
1854
  content: `Thought for ${reasoningTime / 1e3} seconds:
1854
1855
 
@@ -1993,7 +1994,7 @@ ${reasoningContent}`
1993
1994
  this._platformToConversations.delete(platform);
1994
1995
  }
1995
1996
  async _createChatInterface(room) {
1996
- const config = this._service.config;
1997
+ const config = this._service.currentConfig;
1997
1998
  const chatInterface = new ChatInterface(this._service.ctx.root, {
1998
1999
  chatMode: room.chatMode,
1999
2000
  botName: config.botNames[0],
@@ -68,21 +68,37 @@ async function trackLogToLocal(tag, output, logger) {
68
68
  if (!import_fs.default.existsSync(logDir)) {
69
69
  import_fs.default.mkdirSync(logDir, { recursive: true });
70
70
  }
71
- await import_fs.default.promises.writeFile(logFile, output);
72
- logger.info(`[${tag}] A local log file has been created at ${logFile}`);
73
- const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1e3;
74
- const files = await import_fs.default.promises.readdir(logDir);
75
- for (const file of files) {
76
- if (!file.startsWith("chatluna-log-") || !file.endsWith(".log")) {
77
- continue;
71
+ const writeAndCleanup = /* @__PURE__ */ __name(async () => {
72
+ await import_fs.default.promises.writeFile(logFile, output);
73
+ logger.info(`[${tag}] A local log file has been created at ${logFile}`);
74
+ const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1e3;
75
+ const files = await import_fs.default.promises.readdir(logDir);
76
+ let deletedCount = 0;
77
+ for (const file of files) {
78
+ if (!file.startsWith("chatluna-log-") || !file.endsWith(".log")) {
79
+ continue;
80
+ }
81
+ const filePath = `${logDir}/${file}`;
82
+ let stats;
83
+ try {
84
+ stats = await import_fs.default.promises.stat(filePath);
85
+ } catch {
86
+ continue;
87
+ }
88
+ if (stats.mtimeMs < sevenDaysAgo) {
89
+ try {
90
+ await import_fs.default.promises.unlink(filePath);
91
+ deletedCount += 1;
92
+ } catch {
93
+ }
94
+ await new Promise((resolve) => setTimeout(resolve, 0));
95
+ }
78
96
  }
79
- const filePath = `${logDir}/${file}`;
80
- const stats = await import_fs.default.promises.stat(filePath);
81
- if (stats.mtimeMs < sevenDaysAgo) {
82
- await import_fs.default.promises.unlink(filePath);
83
- logger.debug(`[${tag}] Deleted old log file: ${filePath}`);
84
- }
85
- }
97
+ logger.debug(`[${tag}] Deleted ${deletedCount} old log file(s).`);
98
+ }, "writeAndCleanup");
99
+ setTimeout(() => {
100
+ writeAndCleanup().catch(() => void 0);
101
+ }, 0);
86
102
  }
87
103
  __name(trackLogToLocal, "trackLogToLocal");
88
104
  // Annotate the CommonJS export names for ESM import in node:
@@ -34,21 +34,37 @@ async function trackLogToLocal(tag, output, logger) {
34
34
  if (!fs.existsSync(logDir)) {
35
35
  fs.mkdirSync(logDir, { recursive: true });
36
36
  }
37
- await fs.promises.writeFile(logFile, output);
38
- logger.info(`[${tag}] A local log file has been created at ${logFile}`);
39
- const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1e3;
40
- const files = await fs.promises.readdir(logDir);
41
- for (const file of files) {
42
- if (!file.startsWith("chatluna-log-") || !file.endsWith(".log")) {
43
- continue;
37
+ const writeAndCleanup = /* @__PURE__ */ __name(async () => {
38
+ await fs.promises.writeFile(logFile, output);
39
+ logger.info(`[${tag}] A local log file has been created at ${logFile}`);
40
+ const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1e3;
41
+ const files = await fs.promises.readdir(logDir);
42
+ let deletedCount = 0;
43
+ for (const file of files) {
44
+ if (!file.startsWith("chatluna-log-") || !file.endsWith(".log")) {
45
+ continue;
46
+ }
47
+ const filePath = `${logDir}/${file}`;
48
+ let stats;
49
+ try {
50
+ stats = await fs.promises.stat(filePath);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (stats.mtimeMs < sevenDaysAgo) {
55
+ try {
56
+ await fs.promises.unlink(filePath);
57
+ deletedCount += 1;
58
+ } catch {
59
+ }
60
+ await new Promise((resolve) => setTimeout(resolve, 0));
61
+ }
44
62
  }
45
- const filePath = `${logDir}/${file}`;
46
- const stats = await fs.promises.stat(filePath);
47
- if (stats.mtimeMs < sevenDaysAgo) {
48
- await fs.promises.unlink(filePath);
49
- logger.debug(`[${tag}] Deleted old log file: ${filePath}`);
50
- }
51
- }
63
+ logger.debug(`[${tag}] Deleted ${deletedCount} old log file(s).`);
64
+ }, "writeAndCleanup");
65
+ setTimeout(() => {
66
+ writeAndCleanup().catch(() => void 0);
67
+ }, 0);
52
68
  }
53
69
  __name(trackLogToLocal, "trackLogToLocal");
54
70
  export {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-chatluna",
3
3
  "description": "chatluna for koishi",
4
- "version": "1.3.13",
4
+ "version": "1.3.15",
5
5
  "main": "lib/index.cjs",
6
6
  "module": "lib/index.mjs",
7
7
  "typings": "lib/index.d.ts",