File size: 17,891 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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | import {
APIConnectionError,
APIEmptyResponseError,
APIProviderQuotaExhaustedError,
APIStatusError,
APITimeoutError,
ChatProviderError,
} from '@moonshot-ai/kosong';
export const ErrorCodes = {
CONFIG_INVALID: 'config.invalid',
SESSION_NOT_FOUND: 'session.not_found',
SESSION_ALREADY_EXISTS: 'session.already_exists',
SESSION_ID_INVALID: 'session.id_invalid',
SESSION_ID_REQUIRED: 'session.id_required',
SESSION_ID_EMPTY: 'session.id_empty',
SESSION_TITLE_EMPTY: 'session.title_empty',
SESSION_STATE_NOT_FOUND: 'session.state_not_found',
SESSION_STATE_INVALID: 'session.state_invalid',
SESSION_FORK_ACTIVE_TURN: 'session.fork_active_turn',
SESSION_EXPORT_NOT_FOUND: 'session.export_not_found',
SESSION_EXPORT_MISSING_VERSION: 'session.export_missing_version',
SESSION_CLOSED: 'session.closed',
SESSION_PERMISSION_MODE_INVALID: 'session.permission_mode_invalid',
SESSION_THINKING_EMPTY: 'session.thinking_empty',
SESSION_MODEL_EMPTY: 'session.model_empty',
SESSION_PLAN_MODE_INVALID: 'session.plan_mode_invalid',
SESSION_APPROVAL_HANDLER_ERROR: 'session.approval_handler_error',
SESSION_QUESTION_HANDLER_ERROR: 'session.question_handler_error',
SESSION_INIT_FAILED: 'session.init_failed',
AGENT_NOT_FOUND: 'agent.not_found',
TURN_AGENT_BUSY: 'turn.agent_busy',
GOAL_ALREADY_EXISTS: 'goal.already_exists',
GOAL_NOT_FOUND: 'goal.not_found',
GOAL_OBJECTIVE_EMPTY: 'goal.objective_empty',
GOAL_OBJECTIVE_TOO_LONG: 'goal.objective_too_long',
GOAL_STATUS_INVALID: 'goal.status_invalid',
GOAL_METADATA_RESERVED: 'goal.metadata_reserved',
GOAL_NOT_RESUMABLE: 'goal.not_resumable',
MODEL_NOT_CONFIGURED: 'model.not_configured',
MODEL_CONFIG_INVALID: 'model.config_invalid',
AUTH_LOGIN_REQUIRED: 'auth.login_required',
CONTEXT_OVERFLOW: 'context.overflow',
LOOP_MAX_STEPS_EXCEEDED: 'loop.max_steps_exceeded',
PROVIDER_API_ERROR: 'provider.api_error',
PROVIDER_FILTERED: 'provider.filtered',
PROVIDER_RATE_LIMIT: 'provider.rate_limit',
PROVIDER_AUTH_ERROR: 'provider.auth_error',
PROVIDER_CONNECTION_ERROR: 'provider.connection_error',
SKILL_NOT_FOUND: 'skill.not_found',
SKILL_TYPE_UNSUPPORTED: 'skill.type_unsupported',
SKILL_NAME_EMPTY: 'skill.name_empty',
RECORDS_WRITE_FAILED: 'records.write_failed',
COMPACTION_FAILED: 'compaction.failed',
COMPACTION_UNABLE: 'compaction.unable',
BACKGROUND_TASK_ID_EMPTY: 'task.task_id_empty',
MCP_SERVER_NOT_FOUND: 'mcp.server_not_found',
MCP_SERVER_DISABLED: 'mcp.server_disabled',
MCP_STARTUP_FAILED: 'mcp.startup_failed',
MCP_TOOL_NAME_COLLISION: 'mcp.tool_name_collision',
MCP_OAUTH_FAILED: 'mcp.oauth_failed',
PLUGIN_NOT_FOUND: 'plugin.not_found',
PLUGIN_LOAD_FAILED: 'plugin.load_failed',
REQUEST_INVALID: 'request.invalid',
REQUEST_WORK_DIR_REQUIRED: 'request.work_dir_required',
REQUEST_PROMPT_INPUT_EMPTY: 'request.prompt_input_empty',
SHELL_GIT_BASH_NOT_FOUND: 'shell.git_bash_not_found',
NOT_IMPLEMENTED: 'not_implemented',
INTERNAL: 'internal',
} as const;
export type KimiErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
export interface KimiErrorInfo {
readonly title: string;
readonly retryable: boolean;
readonly public: boolean;
readonly action?: string;
}
export const KIMI_ERROR_INFO = {
'config.invalid': {
title: 'Invalid configuration',
retryable: false,
public: true,
action: 'Check config.toml and provider/model settings.',
},
'session.not_found': {
title: 'Session not found',
retryable: false,
public: true,
action: 'Check the session id or list available sessions.',
},
'session.already_exists': {
title: 'Session already exists',
retryable: false,
public: true,
action: 'Use a different session id or remove the existing session first.',
},
'session.id_invalid': {
title: 'Invalid session id',
retryable: false,
public: true,
action: 'Use a session id without path-traversal characters.',
},
'session.id_required': {
title: 'Session id required',
retryable: false,
public: true,
action: 'Provide a session id when calling this method.',
},
'session.id_empty': {
title: 'Session id is empty',
retryable: false,
public: true,
action: 'Provide a non-empty session id.',
},
'session.title_empty': {
title: 'Session title is empty',
retryable: false,
public: true,
action: 'Provide a non-empty session title.',
},
'session.state_not_found': {
title: 'Session state missing',
retryable: false,
public: true,
action: 'The session directory is corrupted or missing state.json.',
},
'session.state_invalid': {
title: 'Session state invalid',
retryable: false,
public: true,
action: 'The session state.json is corrupted; remove the session or repair the file.',
},
'session.fork_active_turn': {
title: 'Cannot fork session during active turn',
retryable: true,
public: true,
action: 'Wait for the active turn to complete before forking.',
},
'session.export_not_found': {
title: 'Session export directory missing',
retryable: false,
public: true,
action: 'The session has not been persisted to disk yet.',
},
'session.export_missing_version': {
title: 'Export version is missing',
retryable: false,
public: true,
action: 'Provide a version when exporting the session.',
},
'session.closed': {
title: 'Session is closed',
retryable: false,
public: true,
action: 'Create a new session.',
},
'session.permission_mode_invalid': {
title: 'Invalid permission mode',
retryable: false,
public: true,
action: 'Use one of: yolo / manual / auto.',
},
'session.thinking_empty': {
title: 'Thinking value is empty',
retryable: false,
public: true,
action: 'Provide a non-empty thinking option.',
},
'session.model_empty': {
title: 'Model is empty',
retryable: false,
public: true,
action: 'Provide a non-empty model identifier.',
},
'session.plan_mode_invalid': {
title: 'Invalid plan mode',
retryable: false,
public: true,
action: 'Provide a boolean plan mode.',
},
'session.approval_handler_error': {
title: 'Approval handler threw',
retryable: false,
public: true,
action: 'Inspect the SDK approval handler for an unhandled exception.',
},
'session.question_handler_error': {
title: 'Question handler threw',
retryable: false,
public: true,
action: 'Inspect the SDK question handler for an unhandled exception.',
},
'session.init_failed': {
title: 'Session init failed',
retryable: false,
public: false,
action: 'Review the init failure details and try again.',
},
'agent.not_found': {
title: 'Agent not found',
retryable: false,
public: true,
action: 'Check the agent id or list available agents.',
},
'turn.agent_busy': {
title: 'Agent is busy',
retryable: true,
public: true,
action: 'Wait for the current turn to finish or steer it.',
},
'goal.already_exists': {
title: 'A goal is already active',
retryable: false,
public: true,
action: 'Use `/goal replace <objective>` to replace the current goal.',
},
'goal.not_found': {
title: 'No goal found',
retryable: false,
public: true,
action: 'Start a goal with `/goal <objective>` first.',
},
'goal.objective_empty': {
title: 'Goal objective is empty',
retryable: false,
public: true,
action: 'Provide a non-empty objective.',
},
'goal.objective_too_long': {
title: 'Goal objective is too long',
retryable: false,
public: true,
action: 'Keep the objective under 4000 characters; reference long details by file path.',
},
'goal.status_invalid': {
title: 'Invalid goal status transition',
retryable: false,
public: true,
action: 'Use a status allowed for this actor (complete, blocked, or impossible).',
},
'goal.metadata_reserved': {
title: 'Goal metadata is reserved',
retryable: false,
public: true,
action: 'Do not write metadata.custom.goal directly; use the goal lifecycle methods.',
},
'goal.not_resumable': {
title: 'Goal is not resumable',
retryable: false,
public: true,
action: 'Only paused goals can be resumed.',
},
'model.not_configured': {
title: 'No model configured',
retryable: false,
public: true,
action: 'Set a default model in config.toml or via setModel.',
},
'model.config_invalid': {
title: 'Invalid model configuration',
retryable: false,
public: true,
action: 'Check the model and provider entries in config.toml.',
},
'auth.login_required': {
title: 'Login required',
retryable: false,
public: true,
action: 'Run the login flow for the provider before retrying.',
},
'context.overflow': {
title: 'Context window overflow',
retryable: true,
public: true,
action: 'Compact the conversation or start a new session.',
},
'loop.max_steps_exceeded': {
title: 'Turn exceeded max steps',
retryable: false,
public: true,
action: 'Increase loop_control.max_steps_per_turn in config.toml or split the task.',
},
'provider.api_error': {
title: 'Provider API error',
retryable: false,
public: true,
action: 'Inspect details.statusCode / details.requestId; check provider status.',
},
'provider.filtered': {
title: 'Provider filtered response',
retryable: false,
public: true,
action: 'Revise the prompt or model configuration to avoid provider safety filtering.',
},
'provider.rate_limit': {
title: 'Provider rate limit',
retryable: true,
public: true,
action: 'Retry after a delay or reduce request frequency.',
},
'provider.auth_error': {
title: 'Provider authentication error',
retryable: false,
public: true,
action: 'Re-authenticate with the provider.',
},
'provider.connection_error': {
title: 'Provider connection error',
retryable: true,
public: true,
action: 'Check network connectivity and retry.',
},
'skill.not_found': {
title: 'Skill not found',
retryable: false,
public: true,
action: 'List available skills via the skill registry.',
},
'skill.type_unsupported': {
title: 'Skill type not supported',
retryable: false,
public: true,
action: 'Only inline skills can be activated by the user.',
},
'skill.name_empty': {
title: 'Skill name is empty',
retryable: false,
public: true,
action: 'Provide a non-empty skill name.',
},
'records.write_failed': {
title: 'Failed to write records',
retryable: true,
public: true,
action: 'Check disk space and permissions on the session directory.',
},
'compaction.failed': {
title: 'Compaction failed',
retryable: false,
public: true,
action: 'Inspect logs and consider increasing compaction limits.',
},
'compaction.unable': {
title: 'Unable to compact',
retryable: false,
public: true,
action: 'The current history has no prefix that can be compacted (e.g. only a pending user message). Start a new turn or session instead.',
},
'task.task_id_empty': {
title: 'Background task id is empty',
retryable: false,
public: true,
action: 'Provide a non-empty task id.',
},
'mcp.server_not_found': {
title: 'MCP server not found',
retryable: false,
public: true,
action: 'List configured MCP servers and check the requested name.',
},
'mcp.server_disabled': {
title: 'MCP server is disabled',
retryable: false,
public: true,
action: 'Enable the MCP server entry in config before reconnecting.',
},
'mcp.startup_failed': {
title: 'MCP server startup failed',
retryable: true,
public: true,
action: 'Inspect the MCP server log or call reconnect once the server is healthy.',
},
'mcp.tool_name_collision': {
title: 'MCP tool name collision',
retryable: false,
public: true,
action: 'Rename one of the colliding MCP tools or servers so their qualified names are unique.',
},
'mcp.oauth_failed': {
title: 'MCP OAuth authorization failed',
retryable: true,
public: true,
action: 'Begin the authorization flow again; inspect the error details if it keeps failing.',
},
'plugin.not_found': {
title: 'Plugin not found',
retryable: false,
public: true,
action: 'List installed plugins via /plugins and check the requested id.',
},
'plugin.load_failed': {
title: 'Plugin state failed to load',
retryable: true,
public: true,
action: 'Fix the installed.json file under $KIMI_CODE_HOME/plugins/ and run /plugins reload.',
},
'request.invalid': {
title: 'Invalid request',
retryable: false,
public: true,
action: 'Check the input shape matches the API contract.',
},
'request.work_dir_required': {
title: 'workDir is required',
retryable: false,
public: true,
action: 'Provide workDir in the request payload.',
},
'request.prompt_input_empty': {
title: 'Prompt input is empty',
retryable: false,
public: true,
action: 'Provide non-empty prompt input.',
},
'shell.git_bash_not_found': {
title: 'Git Bash not found',
retryable: false,
public: true,
action: 'Install Git for Windows from https://gitforwindows.org/ or set KIMI_SHELL_PATH to a bash.exe.',
},
not_implemented: {
title: 'Not implemented',
retryable: false,
public: true,
action: 'This feature is not implemented yet.',
},
internal: {
title: 'Internal error',
retryable: false,
public: true,
action: 'Inspect logs or report the issue with diagnostics.',
},
} as const satisfies Record<KimiErrorCode, KimiErrorInfo>;
export function isKimiErrorCode(code: unknown): code is KimiErrorCode {
return typeof code === 'string' && Object.hasOwn(KIMI_ERROR_INFO, code);
}
export interface KimiErrorOptions {
readonly details?: Record<string, unknown>;
readonly cause?: unknown;
}
export class KimiError extends Error {
readonly code: KimiErrorCode;
readonly details?: Record<string, unknown>;
override readonly cause?: unknown;
constructor(code: KimiErrorCode, message: string, options: KimiErrorOptions = {}) {
super(message);
this.name = 'KimiError';
this.code = code;
this.details = options.details;
this.cause = options.cause;
}
}
export interface KimiErrorPayload {
readonly code: KimiErrorCode;
readonly message: string;
readonly name?: string;
readonly details?: Record<string, unknown>;
readonly retryable: boolean;
}
export function isKimiError(error: unknown): error is KimiError {
return error instanceof KimiError;
}
export function makeErrorPayload(
code: KimiErrorCode,
message: string,
options?: { readonly details?: Record<string, unknown>; readonly name?: string },
): KimiErrorPayload {
return {
code,
message,
name: options?.name,
details: options?.details,
retryable: KIMI_ERROR_INFO[code].retryable,
};
}
export function toKimiErrorPayload(error: unknown): KimiErrorPayload {
if (isKimiError(error)) {
return {
code: error.code,
message: error.message,
name: error.name,
details: error.details,
retryable: KIMI_ERROR_INFO[error.code].retryable,
};
}
if (error instanceof APIStatusError) {
const code: KimiErrorCode =
error instanceof APIProviderQuotaExhaustedError
? ErrorCodes.PROVIDER_API_ERROR
: error.statusCode === 429
? ErrorCodes.PROVIDER_RATE_LIMIT
: error.statusCode === 401
? ErrorCodes.PROVIDER_AUTH_ERROR
: ErrorCodes.PROVIDER_API_ERROR;
return {
code,
message: sanitizeStatusErrorMessage(error.message),
name: error.name,
details: {
statusCode: error.statusCode,
requestId: error.requestId,
},
retryable: KIMI_ERROR_INFO[code].retryable,
};
}
if (error instanceof APIConnectionError || error instanceof APITimeoutError) {
return {
code: ErrorCodes.PROVIDER_CONNECTION_ERROR,
message: error.message,
name: error.name,
retryable: KIMI_ERROR_INFO[ErrorCodes.PROVIDER_CONNECTION_ERROR].retryable,
};
}
if (error instanceof APIEmptyResponseError) {
const code =
error.finishReason === 'filtered'
? ErrorCodes.PROVIDER_FILTERED
: ErrorCodes.PROVIDER_API_ERROR;
return {
code,
message: error.message,
name: error.name,
details: {
finishReason: error.finishReason,
rawFinishReason: error.rawFinishReason,
},
retryable: KIMI_ERROR_INFO[code].retryable,
};
}
if (error instanceof ChatProviderError) {
return {
code: ErrorCodes.PROVIDER_API_ERROR,
message: error.message,
name: error.name,
retryable: KIMI_ERROR_INFO[ErrorCodes.PROVIDER_API_ERROR].retryable,
};
}
if (error instanceof Error) {
return {
code: ErrorCodes.INTERNAL,
message: error.message,
name: error.name,
retryable: KIMI_ERROR_INFO[ErrorCodes.INTERNAL].retryable,
};
}
return {
code: ErrorCodes.INTERNAL,
message: String(error),
retryable: KIMI_ERROR_INFO[ErrorCodes.INTERNAL].retryable,
};
}
function sanitizeStatusErrorMessage(message: string): string {
const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(message);
const extracted = titleMatch?.[1]?.trim();
const normalized = extracted !== undefined && extracted.length > 0 ? extracted : message;
return normalized.replaceAll('\r', '');
}
export function fromKimiErrorPayload(payload: KimiErrorPayload): KimiError {
return new KimiError(payload.code, payload.message, {
details: payload.details,
});
}
|