@zhin.js/core 1.0.25 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +84 -342
  3. package/lib/adapter.d.ts +17 -0
  4. package/lib/adapter.d.ts.map +1 -1
  5. package/lib/adapter.js +84 -2
  6. package/lib/adapter.js.map +1 -1
  7. package/lib/ai/agent.d.ts +126 -0
  8. package/lib/ai/agent.d.ts.map +1 -0
  9. package/lib/ai/agent.js +645 -0
  10. package/lib/ai/agent.js.map +1 -0
  11. package/lib/ai/context-manager.d.ts +213 -0
  12. package/lib/ai/context-manager.d.ts.map +1 -0
  13. package/lib/ai/context-manager.js +313 -0
  14. package/lib/ai/context-manager.js.map +1 -0
  15. package/lib/ai/conversation-memory.d.ts +181 -0
  16. package/lib/ai/conversation-memory.d.ts.map +1 -0
  17. package/lib/ai/conversation-memory.js +581 -0
  18. package/lib/ai/conversation-memory.js.map +1 -0
  19. package/lib/ai/follow-up.d.ts +131 -0
  20. package/lib/ai/follow-up.d.ts.map +1 -0
  21. package/lib/ai/follow-up.js +265 -0
  22. package/lib/ai/follow-up.js.map +1 -0
  23. package/lib/ai/index.d.ts +29 -0
  24. package/lib/ai/index.d.ts.map +1 -0
  25. package/lib/ai/index.js +34 -0
  26. package/lib/ai/index.js.map +1 -0
  27. package/lib/ai/init.d.ts +30 -0
  28. package/lib/ai/init.d.ts.map +1 -0
  29. package/lib/ai/init.js +424 -0
  30. package/lib/ai/init.js.map +1 -0
  31. package/lib/ai/output.d.ts +93 -0
  32. package/lib/ai/output.d.ts.map +1 -0
  33. package/lib/ai/output.js +176 -0
  34. package/lib/ai/output.js.map +1 -0
  35. package/lib/ai/providers/anthropic.d.ts +23 -0
  36. package/lib/ai/providers/anthropic.d.ts.map +1 -0
  37. package/lib/ai/providers/anthropic.js +322 -0
  38. package/lib/ai/providers/anthropic.js.map +1 -0
  39. package/lib/ai/providers/base.d.ts +43 -0
  40. package/lib/ai/providers/base.d.ts.map +1 -0
  41. package/lib/ai/providers/base.js +135 -0
  42. package/lib/ai/providers/base.js.map +1 -0
  43. package/lib/ai/providers/index.d.ts +12 -0
  44. package/lib/ai/providers/index.d.ts.map +1 -0
  45. package/lib/ai/providers/index.js +9 -0
  46. package/lib/ai/providers/index.js.map +1 -0
  47. package/lib/ai/providers/ollama.d.ts +25 -0
  48. package/lib/ai/providers/ollama.d.ts.map +1 -0
  49. package/lib/ai/providers/ollama.js +243 -0
  50. package/lib/ai/providers/ollama.js.map +1 -0
  51. package/lib/ai/providers/openai.d.ts +46 -0
  52. package/lib/ai/providers/openai.d.ts.map +1 -0
  53. package/lib/ai/providers/openai.js +132 -0
  54. package/lib/ai/providers/openai.js.map +1 -0
  55. package/lib/ai/rate-limiter.d.ts +38 -0
  56. package/lib/ai/rate-limiter.d.ts.map +1 -0
  57. package/lib/ai/rate-limiter.js +86 -0
  58. package/lib/ai/rate-limiter.js.map +1 -0
  59. package/lib/ai/service.d.ts +81 -0
  60. package/lib/ai/service.d.ts.map +1 -0
  61. package/lib/ai/service.js +274 -0
  62. package/lib/ai/service.js.map +1 -0
  63. package/lib/ai/session.d.ts +186 -0
  64. package/lib/ai/session.d.ts.map +1 -0
  65. package/lib/ai/session.js +443 -0
  66. package/lib/ai/session.js.map +1 -0
  67. package/lib/ai/tone-detector.d.ts +19 -0
  68. package/lib/ai/tone-detector.d.ts.map +1 -0
  69. package/lib/ai/tone-detector.js +72 -0
  70. package/lib/ai/tone-detector.js.map +1 -0
  71. package/lib/ai/tools.d.ts +45 -0
  72. package/lib/ai/tools.d.ts.map +1 -0
  73. package/lib/ai/tools.js +206 -0
  74. package/lib/ai/tools.js.map +1 -0
  75. package/lib/ai/types.d.ts +264 -0
  76. package/lib/ai/types.d.ts.map +1 -0
  77. package/lib/ai/types.js +6 -0
  78. package/lib/ai/types.js.map +1 -0
  79. package/lib/ai/user-profile.d.ts +56 -0
  80. package/lib/ai/user-profile.d.ts.map +1 -0
  81. package/lib/ai/user-profile.js +130 -0
  82. package/lib/ai/user-profile.js.map +1 -0
  83. package/lib/ai/zhin-agent.d.ts +165 -0
  84. package/lib/ai/zhin-agent.d.ts.map +1 -0
  85. package/lib/ai/zhin-agent.js +707 -0
  86. package/lib/ai/zhin-agent.js.map +1 -0
  87. package/lib/built/ai-trigger.d.ts.map +1 -1
  88. package/lib/built/ai-trigger.js +7 -3
  89. package/lib/built/ai-trigger.js.map +1 -1
  90. package/lib/built/command.d.ts +33 -17
  91. package/lib/built/command.d.ts.map +1 -1
  92. package/lib/built/command.js +71 -44
  93. package/lib/built/command.js.map +1 -1
  94. package/lib/built/component.d.ts +42 -15
  95. package/lib/built/component.d.ts.map +1 -1
  96. package/lib/built/component.js +84 -52
  97. package/lib/built/component.js.map +1 -1
  98. package/lib/built/config.d.ts +64 -5
  99. package/lib/built/config.d.ts.map +1 -1
  100. package/lib/built/config.js +129 -12
  101. package/lib/built/config.js.map +1 -1
  102. package/lib/built/cron.d.ts +41 -18
  103. package/lib/built/cron.d.ts.map +1 -1
  104. package/lib/built/cron.js +106 -63
  105. package/lib/built/cron.js.map +1 -1
  106. package/lib/built/database.d.ts +55 -6
  107. package/lib/built/database.d.ts.map +1 -1
  108. package/lib/built/database.js +93 -22
  109. package/lib/built/database.js.map +1 -1
  110. package/lib/built/dispatcher.d.ts +118 -0
  111. package/lib/built/dispatcher.d.ts.map +1 -0
  112. package/lib/built/dispatcher.js +196 -0
  113. package/lib/built/dispatcher.js.map +1 -0
  114. package/lib/built/permission.d.ts +45 -5
  115. package/lib/built/permission.d.ts.map +1 -1
  116. package/lib/built/permission.js +56 -11
  117. package/lib/built/permission.js.map +1 -1
  118. package/lib/built/skill.d.ts +117 -0
  119. package/lib/built/skill.d.ts.map +1 -0
  120. package/lib/built/skill.js +191 -0
  121. package/lib/built/skill.js.map +1 -0
  122. package/lib/built/tool.d.ts +71 -164
  123. package/lib/built/tool.d.ts.map +1 -1
  124. package/lib/built/tool.js +212 -297
  125. package/lib/built/tool.js.map +1 -1
  126. package/lib/feature.d.ts +75 -0
  127. package/lib/feature.d.ts.map +1 -0
  128. package/lib/feature.js +69 -0
  129. package/lib/feature.js.map +1 -0
  130. package/lib/index.d.ts +4 -0
  131. package/lib/index.d.ts.map +1 -1
  132. package/lib/index.js +7 -0
  133. package/lib/index.js.map +1 -1
  134. package/lib/plugin.d.ts +25 -17
  135. package/lib/plugin.d.ts.map +1 -1
  136. package/lib/plugin.js +180 -20
  137. package/lib/plugin.js.map +1 -1
  138. package/lib/types.d.ts +4 -9
  139. package/lib/types.d.ts.map +1 -1
  140. package/package.json +6 -6
  141. package/src/adapter.ts +101 -2
  142. package/src/ai/agent.ts +772 -0
  143. package/src/ai/context-manager.ts +440 -0
  144. package/src/ai/conversation-memory.ts +774 -0
  145. package/src/ai/follow-up.ts +357 -0
  146. package/src/ai/index.ts +128 -0
  147. package/src/ai/init.ts +502 -0
  148. package/src/ai/output.ts +261 -0
  149. package/src/ai/providers/anthropic.ts +375 -0
  150. package/src/ai/providers/base.ts +173 -0
  151. package/src/ai/providers/index.ts +13 -0
  152. package/src/ai/providers/ollama.ts +292 -0
  153. package/src/ai/providers/openai.ts +167 -0
  154. package/src/ai/rate-limiter.ts +129 -0
  155. package/src/ai/service.ts +319 -0
  156. package/src/ai/session.ts +544 -0
  157. package/src/ai/tone-detector.ts +89 -0
  158. package/src/ai/tools.ts +218 -0
  159. package/src/ai/types.ts +296 -0
  160. package/src/ai/user-profile.ts +181 -0
  161. package/src/ai/zhin-agent.ts +845 -0
  162. package/src/built/ai-trigger.ts +6 -3
  163. package/src/built/command.ts +75 -69
  164. package/src/built/component.ts +94 -76
  165. package/src/built/config.ts +288 -128
  166. package/src/built/cron.ts +117 -101
  167. package/src/built/database.ts +128 -33
  168. package/src/built/dispatcher.ts +332 -0
  169. package/src/built/permission.ts +146 -54
  170. package/src/built/skill.ts +280 -0
  171. package/src/built/tool.ts +245 -366
  172. package/src/feature.ts +113 -0
  173. package/src/index.ts +7 -0
  174. package/src/plugin.ts +198 -33
  175. package/src/types.ts +6 -10
  176. package/tests/adapter.test.ts +153 -1
  177. package/tests/ai/agent.test.ts +614 -0
  178. package/tests/ai/ai-trigger.test.ts +368 -0
  179. package/tests/ai/context-manager.test.ts +413 -0
  180. package/tests/ai/conversation-memory.test.ts +128 -0
  181. package/tests/ai/follow-up.test.ts +175 -0
  182. package/tests/ai/integration.test.ts +584 -0
  183. package/tests/ai/output.test.ts +128 -0
  184. package/tests/ai/providers.integration.test.ts +227 -0
  185. package/tests/ai/rate-limiter.test.ts +108 -0
  186. package/tests/ai/session.test.ts +375 -0
  187. package/tests/ai/setup.ts +308 -0
  188. package/tests/ai/tone-detector.test.ts +80 -0
  189. package/tests/ai/tool.test.ts +800 -0
  190. package/tests/ai/tools-builtin.test.ts +346 -0
  191. package/tests/ai/user-profile.test.ts +73 -0
  192. package/tests/ai/zhin-agent.test.ts +177 -0
  193. package/tests/config.test.ts +46 -0
  194. package/tests/cron.test.ts +94 -5
  195. package/tests/dispatcher.test.ts +146 -0
  196. package/tests/feature.test.ts +145 -0
  197. package/tests/features-builtin.test.ts +191 -0
  198. package/tests/plugin.test.ts +88 -14
  199. package/tests/skill-feature.test.ts +179 -0
  200. package/tests/tool-feature.test.ts +254 -0
  201. package/test/minimal-bot.ts +0 -31
  202. package/test/stress-test.ts +0 -123
