File size: 1,814 Bytes
c60f42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * AgentFS 调试 API 错误类型与 HTTP 映射。
 */

export class AgentFsDebugError extends Error {
  readonly status: number;
  readonly code: string;

  constructor(status: number, code: string, message: string) {
    super(message);
    this.name = "AgentFsDebugError";
    this.status = status;
    this.code = code;
  }
}

/** 把未知错误转成 JSON Response(channel 层统一 catch)。 */
export function jsonError(err: unknown): Response {
  if (err instanceof AgentFsDebugError) {
    return Response.json(
      { ok: false, error: { code: err.code, message: err.message } },
      { status: err.status },
    );
  }
  const message = err instanceof Error ? err.message : String(err);
  return Response.json(
    { ok: false, error: { code: "internal", message } },
    { status: 500 },
  );
}

/** 虚拟 FS 操作错误 → 调试 API 错误。 */
export function mapFsError(err: unknown, path: string): AgentFsDebugError {
  const code = (err as NodeJS.ErrnoException)?.code;
  if (code === "ENOENT") {
    return new AgentFsDebugError(404, "not_found", `路径不存在: ${path}`);
  }
  if (code === "ENOTDIR") {
    return new AgentFsDebugError(400, "not_directory", `不是目录: ${path}`);
  }
  if (code === "EISDIR") {
    return new AgentFsDebugError(400, "is_directory", `是目录: ${path}`);
  }
  const message = err instanceof Error ? err.message : String(err);
  return new AgentFsDebugError(500, "fs_error", message);
}

/** AgentFS.open 失败(常见:库被占用、损坏)。 */
export function mapAgentFsOpenError(
  err: unknown,
  label: string,
): AgentFsDebugError {
  const message = err instanceof Error ? err.message : String(err);
  return new AgentFsDebugError(
    503,
    "open_failed",
    `无法打开 AgentFS(${label}): ${message}`,
  );
}