error.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { ConfigMarkdown } from "@/config/markdown"
  2. import { Config } from "../config/config"
  3. import { MCP } from "../mcp"
  4. import { Provider } from "../provider/provider"
  5. import { UI } from "./ui"
  6. export function FormatError(input: unknown) {
  7. if (MCP.Failed.isInstance(input))
  8. return `MCP server "${input.data.name}" failed. Note, opencode does not support MCP authentication yet.`
  9. if (Provider.ModelNotFoundError.isInstance(input)) {
  10. const { providerID, modelID, suggestions } = input.data
  11. return [
  12. `Model not found: ${providerID}/${modelID}`,
  13. ...(Array.isArray(suggestions) && suggestions.length ? ["Did you mean: " + suggestions.join(", ")] : []),
  14. `Try: \`opencode models\` to list available models`,
  15. `Or check your config (opencode.json) provider/model names`,
  16. ].join("\n")
  17. }
  18. if (Provider.InitError.isInstance(input)) {
  19. return `Failed to initialize provider "${input.data.providerID}". Check credentials and configuration.`
  20. }
  21. if (Config.JsonError.isInstance(input)) {
  22. return (
  23. `Config file at ${input.data.path} is not valid JSON(C)` + (input.data.message ? `: ${input.data.message}` : "")
  24. )
  25. }
  26. if (Config.ConfigDirectoryTypoError.isInstance(input)) {
  27. return `Directory "${input.data.dir}" in ${input.data.path} is not valid. Rename the directory to "${input.data.suggestion}" or remove it. This is a common typo.`
  28. }
  29. if (ConfigMarkdown.FrontmatterError.isInstance(input)) {
  30. return `Failed to parse frontmatter in ${input.data.path}:\n${input.data.message}`
  31. }
  32. if (Config.InvalidError.isInstance(input))
  33. return [
  34. `Config file at ${input.data.path} is invalid` + (input.data.message ? `: ${input.data.message}` : ""),
  35. ...(input.data.issues?.map((issue) => "↳ " + issue.message + " " + issue.path.join(".")) ?? []),
  36. ].join("\n")
  37. if (UI.CancelledError.isInstance(input)) return ""
  38. }
  39. export function FormatUnknownError(input: unknown): string {
  40. if (input instanceof Error) {
  41. return input.stack ?? `${input.name}: ${input.message}`
  42. }
  43. if (typeof input === "object" && input !== null) {
  44. try {
  45. const json = JSON.stringify(input, null, 2)
  46. if (json && json !== "{}") return json
  47. } catch {}
  48. }
  49. return String(input)
  50. }