@zhin.js/core 1.1.0 → 1.1.2

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 (122) hide show
  1. package/lib/adapter.d.ts +1 -26
  2. package/lib/adapter.d.ts.map +1 -1
  3. package/lib/adapter.js +20 -117
  4. package/lib/adapter.js.map +1 -1
  5. package/lib/built/adapter-process.d.ts +0 -4
  6. package/lib/built/adapter-process.d.ts.map +1 -1
  7. package/lib/built/adapter-process.js +0 -95
  8. package/lib/built/adapter-process.js.map +1 -1
  9. package/lib/built/agent-preset.d.ts +2 -0
  10. package/lib/built/agent-preset.d.ts.map +1 -1
  11. package/lib/built/agent-preset.js +4 -0
  12. package/lib/built/agent-preset.js.map +1 -1
  13. package/lib/built/command.d.ts +4 -0
  14. package/lib/built/command.d.ts.map +1 -1
  15. package/lib/built/command.js +6 -0
  16. package/lib/built/command.js.map +1 -1
  17. package/lib/built/component.d.ts.map +1 -1
  18. package/lib/built/component.js +1 -0
  19. package/lib/built/component.js.map +1 -1
  20. package/lib/built/dispatcher.d.ts.map +1 -1
  21. package/lib/built/dispatcher.js +0 -13
  22. package/lib/built/dispatcher.js.map +1 -1
  23. package/lib/built/message-filter.d.ts +2 -0
  24. package/lib/built/message-filter.d.ts.map +1 -1
  25. package/lib/built/message-filter.js +5 -0
  26. package/lib/built/message-filter.js.map +1 -1
  27. package/lib/built/skill.d.ts +11 -0
  28. package/lib/built/skill.d.ts.map +1 -1
  29. package/lib/built/skill.js +14 -0
  30. package/lib/built/skill.js.map +1 -1
  31. package/lib/built/tool.d.ts +11 -44
  32. package/lib/built/tool.d.ts.map +1 -1
  33. package/lib/built/tool.js +14 -353
  34. package/lib/built/tool.js.map +1 -1
  35. package/lib/plugin.d.ts +1 -25
  36. package/lib/plugin.d.ts.map +1 -1
  37. package/lib/plugin.js +1 -77
  38. package/lib/plugin.js.map +1 -1
  39. package/lib/types.d.ts +0 -25
  40. package/lib/types.d.ts.map +1 -1
  41. package/package.json +10 -7
  42. package/CHANGELOG.md +0 -561
  43. package/REFACTORING_COMPLETE.md +0 -178
  44. package/REFACTORING_STATUS.md +0 -263
  45. package/src/adapter.ts +0 -275
  46. package/src/ai/index.ts +0 -55
  47. package/src/ai/providers/anthropic.ts +0 -379
  48. package/src/ai/providers/base.ts +0 -175
  49. package/src/ai/providers/index.ts +0 -13
  50. package/src/ai/providers/ollama.ts +0 -302
  51. package/src/ai/providers/openai.ts +0 -174
  52. package/src/ai/types.ts +0 -348
  53. package/src/bot.ts +0 -37
  54. package/src/built/adapter-process.ts +0 -177
  55. package/src/built/agent-preset.ts +0 -136
  56. package/src/built/ai-trigger.ts +0 -259
  57. package/src/built/command.ts +0 -108
  58. package/src/built/common-adapter-tools.ts +0 -242
  59. package/src/built/component.ts +0 -130
  60. package/src/built/config.ts +0 -335
  61. package/src/built/cron.ts +0 -156
  62. package/src/built/database.ts +0 -134
  63. package/src/built/dispatcher.ts +0 -496
  64. package/src/built/login-assist.ts +0 -131
  65. package/src/built/message-filter.ts +0 -390
  66. package/src/built/permission.ts +0 -151
  67. package/src/built/schema-feature.ts +0 -190
  68. package/src/built/skill.ts +0 -221
  69. package/src/built/tool.ts +0 -948
  70. package/src/command.ts +0 -87
  71. package/src/component.ts +0 -565
  72. package/src/cron.ts +0 -4
  73. package/src/errors.ts +0 -46
  74. package/src/feature.ts +0 -7
  75. package/src/index.ts +0 -53
  76. package/src/jsx-dev-runtime.ts +0 -2
  77. package/src/jsx-runtime.ts +0 -12
  78. package/src/jsx.ts +0 -135
  79. package/src/message.ts +0 -48
  80. package/src/models/system-log.ts +0 -20
  81. package/src/models/user.ts +0 -15
  82. package/src/notice.ts +0 -98
  83. package/src/plugin.ts +0 -896
  84. package/src/prompt.ts +0 -293
  85. package/src/request.ts +0 -95
  86. package/src/scheduler/index.ts +0 -19
  87. package/src/scheduler/scheduler.ts +0 -372
  88. package/src/scheduler/types.ts +0 -74
  89. package/src/tool-zod.ts +0 -115
  90. package/src/types-generator.ts +0 -78
  91. package/src/types.ts +0 -505
  92. package/src/utils.ts +0 -227
  93. package/tests/adapter.test.ts +0 -638
  94. package/tests/ai/ai-trigger.test.ts +0 -368
  95. package/tests/ai/providers.integration.test.ts +0 -227
  96. package/tests/ai/setup.ts +0 -308
  97. package/tests/ai/tool.test.ts +0 -800
  98. package/tests/bot.test.ts +0 -151
  99. package/tests/command.test.ts +0 -737
  100. package/tests/component-new.test.ts +0 -361
  101. package/tests/config.test.ts +0 -372
  102. package/tests/cron.test.ts +0 -82
  103. package/tests/dispatcher.test.ts +0 -293
  104. package/tests/errors.test.ts +0 -21
  105. package/tests/expression-evaluation.test.ts +0 -258
  106. package/tests/features-builtin.test.ts +0 -191
  107. package/tests/jsx-runtime.test.ts +0 -45
  108. package/tests/jsx.test.ts +0 -319
  109. package/tests/message-filter.test.ts +0 -566
  110. package/tests/message.test.ts +0 -402
  111. package/tests/notice.test.ts +0 -198
  112. package/tests/plugin.test.ts +0 -779
  113. package/tests/prompt.test.ts +0 -78
  114. package/tests/redos-protection.test.ts +0 -198
  115. package/tests/request.test.ts +0 -221
  116. package/tests/schema.test.ts +0 -248
  117. package/tests/skill-feature.test.ts +0 -179
  118. package/tests/test-utils.ts +0 -59
  119. package/tests/tool-feature.test.ts +0 -254
  120. package/tests/types.test.ts +0 -162
  121. package/tests/utils.test.ts +0 -135
  122. package/tsconfig.json +0 -24
