Skip to content

Commit ae3c033

Browse files
author
echoVic
committed
refactor(task): 使用运行时验证替代静态枚举检查
将 subagent 类型验证从静态 z.enum() 改为运行时 z.string().refine() 检查 避免模块加载时因 registry 未初始化导致的默认值问题
1 parent fb4a55a commit ae3c033

1 file changed

Lines changed: 15 additions & 7 deletions

File tree

src/tools/builtin/task/task.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,17 @@ function extractUserFriendlyError(error: Error): string {
6363
}
6464

6565
/**
66-
* 获取可用的 subagent 类型(用于 Zod 枚举)
66+
* 验证 subagent 类型是否有效(运行时验证)
67+
* 不能使用 z.enum() 因为它在模块加载时调用,此时 registry 还未初始化
6768
*/
68-
function getAvailableSubagentTypes(): [string, ...string[]] {
69+
function isValidSubagentType(type: string): boolean {
6970
const types = subagentRegistry.getAllNames();
70-
if (types.length === 0) {
71-
return ['Explore']; // 默认值,避免 Zod 空数组报错
72-
}
73-
return types as [string, ...string[]];
71+
return types.includes(type);
72+
}
73+
74+
function getAvailableSubagentTypesMessage(): string {
75+
const types = subagentRegistry.getAllNames();
76+
return types.length > 0 ? types.join(', ') : 'none (registry not initialized)';
7477
}
7578

7679
/**
@@ -127,9 +130,14 @@ export const taskTool = createTool({
127130
isReadOnly: true,
128131

129132
// Zod Schema 定义
133+
// 注意:使用 z.string() + refine 而非 z.enum(),因为 enum 在模块加载时求值,
134+
// 此时 subagentRegistry 还未初始化,会导致只接受默认值
130135
schema: z.object({
131136
subagent_type: z
132-
.enum(getAvailableSubagentTypes())
137+
.string()
138+
.refine(isValidSubagentType, (val) => ({
139+
message: `Invalid subagent type: "${val}". Available: ${getAvailableSubagentTypesMessage()}`,
140+
}))
133141
.describe('Subagent type to use (e.g., "Explore", "Plan")'),
134142
description: z
135143
.string()

0 commit comments

Comments
 (0)