@@ -1,142 +1,302 @@
1
+ /**
2
+ * ConfigFeature
3
+ * 配置管理服务,继承自 Feature 抽象类
4
+ * 保留原有 ConfigLoader / ConfigService 逻辑,增加 addConfig 扩展
5
+ */
1
6
  import path from "node:path";
2
7
  import fs from "node:fs";
3
- import { stringify as stringifyYaml,parse as parseYaml } from "yaml";
8
+ import { stringify as stringifyYaml, parse as parseYaml } from "yaml";
9
+ import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
4
10
  import { Schema } from "@zhin.js/schema";
5
- export class ConfigLoader<T extends object>{
6
- #data: T;
7
- get data(): T {
8
- return this.#proxy(this.#data,this);
9
- }
10
- get raw(): T {
11
- return this.#data;
12
- }
13
- get extension() {
14
- return path.extname(this.filename).toLowerCase();
15
- }
16
- constructor(public filename: string, public initial:T, public schema?: Schema<T>) {
17
- this.#data = this.initial;
18
- }
19
- #proxy<R extends object>(data: R, loader: ConfigLoader<T>) {
20
- return new Proxy(data, {
21
- get(target, prop, receiver) {
22
- // 对于特殊属性(如 Symbol、prototype 等),直接返回原始值
23
- if (typeof prop === 'symbol' || prop === 'constructor' || prop === 'prototype') {
24
- return Reflect.get(target, prop, receiver);
25
- }
26
-
27
- const result= Reflect.get(target, prop, receiver);
28
-
29
- // 对于函数属性(如数组的 map、filter 等),直接返回,不进行代理
30
- if (typeof result === 'function') {
31
- return result;
32
- }
33
-
34
- // 对于对象和数组,递归代理(但排除函数)
35
- if(result instanceof Object && result!==null && typeof result !== 'function') {
36
- return loader.#proxy(result,loader);
37
- }
38
-
39
- // 处理环境变量占位符
40
- if(typeof result==='string') {
41
- if(result.startsWith('\\${') && result.endsWith('}')) return result.slice(1);
42
- if(/^\$\{(.*)\}$/.test(result)){
43
- const content = result.slice(2, -1);
44
- const [key, ...rest] = content.split(':');
45
- const defaultValue = rest.length > 0 ? rest.join(':') : undefined;
46
- return process.env[key] ?? defaultValue ?? (loader.initial as any)[key] ?? result;
47
- }
48
- }
49
- return result;
50
- },
51
- set(target, prop, value, receiver) {
52
- const result= Reflect.set(target, prop, value, receiver);
53
- loader.save(loader.filename);
54
- return result;
55
- },
56
- deleteProperty(target, prop) {
57
- const result= Reflect.deleteProperty(target, prop);
58
- loader.save(loader.filename);
59
- return result;
60
- }
61
- });
62
- }
63
- load() {
64
- const fullPath=path.resolve(process.cwd(), this.filename);
65
- if (!fs.existsSync(fullPath)) {
66
- this.save(fullPath);
11
+ import { Feature, FeatureJSON } from "../feature.js";
12
+ import { getPlugin } from "../plugin.js";
13
+
14
+ // ============================================================================
15
+ // ConfigLoader(保持不变)
16
+ // ============================================================================
17
+
18
+ export class ConfigLoader<T extends object> {
19
+ #data: T;
20
+ get data(): T {
21
+ return this.#proxy(this.#data, this);
22
+ }
23
+ get raw(): T {
24
+ return this.#data;
25
+ }
26
+ get extension() {
27
+ return path.extname(this.filename).toLowerCase();
28
+ }
29
+ constructor(public filename: string, public initial: T, public schema?: Schema<T>) {
30
+ this.#data = this.initial;
31
+ }
32
+ #proxy<R extends object>(data: R, loader: ConfigLoader<T>) {
33
+ return new Proxy(data, {
34
+ get(target, prop, receiver) {
35
+ if (typeof prop === 'symbol' || prop === 'constructor' || prop === 'prototype') {
36
+ return Reflect.get(target, prop, receiver);
67
37
  }
68
- const content = fs.readFileSync(fullPath, "utf-8");
69
- let rawConfig: any;
70
- switch (this.extension) {
71
- case ".json":
72
- rawConfig = JSON.parse(content);
73
- break;
74
- case ".yaml":
75
- case ".yml":
76
- rawConfig = parseYaml(content);
77
- break;
38
+
39
+ const result = Reflect.get(target, prop, receiver);
40
+
41
+ if (typeof result === 'function') {
42
+ return result;
78
43
  }
79
- if(this.schema){
80
- this.#data = this.schema(rawConfig || this.initial) as T;
81
- }else{
82
- this.#data = rawConfig as T;
44
+
45
+ if (result instanceof Object && result !== null && typeof result !== 'function') {
46
+ return loader.#proxy(result, loader);
83
47
  }
84
- }
85
- save(fullPath: string) {
86
- switch (this.extension) {
87
- case ".json":
88
- fs.writeFileSync(fullPath, JSON.stringify(this.#data, null, 2));
89
- break;
90
- case ".yaml":
91
- case ".yml":
92
- fs.writeFileSync(fullPath, stringifyYaml(this.#data));
93
- break;
48
+
49
+ if (typeof result === 'string') {
50
+ if (result.startsWith('\\${') && result.endsWith('}')) return result.slice(1);
51
+ if (/^\$\{(.*)\}$/.test(result)) {
52
+ const content = result.slice(2, -1);
53
+ // 支持 bash 风格的默认值语法:${VAR:-default} 和 ${VAR:=default}
54
+ // 同时兼容简单语法 ${VAR:default}
55
+ let key: string;
56
+ let defaultValue: string | undefined;
57
+ const bashDefaultMatch = content.match(/^([^:}]+):[-=](.*)$/);
58
+ if (bashDefaultMatch) {
59
+ // ${VAR:-default} 或 ${VAR:=default}
60
+ key = bashDefaultMatch[1];
61
+ defaultValue = bashDefaultMatch[2];
62
+ } else if (content.includes(':')) {
63
+ // ${VAR:default}(旧的简单语法)
64
+ const [k, ...rest] = content.split(':');
65
+ key = k;
66
+ defaultValue = rest.join(':');
67
+ } else {
68
+ key = content;
69
+ defaultValue = undefined;
70
+ }
71
+ return process.env[key] ?? defaultValue ?? (loader.initial as any)[key] ?? result;
72
+ }
94
73
  }
95
- }
96
- }
97
- export namespace ConfigLoader{
98
- export const supportedExtensions = [".json", ".yaml", ".yml"];
99
- export function load<T extends object>(filename: string, initial?:T, schema?: Schema<T>) {
100
- const result = new ConfigLoader<T>(filename, initial??{} as T, schema);
101
- result.load();
102
74
  return result;
75
+ },
76
+ set(target, prop, value, receiver) {
77
+ const result = Reflect.set(target, prop, value, receiver);
78
+ loader.save(loader.filename);
79
+ return result;
80
+ },
81
+ deleteProperty(target, prop) {
82
+ const result = Reflect.deleteProperty(target, prop);
83
+ loader.save(loader.filename);
84
+ return result;
85
+ }
86
+ });
87
+ }
88
+ load() {
89
+ const fullPath = path.resolve(process.cwd(), this.filename);
90
+ if (!fs.existsSync(fullPath)) {
91
+ this.save(fullPath);
103
92
  }
104
- }
105
- export class ConfigService{
106
- configs: Map<string, ConfigLoader<any>> = new Map();
107
- constructor() {
93
+ const content = fs.readFileSync(fullPath, "utf-8");
94
+ let rawConfig: any;
95
+ switch (this.extension) {
96
+ case ".json":
97
+ rawConfig = JSON.parse(content);
98
+ break;
99
+ case ".yaml":
100
+ case ".yml":
101
+ rawConfig = parseYaml(content);
102
+ break;
103
+ case ".toml":
104
+ rawConfig = parseToml(content);
105
+ break;
108
106
  }
109
- load<T extends object>(filename: string, initial?:Partial<T>, schema?: Schema<T>) {
110
- const ext = path.extname(filename).toLowerCase();
111
- if (!ConfigLoader.supportedExtensions.includes(ext)) {
112
- throw new Error(`不支持的配置文件格式: ${ext}`);
113
- }
114
- const config = ConfigLoader.load(filename, initial as T, schema);
115
- this.configs.set(filename, config);
116
- return config;
107
+ if (this.schema) {
108
+ this.#data = this.schema(rawConfig || this.initial) as T;
109
+ } else {
110
+ this.#data = rawConfig as T;
111
+ }
112
+ }
113
+ save(fullPath: string) {
114
+ switch (this.extension) {
115
+ case ".json":
116
+ fs.writeFileSync(fullPath, JSON.stringify(this.#data, null, 2));
117
+ break;
118
+ case ".yaml":
119
+ case ".yml":
120
+ fs.writeFileSync(fullPath, stringifyYaml(this.#data));
121
+ break;
122
+ case ".toml":
123
+ fs.writeFileSync(fullPath, stringifyToml(this.#data as Record<string, any>));
124
+ break;
117
125
  }
118
- get<T extends object>(filename: string, initial?:Partial<T>, schema?: Schema<T>): T {
119
- if(!this.configs.has(filename)) this.load(filename, initial, schema);
120
- const config = this.configs.get(filename);
121
- if(!config) throw new Error(`配置文件 ${filename} 未加载`);
122
- return config.data as T;
126
+ }
127
+ }
128
+
129
+ export namespace ConfigLoader {
130
+ export const supportedExtensions = [".json", ".yaml", ".yml", ".toml"];
131
+
132
+ /**
133
+ * 自动发现配置文件(按优先级:yml > yaml > json > toml)
134
+ */
135
+ export function discover(basename: string): string | null {
136
+ const cwd = process.cwd();
137
+ for (const ext of ['.yml', '.yaml', '.json', '.toml']) {
138
+ const filename = `${basename}${ext}`;
139
+ if (fs.existsSync(path.resolve(cwd, filename))) {
140
+ return filename;
141
+ }
142
+ }
143
+ return null;
144
+ }
145
+ export function load<T extends object>(filename: string, initial?: T, schema?: Schema<T>) {
146
+ const result = new ConfigLoader<T>(filename, initial ?? {} as T, schema);
147
+ result.load();
148
+ return result;
149
+ }
150
+ }
151
+
152
+ // ============================================================================
153
+ // ConfigFeature
154
+ // ============================================================================
155
+
156
+ /**
157
+ * 配置项声明记录
158
+ */
159
+ export interface ConfigRecord {
160
+ key: string;
161
+ defaultValue: any;
162
+ }
163
+
164
+ /**
165
+ * ConfigFeature 扩展方法类型
166
+ */
167
+ export interface ConfigContextExtensions {
168
+ /** 声明插件配置项(key + 默认值),如果配置文件中不存在则写入默认值 */
169
+ addConfig(key: string, defaultValue: any): () => void;
170
+ }
171
+
172
+ declare module "../plugin.js" {
173
+ namespace Plugin {
174
+ interface Extensions extends ConfigContextExtensions {}
175
+ interface Contexts {
176
+ config: ConfigFeature;
123
177
  }
124
- getRaw<T extends object>(filename: string, initial?:Partial<T>, schema?: Schema<T>): T {
125
- if(!this.configs.has(filename)) this.load(filename, initial, schema);
126
- const config = this.configs.get(filename);
127
- if(!config) throw new Error(`配置文件 ${filename} 未加载`);
128
- return config.raw as T;
178
+ }
179
+ }
180
+
181
+ export class ConfigFeature extends Feature<ConfigRecord> {
182
+ readonly name = 'config' as const;
183
+ readonly icon = 'Settings';
184
+ readonly desc = '配置';
185
+
186
+ /** 内部配置文件管理 */
187
+ readonly configs: Map<string, ConfigLoader<any>> = new Map();
188
+
189
+ /** 主配置文件名(第一个加载的配置文件) */
190
+ #primaryConfigFile: string = '';
191
+
192
+ /** 获取主配置文件名 */
193
+ get primaryFile(): string {
194
+ return this.#primaryConfigFile;
195
+ }
196
+
197
+ /**
198
+ * 加载配置文件
199
+ */
200
+ load<T extends object>(filename: string, initial?: Partial<T>, schema?: Schema<T>): ConfigLoader<T> {
201
+ const ext = path.extname(filename).toLowerCase();
202
+ if (!ConfigLoader.supportedExtensions.includes(ext)) {
203
+ throw new Error(`不支持的配置文件格式: ${ext}`);
129
204
  }
130
- /**
131
- * 更新配置文件内容
132
- * @param filename 配置文件名
133
- * @param data 新的配置数据
134
- */
135
- set<T extends object>(filename: string, data: T): void {
136
- const config = this.configs.get(filename);
137
- if(!config) throw new Error(`配置文件 ${filename} 未加载`);
138
- // 直接更新内部数据(会触发 Proxy 的 set 拦截器并自动保存)
139
- Object.assign(config.raw, data);
140
- config.save(path.resolve(process.cwd(), filename));
205
+ const config = ConfigLoader.load(filename, initial as T, schema);
206
+ this.configs.set(filename, config);
207
+ if (!this.#primaryConfigFile) {
208
+ this.#primaryConfigFile = filename;
141
209
  }
142
- }
210
+ return config;
211
+ }
212
+
213
+ /**
214
+ * 获取配置数据(代理模式,自动保存)
215
+ */
216
+ get<T extends object>(filename: string, initial?: Partial<T>, schema?: Schema<T>): T {
217
+ if (!this.configs.has(filename)) this.load(filename, initial, schema);
218
+ const config = this.configs.get(filename);
219
+ if (!config) throw new Error(`配置文件 ${filename} 未加载`);
220
+ return config.data as T;
221
+ }
222
+
223
+ /**
224
+ * 获取主配置文件数据(第一个加载的配置文件)
225
+ */
226
+ getPrimary<T extends object>(): T {
227
+ if (!this.#primaryConfigFile) throw new Error('没有加载任何配置文件');
228
+ return this.get<T>(this.#primaryConfigFile);
229
+ }
230
+
231
+ /**
232
+ * 获取原始配置数据
233
+ */
234
+ getRaw<T extends object>(filename: string, initial?: Partial<T>, schema?: Schema<T>): T {
235
+ if (!this.configs.has(filename)) this.load(filename, initial, schema);
236
+ const config = this.configs.get(filename);
237
+ if (!config) throw new Error(`配置文件 ${filename} 未加载`);
238
+ return config.raw as T;
239
+ }
240
+
241
+ /**
242
+ * 更新配置文件内容
243
+ */
244
+ set<T extends object>(filename: string, data: T): void {
245
+ const config = this.configs.get(filename);
246
+ if (!config) throw new Error(`配置文件 ${filename} 未加载`);
247
+ Object.assign(config.raw, data);
248
+ config.save(path.resolve(process.cwd(), filename));
249
+ }
250
+
251
+ /**
252
+ * 序列化为 JSON
253
+ */
254
+ toJSON(pluginName?: string): FeatureJSON {
255
+ const list = pluginName ? this.getByPlugin(pluginName) : this.items;
256
+ return {
257
+ name: this.name,
258
+ icon: this.icon,
259
+ desc: this.desc,
260
+ count: list.length,
261
+ items: list.map(r => ({
262
+ name: r.key,
263
+ // 不暴露 defaultValue 以防止泄露密钥/令牌
264
+ })),
265
+ };
266
+ }
267
+
268
+ /**
269
+ * 提供给 Plugin.prototype 的扩展方法
270
+ */
271
+ get extensions() {
272
+ const feature = this;
273
+ return {
274
+ addConfig(key: string, defaultValue: any) {
275
+ const plugin = getPlugin();
276
+
277
+ // 尝试写入主配置文件(如果 key 不存在)
278
+ if (feature.#primaryConfigFile) {
279
+ const config = feature.configs.get(feature.#primaryConfigFile);
280
+ if (config) {
281
+ const raw = config.raw as Record<string, any>;
282
+ if (!(key in raw)) {
283
+ raw[key] = defaultValue;
284
+ config.save(path.resolve(process.cwd(), feature.#primaryConfigFile));
285
+ }
286
+ }
287
+ }
288
+
289
+ const record: ConfigRecord = { key, defaultValue };
290
+ const dispose = feature.add(record, plugin.name);
291
+ plugin.recordFeatureContribution(feature.name, key);
292
+ plugin.onDispose(dispose);
293
+ return dispose;
294
+ },
295
+ };
296
+ }
297
+ }
298
+
299
+ /**
300
+ * @deprecated Use ConfigFeature instead
301
+ */
302
+ export const ConfigService = ConfigFeature;
package/src/built/cron.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  /**
2
- * Cron Context
3
- * 管理所有插件注册的定时任务
2
+ * CronFeature
3
+ * 管理所有插件注册的定时任务,继承自 Feature 抽象类
4
4
  */
5
+ import { Feature, FeatureJSON } from "../feature.js";
5
6
  import { Cron } from "../cron.js";
6
- import { Context, Plugin, getPlugin } from "../plugin.js";
7
+ import { Plugin, getPlugin } from "../plugin.js";
7
8
 
8
9
  /**
9
10
  * CronContext 扩展方法类型
@@ -18,123 +19,138 @@ declare module "../plugin.js" {
18
19
  namespace Plugin {
19
20
  interface Extensions extends CronContextExtensions {}
20
21
  interface Contexts {
21
- cron: CronService;
22
+ cron: CronFeature;
22
23
  }
23
24
  }
24
25
  }
25
26
 
26
27
  /**
27
- * 定时任务服务数据
28
+ * 定时任务服务 Feature
28
29
  */
29
- export interface CronService {
30
- /** 任务列表 */
31
- readonly items: Cron[];
30
+ export class CronFeature extends Feature<Cron> {
31
+ readonly name = 'cron' as const;
32
+ readonly icon = 'Clock';
33
+ readonly desc = '定时任务';
34
+
32
35
  /** 按 ID/表达式 索引 */
33
- readonly byName: Map<string, Cron>;
34
- /** 添加任务 */
35
- add(cron: Cron, pluginName: string): () => void;
36
- /** 移除任务 */
37
- remove(cron: Cron): boolean;
38
- /** 按名称获取 */
39
- get(id: string): Cron | undefined;
40
- /** 停止所有任务 */
41
- stopAll(): void;
42
- /** 启动所有任务 */
43
- startAll(): void;
44
- /** 获取状态 */
36
+ readonly byName = new Map<string, Cron>();
37
+
38
+ /**
39
+ * 添加定时任务,自动启动
40
+ */
41
+ add(cron: Cron, pluginName: string): () => void {
42
+ this.byName.set(cron.id || cron.cronExpression, cron);
43
+ // 自动启动
44
+ if (!cron.running) {
45
+ cron.run();
46
+ }
47
+ return super.add(cron, pluginName);
48
+ }
49
+
50
+ /**
51
+ * 移除定时任务,自动停止
52
+ */
53
+ remove(cron: Cron): boolean {
54
+ if (cron.running) {
55
+ cron.stop();
56
+ }
57
+ this.byName.delete(cron.id || cron.cronExpression);
58
+ return super.remove(cron);
59
+ }
60
+
61
+ /**
62
+ * 按 ID/表达式 获取
63
+ */
64
+ get(id: string): Cron | undefined {
65
+ return this.byName.get(id);
66
+ }
67
+
68
+ /**
69
+ * 停止所有任务
70
+ */
71
+ stopAll(): void {
72
+ for (const cron of this.items) {
73
+ if (cron.running) {
74
+ cron.stop();
75
+ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 启动所有任务
81
+ */
82
+ startAll(): void {
83
+ for (const cron of this.items) {
84
+ if (!cron.running && !cron.disposed) {
85
+ cron.run();
86
+ }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 获取所有任务状态
92
+ */
45
93
  getStatus(): Array<{
46
94
  expression: string;
47
95
  running: boolean;
48
96
  nextExecution: Date | null;
49
97
  plugin: string;
50
- }>;
51
- }
52
-
53
- /**
54
- * 创建定时任务 Context
55
- */
56
- export function createCronService(): Context<'cron', CronContextExtensions> {
57
- const items: Cron[] = [];
58
- const byName = new Map<string, Cron>();
59
- const pluginMap = new Map<Cron, string>();
60
-
61
- const value: CronService = {
62
- items,
63
- byName,
64
-
65
- add(cron, pluginName) {
66
- items.push(cron);
67
- byName.set(cron.id || cron.cronExpression, cron);
68
- pluginMap.set(cron, pluginName);
69
- // 自动启动
70
- if (!cron.running) {
71
- cron.run();
72
- }
73
- return () => value.remove(cron);
74
- },
75
-
76
- remove(cron) {
77
- const index = items.indexOf(cron);
78
- if (index !== -1) {
79
- // 自动停止
80
- if (cron.running) {
81
- cron.stop();
98
+ }> {
99
+ return this.items.map(cron => {
100
+ // 从 pluginItems 中找到对应的插件名
101
+ let pluginName = 'unknown';
102
+ for (const [name, items] of this.pluginItems) {
103
+ if (items.includes(cron)) {
104
+ pluginName = name;
105
+ break;
82
106
  }
83
- items.splice(index, 1);
84
- byName.delete(cron.id || cron.cronExpression);
85
- pluginMap.delete(cron);
86
- return true;
87
107
  }
88
- return false;
89
- },
90
-
91
- get(id) {
92
- return byName.get(id);
93
- },
94
-
95
- stopAll() {
96
- for (const cron of items) {
97
- if (cron.running) {
98
- cron.stop();
99
- }
100
- }
101
- },
102
-
103
- startAll() {
104
- for (const cron of items) {
105
- if (!cron.running && !cron.disposed) {
106
- cron.run();
107
- }
108
- }
109
- },
110
-
111
- getStatus() {
112
- return items.map(cron => ({
108
+ return {
113
109
  expression: cron.cronExpression,
114
110
  running: cron.running,
115
111
  nextExecution: cron.running ? cron.getNextExecutionTime() : null,
116
- plugin: pluginMap.get(cron) || 'unknown',
117
- }));
118
- }
119
- };
120
-
121
- return {
122
- name: 'cron',
123
- description: '定时任务服务',
124
- value,
125
-
126
- dispose() {
127
- value.stopAll();
128
- },
129
-
130
- extensions: {
112
+ plugin: pluginName,
113
+ };
114
+ });
115
+ }
116
+
117
+ /**
118
+ * 生命周期: 销毁时停止所有任务
119
+ */
120
+ dispose(): void {
121
+ this.stopAll();
122
+ }
123
+
124
+ /**
125
+ * 序列化为 JSON
126
+ */
127
+ toJSON(pluginName?: string): FeatureJSON {
128
+ const list = pluginName ? this.getByPlugin(pluginName) : this.items;
129
+ return {
130
+ name: this.name,
131
+ icon: this.icon,
132
+ desc: this.desc,
133
+ count: list.length,
134
+ items: list.map(c => ({
135
+ expression: c.cronExpression,
136
+ running: c.running,
137
+ })),
138
+ };
139
+ }
140
+
141
+ /**
142
+ * 提供给 Plugin.prototype 的扩展方法
143
+ */
144
+ get extensions() {
145
+ const feature = this;
146
+ return {
131
147
  addCron(cron: Cron) {
132
148
  const plugin = getPlugin();
133
- const dispose = value.add(cron, plugin.name);
149
+ const dispose = feature.add(cron, plugin.name);
150
+ plugin.recordFeatureContribution(feature.name, cron.id || cron.cronExpression);
134
151
  plugin.onDispose(dispose);
135
152
  return dispose;
136
- }
137
- }
138
- };
153
+ },
154
+ };
155
+ }
139
156
  }
140
-