File size: 13,828 Bytes
4e23b01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | import { parsePattern } from '@moonshot-ai/agent-core-v2/agent/permissionRules/matchesRule';
import { z } from 'zod';
import { ErrorCodes, KimiError } from '#/errors';
const HOOK_EVENT_TYPES = [
'PreToolUse',
'PostToolUse',
'PostToolUseFailure',
'PermissionRequest',
'PermissionResult',
'UserPromptSubmit',
'Stop',
'StopFailure',
'Interrupt',
'SessionStart',
'SessionEnd',
'SubagentStart',
'SubagentStop',
'PreCompact',
'PostCompact',
'Notification',
] as const;
export const ProviderTypeSchema = z.enum([
'anthropic',
'openai',
'kimi',
'google-genai',
'openai_responses',
'vertexai',
]);
export type ProviderType = z.infer<typeof ProviderTypeSchema>;
export const OAuthRefSchema = z.object({
storage: z.enum(['file', 'keyring']),
key: z.string().min(1),
oauthHost: z.string().min(1).optional(),
});
export type OAuthRef = z.infer<typeof OAuthRefSchema>;
const StringRecordSchema = z.record(z.string(), z.string());
export const ProviderConfigSchema = z.object({
type: ProviderTypeSchema,
apiKey: z.string().optional(),
baseUrl: z.string().optional(),
defaultModel: z.string().optional(),
oauth: OAuthRefSchema.optional(),
env: StringRecordSchema.optional(),
customHeaders: StringRecordSchema.optional(),
source: z.record(z.string(), z.unknown()).optional(),
});
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>;
const ModelAliasBaseSchema = z.object({
provider: z.string(),
model: z.string(),
maxContextSize: z.number().int().min(1),
maxInputSize: z.number().int().min(1).optional(),
maxOutputSize: z.number().int().min(1).optional(),
capabilities: z.array(z.string()).optional(),
displayName: z.string().optional(),
reasoningKey: z.string().optional(),
protocol: z.enum(['anthropic', 'openai_responses']).optional(),
adaptiveThinking: z.boolean().optional(),
supportEfforts: z.array(z.string()).optional(),
defaultEffort: z.string().optional(),
offEffort: z.string().optional(),
betaApi: z.boolean().optional(),
baseUrl: z.string().optional(),
});
export const ModelAliasOverrideSchema = ModelAliasBaseSchema.omit({
provider: true,
model: true,
protocol: true,
betaApi: true,
baseUrl: true,
}).partial();
export type ModelAliasOverrides = z.infer<typeof ModelAliasOverrideSchema>;
export const ModelAliasSchema = ModelAliasBaseSchema.extend({
overrides: ModelAliasOverrideSchema.optional(),
});
export type ModelAlias = z.infer<typeof ModelAliasSchema>;
export const SecondaryModelConfigSchema = ModelAliasOverrideSchema.extend({
model: z.string().min(1).optional(),
defaultModel: z.string().min(1).optional(),
models: z.record(z.string(), z.string()).optional(),
force: z.boolean().optional(),
});
export type SecondaryModelConfig = z.infer<typeof SecondaryModelConfigSchema>;
export const ThinkingConfigSchema = z.object({
enabled: z.boolean().optional(),
effort: z.string().optional(),
keep: z.string().optional(),
});
export type ThinkingConfig = z.infer<typeof ThinkingConfigSchema>;
export const PermissionModeSchema = z.enum(['yolo', 'manual', 'auto']);
export const PermissionRuleDecisionSchema = z.enum(['allow', 'deny', 'ask']);
export const PermissionRuleScopeSchema = z.enum([
'turn-override',
'session-runtime',
'project',
'user',
]);
export const PermissionRuleSchema = z.object({
decision: PermissionRuleDecisionSchema,
scope: PermissionRuleScopeSchema.default('user'),
pattern: z.string().min(1).refine(isValidPermissionPattern, {
message: 'Invalid permission rule pattern',
}),
reason: z.string().optional(),
});
export const PermissionConfigSchema = z.object({
rules: z.array(PermissionRuleSchema).optional(),
});
export type PermissionConfig = z.infer<typeof PermissionConfigSchema>;
export const LoopControlSchema = z.object({
maxStepsPerTurn: z.number().int().min(0).optional(),
maxRetriesPerStep: z.number().int().min(0).optional(),
maxRalphIterations: z.number().int().min(-1).optional(),
reservedContextSize: z.number().int().min(0).optional(),
compactionTriggerRatio: z.number().min(0.5).max(0.99).optional(),
compactionMaxAttempts: z.number().int().min(1).optional(),
});
export type LoopControl = z.infer<typeof LoopControlSchema>;
export const BackgroundConfigSchema = z.object({
maxRunningTasks: z.number().int().min(1).optional(),
keepAliveOnExit: z.boolean().optional(),
bashAutoBackgroundOnTimeout: z.boolean().optional(),
bashTaskTimeoutS: z.number().int().min(0).optional(),
killGracePeriodMs: z.number().int().min(0).optional(),
printWaitCeilingS: z.number().int().min(1).optional(),
printBackgroundMode: z.enum(['exit', 'drain', 'steer']).optional(),
printMaxTurns: z.number().int().min(1).optional(),
});
export type BackgroundConfig = z.infer<typeof BackgroundConfigSchema>;
export const SubagentConfigSchema = z.object({
timeoutMs: z.number().int().min(0).optional(),
});
export type SubagentConfig = z.infer<typeof SubagentConfigSchema>;
export const MAX_MCP_TIMEOUT_MS = 2_147_483_647;
const McpTimeoutMsSchema = z.number().int().min(1).max(MAX_MCP_TIMEOUT_MS);
export const McpConfigSchema = z.object({
startupTimeoutMs: McpTimeoutMsSchema.optional(),
toolTimeoutMs: McpTimeoutMsSchema.optional(),
});
export type McpConfig = z.infer<typeof McpConfigSchema>;
export const ImageConfigSchema = z.object({
maxEdgePx: z.number().int().min(1).optional(),
readByteBudget: z.number().int().min(1).optional(),
});
export type ImageConfig = z.infer<typeof ImageConfigSchema>;
export const ModelCatalogConfigSchema = z.object({
refreshIntervalMs: z.number().int().min(0).optional(),
refreshOnStart: z.boolean().optional(),
});
export type ModelCatalogConfig = z.infer<typeof ModelCatalogConfigSchema>;
export const ExperimentalConfigSchema = z.record(z.string(), z.boolean());
export type ExperimentalConfig = z.infer<typeof ExperimentalConfigSchema>;
export const HookDefSchema = z
.object({
event: z.enum(HOOK_EVENT_TYPES),
matcher: z.string().optional(),
command: z.string().min(1),
timeout: z.number().int().min(1).max(600).optional(),
})
.strict();
export type HookDefConfig = z.infer<typeof HookDefSchema>;
export const MoonshotServiceConfigSchema = z.object({
baseUrl: z.string().optional(),
apiKey: z.string().optional(),
oauth: OAuthRefSchema.optional(),
customHeaders: StringRecordSchema.optional(),
});
export type MoonshotServiceConfig = z.infer<typeof MoonshotServiceConfigSchema>;
export const ServicesConfigSchema = z.object({
moonshotSearch: MoonshotServiceConfigSchema.optional(),
moonshotFetch: MoonshotServiceConfigSchema.optional(),
});
export type ServicesConfig = z.infer<typeof ServicesConfigSchema>;
const McpServerCommonFields = {
enabled: z.boolean().optional(),
startupTimeoutMs: McpTimeoutMsSchema.optional(),
toolTimeoutMs: McpTimeoutMsSchema.optional(),
enabledTools: z.array(z.string()).optional(),
disabledTools: z.array(z.string()).optional(),
} as const;
export const McpServerStdioConfigSchema = z.object({
transport: z.literal('stdio'),
command: z.string().min(1),
args: z.array(z.string()).optional(),
env: StringRecordSchema.optional(),
cwd: z.string().optional(),
executor: z.enum(['local', 'kaos']).optional(),
...McpServerCommonFields,
});
export type McpServerStdioConfig = z.infer<typeof McpServerStdioConfigSchema>;
export const McpServerHttpConfigSchema = z.object({
transport: z.literal('http'),
url: z.string().url(),
headers: StringRecordSchema.optional(),
auth: z.literal('oauth').optional(),
bearerTokenEnvVar: z.string().min(1).optional(),
...McpServerCommonFields,
});
export type McpServerHttpConfig = z.infer<typeof McpServerHttpConfigSchema>;
export const McpServerSseConfigSchema = z.object({
transport: z.literal('sse'),
url: z.string().url(),
headers: StringRecordSchema.optional(),
auth: z.literal('oauth').optional(),
bearerTokenEnvVar: z.string().min(1).optional(),
...McpServerCommonFields,
});
export type McpServerSseConfig = z.infer<typeof McpServerSseConfigSchema>;
export type McpRemoteServerConfig = McpServerHttpConfig | McpServerSseConfig;
const McpServerConfigDiscriminatedSchema = z.discriminatedUnion('transport', [
McpServerStdioConfigSchema,
McpServerHttpConfigSchema,
McpServerSseConfigSchema,
]);
export const McpServerConfigSchema = z.preprocess((raw) => {
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return raw;
const obj = raw as Record<string, unknown>;
if ('transport' in obj) return obj;
if (typeof obj['command'] === 'string') return { ...obj, transport: 'stdio' };
if (typeof obj['url'] === 'string') return { ...obj, transport: 'http' };
return obj;
}, McpServerConfigDiscriminatedSchema);
export type McpServerConfig = z.infer<typeof McpServerConfigSchema>;
export const KimiConfigSchema = z.object({
providers: z.record(z.string(), ProviderConfigSchema).default({}),
defaultProvider: z.string().optional(),
defaultModel: z.string().optional(),
models: z.record(z.string(), ModelAliasSchema).optional(),
thinking: ThinkingConfigSchema.optional(),
planMode: z.boolean().optional(),
yolo: z.boolean().optional(),
defaultPermissionMode: PermissionModeSchema.optional(),
defaultPlanMode: z.boolean().optional(),
permission: PermissionConfigSchema.optional(),
hooks: z.array(HookDefSchema).optional(),
services: ServicesConfigSchema.optional(),
mergeAllAvailableSkills: z.boolean().optional(),
extraSkillDirs: z.array(z.string()).optional(),
extraAgentDirs: z.array(z.string()).optional(),
loopControl: LoopControlSchema.optional(),
background: BackgroundConfigSchema.optional(),
subagent: SubagentConfigSchema.optional(),
secondaryModel: SecondaryModelConfigSchema.optional(),
mcp: McpConfigSchema.optional(),
image: ImageConfigSchema.optional(),
modelCatalog: ModelCatalogConfigSchema.optional(),
experimental: ExperimentalConfigSchema.optional(),
telemetry: z.boolean().optional(),
raw: z.record(z.string(), z.unknown()).optional(),
});
export type KimiConfig = z.infer<typeof KimiConfigSchema>;
const ProviderConfigPatchSchema = ProviderConfigSchema.partial();
const ModelAliasPatchSchema = ModelAliasSchema.partial();
const ThinkingConfigPatchSchema = ThinkingConfigSchema.partial();
const PermissionConfigPatchSchema = PermissionConfigSchema.partial();
const LoopControlPatchSchema = LoopControlSchema.partial();
const BackgroundConfigPatchSchema = BackgroundConfigSchema.partial();
const SubagentConfigPatchSchema = SubagentConfigSchema.partial();
const SecondaryModelConfigPatchSchema = SecondaryModelConfigSchema.partial();
const McpConfigPatchSchema = McpConfigSchema.partial();
const ImageConfigPatchSchema = ImageConfigSchema.partial();
const ModelCatalogConfigPatchSchema = ModelCatalogConfigSchema.partial();
const ExperimentalConfigPatchSchema = ExperimentalConfigSchema;
const MoonshotServiceConfigPatchSchema = MoonshotServiceConfigSchema.partial();
const ServicesConfigPatchSchema = z.object({
moonshotSearch: MoonshotServiceConfigPatchSchema.optional(),
moonshotFetch: MoonshotServiceConfigPatchSchema.optional(),
});
export const KimiConfigPatchSchema = z
.object({
providers: z.record(z.string(), ProviderConfigPatchSchema).optional(),
defaultProvider: z.string().optional(),
defaultModel: z.string().optional(),
models: z.record(z.string(), ModelAliasPatchSchema).optional(),
thinking: ThinkingConfigPatchSchema.optional(),
planMode: z.boolean().optional(),
yolo: z.boolean().optional(),
defaultPermissionMode: PermissionModeSchema.optional(),
defaultPlanMode: z.boolean().optional(),
permission: PermissionConfigPatchSchema.optional(),
hooks: z.array(HookDefSchema).optional(),
services: ServicesConfigPatchSchema.optional(),
mergeAllAvailableSkills: z.boolean().optional(),
extraSkillDirs: z.array(z.string()).optional(),
extraAgentDirs: z.array(z.string()).optional(),
loopControl: LoopControlPatchSchema.optional(),
background: BackgroundConfigPatchSchema.optional(),
subagent: SubagentConfigPatchSchema.optional(),
secondaryModel: SecondaryModelConfigPatchSchema.optional(),
mcp: McpConfigPatchSchema.optional(),
image: ImageConfigPatchSchema.optional(),
modelCatalog: ModelCatalogConfigPatchSchema.optional(),
experimental: ExperimentalConfigPatchSchema.optional(),
telemetry: z.boolean().optional(),
})
.strict();
export type KimiConfigPatch = z.infer<typeof KimiConfigPatchSchema>;
export function getDefaultConfig(): KimiConfig {
return {
providers: {},
};
}
export function validateConfig(config: unknown): KimiConfig {
try {
return KimiConfigSchema.parse(config);
} catch (error) {
throw new KimiError(ErrorCodes.CONFIG_INVALID, `Invalid configuration: ${formatConfigValidationError(error)}`, {
cause: error,
});
}
}
export function formatConfigValidationError(error: unknown): string {
const missingModelContextSize = missingModelContextSizeMessage(error);
if (missingModelContextSize !== undefined) return missingModelContextSize;
return error instanceof Error ? error.message : String(error);
}
function missingModelContextSizeMessage(error: unknown): string | undefined {
if (!(error instanceof z.ZodError)) return undefined;
for (const issue of error.issues) {
const [section, modelName, field] = issue.path;
if (section === 'models' && typeof modelName === 'string' && field === 'maxContextSize') {
return `Model "${modelName}" must define a positive max_context_size in config.toml.`;
}
}
return undefined;
}
function isValidPermissionPattern(pattern: string): boolean {
try {
parsePattern(pattern);
return true;
} catch {
return false;
}
}
|