auth.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { AuthAnthropic } from "../../auth/anthropic"
  2. import { Auth } from "../../auth"
  3. import { cmd } from "./cmd"
  4. import * as prompts from "@clack/prompts"
  5. import open from "open"
  6. import { UI } from "../ui"
  7. import { ModelsDev } from "../../provider/models"
  8. import { map, pipe, sortBy, values } from "remeda"
  9. export const AuthCommand = cmd({
  10. command: "auth",
  11. describe: "manage credentials",
  12. builder: (yargs) =>
  13. yargs
  14. .command(AuthLoginCommand)
  15. .command(AuthLogoutCommand)
  16. .command(AuthListCommand)
  17. .demandCommand(),
  18. async handler() {},
  19. })
  20. export const AuthListCommand = cmd({
  21. command: "list",
  22. aliases: ["ls"],
  23. describe: "list providers",
  24. async handler() {
  25. UI.empty()
  26. prompts.intro("Credentials")
  27. const results = await Auth.all().then((x) => Object.entries(x))
  28. const database = await ModelsDev.get()
  29. for (const [providerID, result] of results) {
  30. const name = database[providerID]?.name || providerID
  31. prompts.log.info(`${name} ${UI.Style.TEXT_DIM}(${result.type})`)
  32. }
  33. prompts.outro(`${results.length} credentials`)
  34. },
  35. })
  36. export const AuthLoginCommand = cmd({
  37. command: "login",
  38. describe: "login to a provider",
  39. async handler() {
  40. UI.empty()
  41. prompts.intro("Add credential")
  42. const providers = await ModelsDev.get()
  43. const priority: Record<string, number> = {
  44. anthropic: 0,
  45. openai: 1,
  46. google: 2,
  47. }
  48. let provider = await prompts.select({
  49. message: "Select provider",
  50. maxItems: 8,
  51. options: [
  52. ...pipe(
  53. providers,
  54. values(),
  55. sortBy(
  56. (x) => priority[x.id] ?? 99,
  57. (x) => x.name ?? x.id,
  58. ),
  59. map((x) => ({
  60. label: x.name,
  61. value: x.id,
  62. hint: priority[x.id] === 0 ? "recommended" : undefined,
  63. })),
  64. ),
  65. {
  66. value: "other",
  67. label: "Other",
  68. },
  69. ],
  70. })
  71. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  72. if (provider === "other") {
  73. provider = await prompts.text({
  74. message: "Enter provider id",
  75. validate: (x) =>
  76. x.match(/^[a-z-]+$/) ? undefined : "a-z and hyphens only",
  77. })
  78. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  79. provider = provider.replace(/^@ai-sdk\//, "")
  80. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  81. prompts.log.warn(
  82. `This only stores a credential for ${provider} - you will need configure it in opencode.json, check the docs for examples.`,
  83. )
  84. }
  85. if (provider === "amazon-bedrock") {
  86. prompts.log.info(
  87. "Amazon bedrock can be configured with standard AWS environment variables like AWS_PROFILE or AWS_ACCESS_KEY_ID",
  88. )
  89. prompts.outro("Done")
  90. return
  91. }
  92. if (provider === "anthropic") {
  93. const method = await prompts.select({
  94. message: "Login method",
  95. options: [
  96. {
  97. label: "Claude Pro/Max",
  98. value: "oauth",
  99. },
  100. {
  101. label: "API Key",
  102. value: "api",
  103. },
  104. ],
  105. })
  106. if (prompts.isCancel(method)) throw new UI.CancelledError()
  107. if (method === "oauth") {
  108. // some weird bug where program exits without this
  109. await new Promise((resolve) => setTimeout(resolve, 10))
  110. const { url, verifier } = await AuthAnthropic.authorize()
  111. prompts.note("Trying to open browser...")
  112. try {
  113. await open(url)
  114. } catch (e) {
  115. prompts.log.error(
  116. "Failed to open browser perhaps you are running without a display or X server, please open the following URL in your browser:",
  117. )
  118. }
  119. prompts.log.info(url)
  120. const code = await prompts.text({
  121. message: "Paste the authorization code here: ",
  122. validate: (x) => (x.length > 0 ? undefined : "Required"),
  123. })
  124. if (prompts.isCancel(code)) throw new UI.CancelledError()
  125. await AuthAnthropic.exchange(code, verifier)
  126. .then(() => {
  127. prompts.log.success("Login successful")
  128. })
  129. .catch(() => {
  130. prompts.log.error("Invalid code")
  131. })
  132. prompts.outro("Done")
  133. return
  134. }
  135. }
  136. const key = await prompts.password({
  137. message: "Enter your API key",
  138. validate: (x) => (x.length > 0 ? undefined : "Required"),
  139. })
  140. if (prompts.isCancel(key)) throw new UI.CancelledError()
  141. await Auth.set(provider, {
  142. type: "api",
  143. key,
  144. })
  145. prompts.outro("Done")
  146. },
  147. })
  148. export const AuthLogoutCommand = cmd({
  149. command: "logout",
  150. describe: "logout from a configured provider",
  151. async handler() {
  152. UI.empty()
  153. const credentials = await Auth.all().then((x) => Object.entries(x))
  154. prompts.intro("Remove credential")
  155. if (credentials.length === 0) {
  156. prompts.log.error("No credentials found")
  157. return
  158. }
  159. const database = await ModelsDev.get()
  160. const providerID = await prompts.select({
  161. message: "Select provider",
  162. options: credentials.map(([key, value]) => ({
  163. label:
  164. (database[key]?.name || key) +
  165. UI.Style.TEXT_DIM +
  166. " (" +
  167. value.type +
  168. ")",
  169. value: key,
  170. })),
  171. })
  172. if (prompts.isCancel(providerID)) throw new UI.CancelledError()
  173. await Auth.remove(providerID)
  174. prompts.outro("Logout successful")
  175. },
  176. })