package/src/ai/types.ts DELETED
@@ -1,348 +0,0 @@
1
- /**
2
- * @zhin.js/ai - AI Service Types
3
- * 统一的 AI 服务类型定义
4
- */
5
-
6
- // ============================================================================
7
- // 基础类型
8
- // ============================================================================
9
-
10
- /** 消息角色 */
11
- export type MessageRole = 'system' | 'user' | 'assistant' | 'tool' | 'tool_call' | 'tool_result';
12
-
13
- /** 聊天消息 */
14
- export interface ChatMessage {
15
- role: MessageRole;
16
- content: string | ContentPart[];
17
- name?: string;
18
- tool_call_id?: string;
19
- tool_calls?: ToolCall[];
20
- }
21
-
22
- /** 内容部分(支持多模态) */
23
- export type ContentPart =
24
- | { type: 'text'; text: string }
25
- | { type: 'image_url'; image_url: { url: string; detail?: 'auto' | 'low' | 'high' } }
26
- | { type: 'audio'; audio: { data: string; format: 'wav' | 'mp3' } }
27
- | { type: 'video_url'; video_url: { url: string } }
28
- | { type: 'face'; face: { id: string; text?: string } };
29
-
30
- /** 工具调用 */
31
- export interface ToolCall {
32
- id: string;
33
- type: 'function';
34
- function: {
35
- name: string;
36
- arguments: string;
37
- };
38
- }
39
-
40
- /** 工具定义 */
41
- export interface ToolDefinition {
42
- type: 'function';
43
- function: {
44
- name: string;
45
- description: string;
46
- parameters: JsonSchema;
47
- };
48
- }
49
-
50
- /** JSON Schema */
51
- export interface JsonSchema {
52
- type: string;
53
- properties?: Record<string, JsonSchema>;
54
- required?: string[];
55
- items?: JsonSchema;
56
- enum?: unknown[];
57
- description?: string;
58
- default?: unknown;
59
- /** JSON Schema allows arbitrary extension properties */
60
- [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any -- JSON Schema spec requires open index
61
- }
62
-
63
- // ============================================================================
64
- // 请求/响应类型
65
- // ============================================================================
66
-
67
- /** 聊天补全请求 */
68
- export interface ChatCompletionRequest {
69
- model: string;
70
- messages: ChatMessage[];
71
- tools?: ToolDefinition[];
72
- tool_choice?: 'auto' | 'none' | 'required' | { type: 'function'; function: { name: string } };
73
- temperature?: number;
74
- top_p?: number;
75
- max_tokens?: number;
76
- stream?: boolean;
77
- stop?: string | string[];
78
- presence_penalty?: number;
79
- frequency_penalty?: number;
80
- user?: string;
81
- /** 是否启用模型思考(如 qwen3 的 <think> 模式)。设为 false 可跳过思考加速响应。 */
82
- think?: boolean;
83
- }
84
-
85
- /** 聊天补全响应 */
86
- export interface ChatCompletionResponse {
87
- id: string;
88
- object: 'chat.completion';
89
- created: number;
90
- model: string;
91
- choices: ChatCompletionChoice[];
92
- usage?: Usage;
93
- }
94
-
95
- /** 选择 */
96
- export interface ChatCompletionChoice {
97
- index: number;
98
- message: ChatMessage;
99
- finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
100
- }
101
-
102
- /** 用量统计 */
103
- export interface Usage {
104
- prompt_tokens: number;
105
- completion_tokens: number;
106
- total_tokens: number;
107
- }
108
-
109
- // ============================================================================
110
- // 流式响应类型
111
- // ============================================================================
112
-
113
- /** 流式响应块 */
114
- export interface ChatCompletionChunk {
115
- id: string;
116
- object: 'chat.completion.chunk';
117
- created: number;
118
- model: string;
119
- choices: ChatCompletionChunkChoice[];
120
- usage?: Usage;
121
- }
122
-
123
- /** 流式选择 */
124
- export interface ChatCompletionChunkChoice {
125
- index: number;
126
- delta: Partial<ChatMessage>;
127
- finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
128
- }
129
-
130
- // ============================================================================
131
- // Provider 类型
132
- // ============================================================================
133
-
134
- /** Provider 能力声明 */
135
- export interface ProviderCapabilities {
136
- vision?: boolean;
137
- streaming?: boolean;
138
- toolCalling?: boolean;
139
- thinking?: boolean;
140
- }
141
-
142
- /** Provider 配置 */
143
- export interface ProviderConfig {
144
- apiKey?: string;
145
- /**
146
- * Authorization 头前缀。默认 `'Bearer '`;设为 `''` 时仅用 apiKey 作为值(部分 API 要求 `Authorization: <key>`)。
147
- */
148
- authScheme?: string;
149
- baseUrl?: string;
150
- defaultModel?: string;
151
- models?: string[];
152
- timeout?: number;
153
- maxRetries?: number;
154
- headers?: Record<string, string>;
155
- /** 上下文窗口大小(token 数),各 Provider 映射到自身参数 */
156
- contextWindow?: number;
157
- /** Provider 能力声明 */
158
- capabilities?: ProviderCapabilities;
159
- }
160
-
161
- /** Provider 接口 */
162
- export interface AIProvider {
163
- name: string;
164
- models: string[];
165
-
166
- /** 聊天补全 */
167
- chat(request: ChatCompletionRequest): Promise<ChatCompletionResponse>;
168
-
169
- /** 流式聊天补全 */
170
- chatStream(request: ChatCompletionRequest): AsyncIterable<ChatCompletionChunk>;
171
-
172
- /** 列出可用模型 */
173
- listModels?(): Promise<string[]>;
174
-
175
- /** 检查连接 */
176
- healthCheck?(): Promise<boolean>;
177
-
178
- /** 上下文窗口大小(token 数),由 Provider 实现暴露 */
179
- contextWindow?: number;
180
-
181
- /** Provider 能力声明 */
182
- capabilities?: ProviderCapabilities;
183
- }
184
-
185
- // ============================================================================
186
- // Agent 类型
187
- // ============================================================================
188
-
189
- /** Agent 工具 */
190
- export interface AgentTool {
191
- name: string;
192
- description: string;
193
- parameters: JsonSchema;
194
- execute: (args: Record<string, any>) => Promise<unknown>;
195
- /** 工具标签,用于分类和快速匹配 */
196
- tags?: string[];
197
- /** 触发关键词,用户消息包含这些词时优先选择此工具 */
198
- keywords?: string[];
199
- /** 所需权限级别 (0=所有人, 1=群管理, 2=群主, 3=Bot管理员, 4=拥有者) */
200
- permissionLevel?: number;
201
- /** 是否允许预执行(opt-in),默认 false */
202
- preExecutable?: boolean;
203
- /** 工具分类(如 file / shell / web),用于 formatToolTitle 等展示 */
204
- kind?: string;
205
- }
206
-
207
- /**
208
- * 工具过滤选项
209
- * 在 Agent.run() / runStream() 中启用程序化工具预过滤,
210
- * 省去额外的 AI 意图分析往返
211
- */
212
- export interface ToolFilterOptions {
213
- /** 调用者权限级别 (0-4),高于工具要求才能使用 */
214
- callerPermissionLevel?: number;
215
- /** 最大返回工具数量 (默认 10) */
216
- maxTools?: number;
217
- /** 最低相关性得分阈值,低于此分数的工具被过滤掉 (默认 0.1) */
218
- minScore?: number;
219
- }
220
-
221
- /** Agent 配置 */
222
- export interface AgentConfig {
223
- provider: string;
224
- model?: string;
225
- systemPrompt?: string;
226
- tools?: AgentTool[];
227
- maxIterations?: number;
228
- temperature?: number;
229
- }
230
-
231
- /** Agent 运行结果 */
232
- export interface AgentResult {
233
- content: string;
234
- toolCalls: {
235
- tool: string;
236
- args: Record<string, any>;
237
- result: any;
238
- }[];
239
- usage: Usage;
240
- iterations: number;
241
- }
242
-
243
- // ============================================================================
244
- // Session 类型
245
- // ============================================================================
246
-
247
- /** 会话配置 */
248
- export interface SessionConfig {
249
- provider: string;
250
- model?: string;
251
- systemPrompt?: string;
252
- maxHistory?: number;
253
- expireMs?: number;
254
- }
255
-
256
- /** 会话 */
257
- export interface Session {
258
- id: string;
259
- config: SessionConfig;
260
- messages: ChatMessage[];
261
- createdAt: number;
262
- updatedAt: number;
263
- metadata?: Record<string, any>;
264
- }
265
-
266
- // ============================================================================
267
- // AI Service 配置
268
- // ============================================================================
269
-
270
- /** Ollama-specific fields for AIConfig typing (mirrors OllamaConfig) */
271
- export interface OllamaProviderConfig extends ProviderConfig {
272
- host?: string;
273
- models?: string[];
274
- num_ctx?: number;
275
- }
276
-
277
- /** AI 服务配置 */
278
- export interface AIConfig {
279
- enabled?: boolean;
280
- defaultProvider?: string;
281
- providers?: {
282
- openai?: ProviderConfig;
283
- anthropic?: ProviderConfig;
284
- deepseek?: ProviderConfig;
285
- moonshot?: ProviderConfig;
286
- zhipu?: ProviderConfig;
287
- ollama?: OllamaProviderConfig;
288
- custom?: ProviderConfig[];
289
- };
290
- sessions?: {
291
- /** 最大历史消息数(数据库模式默认200,内存模式默认100) */
292
- maxHistory?: number;
293
- /** 会话过期时间(毫秒,数据库模式默认7天,内存模式默认24小时) */
294
- expireMs?: number;
295
- /** 是否使用数据库持久化存储(默认 true) */
296
- useDatabase?: boolean;
297
- };
298
- context?: {
299
- /** 是否启用消息记录(默认 true) */
300
- enabled?: boolean;
301
- /** 读取的最近消息数量(默认 100) */
302
- maxRecentMessages?: number;
303
- /** 触发总结的消息数量阈值(默认 50) */
304
- summaryThreshold?: number;
305
- /** 总结后保留的消息数量(默认 10) */
306
- keepAfterSummary?: number;
307
- /** 上下文最大 token 估算(默认 4000) */
308
- maxContextTokens?: number;
309
- /** 自定义总结提示词 */
310
- summaryPrompt?: string;
311
- };
312
- /** Agent 工具开关与执行安全 */
313
- agent?: {
314
- /** 禁用的工具名列表,这些工具不会下发给 AI */
315
- disabledTools?: string[];
316
- /** 仅允许的工具名列表;若设置则只下发列表中的工具(与 disabledTools 二选一,allowedTools 优先) */
317
- allowedTools?: string[];
318
- /** bash 执行策略:deny=禁止执行,allowlist=仅允许列表内命令,full=不限制 */
319
- execSecurity?: 'deny' | 'allowlist' | 'full';
320
- /** 预设命令白名单模式:readonly / network / development / custom(默认 custom,使用自定义 execAllowlist) */
321
- execPreset?: 'readonly' | 'network' | 'development' | 'custom';
322
- /** allowlist 模式下允许的命令(支持正则字符串,如 "^ls "、"^cat "),与 preset 合并 */
323
- execAllowlist?: string[];
324
- /** allowlist 未命中时:true=需审批(当前实现为拒绝并提示),false=直接拒绝 */
325
- execAsk?: boolean;
326
- };
327
- /** AI 触发配置 */
328
- trigger?: {
329
- /** 是否启用(默认 true) */
330
- enabled?: boolean;
331
- /** 触发前缀列表(默认 ['#', 'AI:']) */
332
- prefixes?: string[];
333
- /** 是否响应 @ 机器人(默认 true) */
334
- respondToAt?: boolean;
335
- /** 是否响应私聊(默认 true) */
336
- respondToPrivate?: boolean;
337
- /** 触发关键词(可选) */
338
- keywords?: string[];
339
- /** 忽略的前缀(命令前缀,避免与命令冲突,默认 ['/', '!', '!']) */
340
- ignorePrefixes?: string[];
341
- /** 超时时间(毫秒,默认 60000) */
342
- timeout?: number;
343
- /** 思考中提示语(可选,设置后会在处理前发送) */
344
- thinkingMessage?: string;
345
- /** 错误提示模板(默认 '❌ AI 处理失败: {error}') */
346
- errorTemplate?: string;
347
- };
348
- }
package/src/bot.ts DELETED
@@ -1,37 +0,0 @@
1
- import type { SendOptions } from "./types.js";
2
- import { Message } from "./message.js";
3
- import { Notice } from "./notice.js";
4
- import { Request } from "./request.js";
5
- import { Adapter, Adapters } from "./adapter.js";
6
- /**
7
- * Bot接口:所有平台机器人需实现的统一接口。
8
- * 负责消息格式化、连接、断开、消息发送等。
9
- * @template Config 配置类型
10
- * @template Event 消息事件类型
11
- */
12
- export interface Bot<Config extends object= {},Event extends object = {}> {
13
- $id:string
14
- /** 机器人配置 */
15
- $config: Config;
16
- /** 是否已连接 */
17
- $connected: boolean;
18
- /** 格式化平台消息为标准Message结构 */
19
- $formatMessage(event: Event): Message<Event>;
20
- /** 格式化平台通知为标准Notice结构(适配器可选实现) */
21
- $formatNotice?(event: any): Notice<any>;
22
- /** 格式化平台请求为标准Request结构(适配器可选实现) */
23
- $formatRequest?(event: any): Request<any>;
24
- /** 连接机器人 */
25
- $connect(): Promise<void>;
26
- /** 断开机器人 */
27
- $disconnect(): Promise<void>;
28
- /** 撤回消息 */
29
- $recallMessage(id: string): Promise<void>;
30
- /** 发送消息返回消息id */
31
- $sendMessage(options: SendOptions): Promise<string>;
32
- }
33
- export namespace Bot {
34
- export type Config<K extends keyof Adapters = keyof Adapters> =Adapter.BotConfig<Adapter.InferBot<Adapters[K]>> & {
35
- context: K;
36
- }
37
- }
@@ -1,177 +0,0 @@
1
- import { Adapter, Plugin, Bot, SendContent, SendOptions, MessageBase, Message, segment } from "@zhin.js/core";
2
- export class ProcessBot implements Bot<{ owner?: string },{content:string,ts:number}>{
3
- $id=`${process.pid}`;
4
- get logger() {
5
- return this.adapter.logger;
6
- }
7
- $connected=false;
8
- constructor(public adapter: ProcessAdapter, public $config: { owner?: string }={ owner: `${process.pid}` }) {
9
- this.$listenInput=this.$listenInput.bind(this);
10
- }
11
- $listenInput:(data:Buffer<ArrayBufferLike>)=>void=function (this:ProcessBot,data){
12
- const content = data.toString().trim();
13
- if (content) {
14
- this.adapter.emit('message.receive', this.$formatMessage({content,ts:Date.now()}));
15
- }
16
- }
17
- async connect() {
18
- }
19
- async disconnect() {
20
- }
21
- $formatMessage(event: {content:string,ts:number}): Message<{content:string,ts:number}> {
22
- const base:MessageBase={
23
- $id: `${event.ts}`,
24
- $adapter: 'process',
25
- $bot: `${process.pid}`,
26
- $sender: {
27
- id: `${process.pid}`,
28
- name: process.title,
29
- },
30
- $channel: {
31
- id: `${process.pid}`,
32
- type: 'private',
33
- },
34
- $content: [{type:'text',data:{text:event.content}}],
35
- $raw: event.content,
36
- $timestamp: event.ts,
37
- $recall: async () => {
38
- await this.$recallMessage(base.$id)
39
- },
40
- $reply: async (content: SendContent) => {
41
- return await this.adapter.sendMessage({
42
- context: 'process',
43
- bot: base.$bot,
44
- content,
45
- id: base.$id,
46
- type: base.$channel.type,
47
- });
48
- },
49
- }
50
- return Message.from(event, base);
51
- }
52
- async $recallMessage(id: string) {
53
- }
54
- async $sendMessage(options: SendOptions) {
55
- return `${Date.now()}`;
56
- }
57
- async $connect(): Promise<void> {
58
- process.stdin.on('data', this.$listenInput);
59
- this.$connected = true;
60
- }
61
- async $disconnect() {
62
- process.stdin.removeListener('data', this.$listenInput);
63
- }
64
- }
65
- export class ProcessAdapter extends Adapter<ProcessBot>{
66
- constructor(plugin: Plugin) {
67
- super(plugin, 'process', [{ owner: `${process.pid}` }]);
68
-
69
- // 注册适配器提供的 AI 工具
70
- this.registerDefaultTools();
71
- this.registerProcessTools();
72
- }
73
-
74
- createBot(config: Adapter.BotConfig<ProcessBot>): ProcessBot {
75
- return new ProcessBot(this, config);
76
- }
77
-
78
- /**
79
- * 注册 Process 适配器特有的工具
80
- */
81
- private registerProcessTools(): void {
82
- // 获取进程信息
83
- this.addTool({
84
- name: 'process_get_info',
85
- description: '获取当前进程的详细信息,包括 PID、内存使用、运行时间等',
86
- parameters: {
87
- type: 'object',
88
- properties: {},
89
- },
90
- execute: async () => {
91
- const memUsage = process.memoryUsage();
92
- return {
93
- pid: process.pid,
94
- title: process.title,
95
- uptime: process.uptime(),
96
- platform: process.platform,
97
- arch: process.arch,
98
- nodeVersion: process.version,
99
- memory: {
100
- rss: Math.round(memUsage.rss / 1024 / 1024) + ' MB',
101
- heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024) + ' MB',
102
- heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024) + ' MB',
103
- },
104
- cwd: process.cwd(),
105
- };
106
- },
107
- });
108
-
109
- // 获取环境变量
110
- this.addTool({
111
- name: 'process_get_env',
112
- description: '获取指定的环境变量值',
113
- parameters: {
114
- type: 'object',
115
- properties: {
116
- name: {
117
- type: 'string',
118
- description: '环境变量名称',
119
- },
120
- },
121
- required: ['name'],
122
- },
123
- execute: async (args) => {
124
- const { name } = args;
125
- // 安全起见,不返回敏感环境变量
126
- const sensitive = ['PASSWORD', 'SECRET', 'TOKEN', 'KEY', 'CREDENTIAL'];
127
- if (sensitive.some(s => name.toUpperCase().includes(s))) {
128
- return { error: '无法访问敏感环境变量' };
129
- }
130
- return { name, value: process.env[name] || null };
131
- },
132
- });
133
-
134
- // 输出到控制台
135
- this.addTool({
136
- name: 'process_console_log',
137
- description: '向控制台输出信息',
138
- parameters: {
139
- type: 'object',
140
- properties: {
141
- message: {
142
- type: 'string',
143
- description: '要输出的消息',
144
- },
145
- level: {
146
- type: 'string',
147
- enum: ['info', 'warn', 'error', 'debug'],
148
- description: '日志级别',
149
- },
150
- },
151
- required: ['message'],
152
- },
153
- execute: async (args) => {
154
- const { message, level = 'info' } = args;
155
- switch (level) {
156
- case 'warn':
157
- console.warn(message);
158
- break;
159
- case 'error':
160
- console.error(message);
161
- break;
162
- case 'debug':
163
- console.debug(message);
164
- break;
165
- default:
166
- console.log(message);
167
- }
168
- return { success: true, message: `已输出: ${message}` };
169
- },
170
- });
171
- }
172
- }
173
- declare module '../adapter.js'{
174
- interface Adapters{
175
- process:ProcessAdapter
176
- }
177
- }
@@ -1,136 +0,0 @@
1
- /**
2
- * AgentPreset — 插件声明的专长 Agent 预设
3
- *
4
- * 核心概念:
5
- * Tool = 单个 AI 可调用的能力(函数)
6
- * Skill = 一组相关 Tool + 发现元数据(SKILL.md)
7
- * Agent = 针对特定领域的 Agent 预设(*.agent.md)
8
- *
9
- * Agent 预设以标准 *.agent.md 文件提供,框架自动扫描发现。
10
- * 主 Agent(ZhinAgent)可根据用户请求自动委派给匹配的专长 Agent。
11
- */
12
-
13
- import { Feature, type FeatureJSON } from '../feature.js';
14
- import type { Tool } from '../types.js';
15
-
16
- // ============================================================================
17
- // AgentPreset 接口
18
- // ============================================================================
19
-
20
- /**
21
- * Agent 预设(从 *.agent.md 文件解析或编程式注册)
22
- */
23
- export interface AgentPreset {
24
- /** 预设名称(唯一标识) */
25
- name: string;
26
-
27
- /** 描述(AI 用来判断何时委派给此 Agent) */
28
- description: string;
29
-
30
- /** 自定义系统提示词(从 agent.md body 提取或显式指定) */
31
- systemPrompt?: string;
32
-
33
- /** 关联的工具列表 */
34
- tools?: Tool[];
35
-
36
- /** 触发关键词(用户消息匹配时优先考虑此 Agent) */
37
- keywords?: string[];
38
-
39
- /** 分类标签 */
40
- tags?: string[];
41
-
42
- /** 首选模型名 */
43
- model?: string;
44
-
45
- /** 首选 Provider 名 */
46
- provider?: string;
47
-
48
- /** 最大工具调用迭代次数 */
49
- maxIterations?: number;
50
-
51
- /** 来源插件名(由框架自动填充) */
52
- pluginName?: string;
53
-
54
- /** *.agent.md 文件的绝对路径 */
55
- filePath?: string;
56
- }
57
-
58
- // ============================================================================
59
- // AgentPresetFeature
60
- // ============================================================================
61
-
62
- declare module '../plugin.js' {
63
- namespace Plugin {
64
- interface Contexts {
65
- agentPreset: AgentPresetFeature;
66
- }
67
- }
68
- }
69
-
70
- export class AgentPresetFeature extends Feature<AgentPreset> {
71
- readonly name = 'agentPreset' as const;
72
- readonly icon = 'Bot';
73
- readonly desc = 'Agent 预设';
74
-
75
- readonly byName = new Map<string, AgentPreset>();
76
-
77
- add(preset: AgentPreset, pluginName: string): () => void {
78
- this.byName.set(preset.name, preset);
79
- return super.add(preset, pluginName);
80
- }
81
-
82
- remove(preset: AgentPreset, pluginName?: string): boolean {
83
- this.byName.delete(preset.name);
84
- return super.remove(preset, pluginName);
85
- }
86
-
87
- get(name: string): AgentPreset | undefined {
88
- return this.byName.get(name);
89
- }
90
-
91
- getAll(): AgentPreset[] {
92
- return [...this.items];
93
- }
94
-
95
- search(query: string, options?: { maxResults?: number }): AgentPreset[] {
96
- const maxResults = options?.maxResults ?? 5;
97
- const lower = query.toLowerCase();
98
- const scored = this.items
99
- .map(preset => ({ preset, score: this.#scorePreset(preset, lower) }))
100
- .filter(({ score }) => score > 0)
101
- .sort((a, b) => b.score - a.score)
102
- .slice(0, maxResults);
103
- return scored.map(({ preset }) => preset);
104
- }
105
-
106
- #scorePreset(preset: AgentPreset, query: string): number {
107
- let score = 0;
108
- if (preset.name.toLowerCase().includes(query)) score += 10;
109
- if (preset.description.toLowerCase().includes(query)) score += 5;
110
- for (const kw of preset.keywords || []) {
111
- if (kw.toLowerCase().includes(query) || query.includes(kw.toLowerCase())) score += 8;
112
- }
113
- for (const tag of preset.tags || []) {
114
- if (tag.toLowerCase().includes(query)) score += 3;
115
- }
116
- return score;
117
- }
118
-
119
- toJSON(pluginName?: string): FeatureJSON {
120
- const list = pluginName ? this.getByPlugin(pluginName) : this.items;
121
- return {
122
- name: this.name,
123
- icon: this.icon,
124
- desc: this.desc,
125
- count: list.length,
126
- items: list.map(p => ({
127
- name: p.name,
128
- desc: p.description,
129
- keywords: p.keywords,
130
- tags: p.tags,
131
- model: p.model,
132
- provider: p.provider,
133
- })),
134
- };
135
- }
136
- }