diff --git a/packages/cli/src/commands/commands.ts b/packages/cli/src/commands/commands.ts index b084368157b..241f57aa2a3 100644 --- a/packages/cli/src/commands/commands.ts +++ b/packages/cli/src/commands/commands.ts @@ -72,6 +72,30 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME ), }, }), + Spec.make("uninstall", { + description: "Uninstall OpenCode and remove all related files", + params: { + keepConfig: Flag.boolean("keep-config").pipe( + Flag.withAlias("c"), + Flag.withDescription("Keep configuration files"), + Flag.withDefault(false), + ), + keepData: Flag.boolean("keep-data").pipe( + Flag.withAlias("d"), + Flag.withDescription("Keep session data and snapshots"), + Flag.withDefault(false), + ), + dryRun: Flag.boolean("dry-run").pipe( + Flag.withDescription("Show what would be removed without removing"), + Flag.withDefault(false), + ), + force: Flag.boolean("force").pipe( + Flag.withAlias("f"), + Flag.withDescription("Skip confirmation prompts"), + Flag.withDefault(false), + ), + }, + }), Spec.make("acp", { description: "Start an Agent Client Protocol server" }), Spec.make("api", { description: "Make a request to the running server", diff --git a/packages/cli/src/commands/handlers/uninstall.ts b/packages/cli/src/commands/handlers/uninstall.ts new file mode 100644 index 00000000000..6cf4fa821c0 --- /dev/null +++ b/packages/cli/src/commands/handlers/uninstall.ts @@ -0,0 +1,167 @@ +import { confirm, intro, log, outro, spinner } from "@clack/prompts" +import { Service } from "@opencode/client/effect/service" +import { Global } from "@opencode/util/global" +import { Effect, FileSystem } from "effect" +import path from "node:path" +import { Commands } from "../commands" +import { Runtime } from "../../framework/runtime" +import { ServerConnection } from "../../services/server-connection" +import { Updater } from "../../services/updater" +import { handlePromptErrors, prompt, requireInteractive } from "../../ui/prompt" +import { errorMessage } from "../../util/error" + +export default Runtime.handler( + Commands.commands.uninstall, + Effect.fn("cli.uninstall")(function* (input) { + intro("Uninstall OpenCode") + const fs = yield* FileSystem.FileSystem + const global = yield* Global.Service + const updater = yield* Updater.Service + const method = yield* updater.method() + const removal = method ? updater.removal(method) : undefined + const directories = [ + { path: global.data, label: "Data", keep: input.keepData }, + { path: global.cache, label: "Cache", keep: false }, + { path: global.config, label: "Config", keep: input.keepConfig }, + { path: global.state, label: "State", keep: false }, + ] + // All channels share these directories. Stop their owners before deleting state or data. + // Read registrations directly: ServiceConfig.options() can migrate files even during a dry run. + const services = (yield* fs.exists(global.state)) + ? (yield* fs.readDirectory(global.state)).filter((name) => /^service(?:-.*)?\.json$/.test(name)) + : [] + const shell = method === "curl" ? yield* shellConfigs(global.home) : [] + + log.info(`Installation method: ${method ?? "unknown"}`) + log.message("The following global files will be removed (shared by OpenCode versions and channels):") + yield* Effect.forEach(directories, (directory) => + Effect.gen(function* () { + if (!(yield* fs.exists(directory.path))) return + log.info(` ${directory.label}: ${directory.path}${directory.keep ? " (keeping)" : ""}`) + }), + ) + services.forEach((name) => + log.info(` Stop background service and persistent terminals: ${path.join(global.state, name)}`), + ) + shell.forEach((file) => log.info(` Shell PATH: ${file}`)) + if (removal) log.info(` Package: ${removal.command.join(" ")}`) + if (method === "curl") log.info(` Binary (manual removal): ${process.execPath}`) + if (!method) log.warn("Could not detect the installation method. Remove the installation manually after cleanup.") + + if (input.dryRun) { + log.warn("Dry run - no changes made") + outro("Done") + return + } + if (!input.force) { + yield* requireInteractive("Use --force to uninstall without an interactive terminal, or --dry-run to preview.") + const accepted = yield* prompt(() => + confirm({ message: "Are you sure you want to uninstall?", initialValue: false }), + ) + if (!accepted) { + outro("Cancelled") + return + } + } + + const progress = spinner() + if (services.length) { + progress.start("Stopping background services...") + yield* Effect.forEach(services, (name) => + Effect.gen(function* () { + const options = { file: path.join(global.state, name) } + yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore) + yield* Service.stop(options) + }), + ).pipe( + Effect.tap(() => Effect.sync(() => progress.stop("Background services stopped"))), + Effect.tapCause(() => Effect.sync(() => progress.stop("Failed to stop background services", 1))), + ) + } + + const errors: string[] = [] + yield* Effect.forEach(directories, (directory) => + Effect.gen(function* () { + if (directory.keep) return + progress.start(`Removing ${directory.label}...`) + yield* fs.remove(directory.path, { recursive: true, force: true }).pipe( + Effect.tap(() => Effect.sync(() => progress.stop(`Removed ${directory.label}`))), + Effect.catch((error) => + Effect.sync(() => { + progress.stop(`Failed to remove ${directory.label}`, 1) + errors.push(`${directory.label}: ${errorMessage(error)}`) + }), + ), + ) + }), + ) + yield* Effect.forEach(shell, (file) => + fs.readFileString(file).pipe( + Effect.flatMap((content) => fs.writeFileString(file, cleanShellConfig(content))), + Effect.catch((error) => Effect.sync(() => errors.push(`Shell config ${file}: ${errorMessage(error)}`))), + ), + ) + if (removal) { + progress.start(`Running ${removal.command.join(" ")}...`) + yield* removal.run.pipe( + Effect.tap(() => Effect.sync(() => progress.stop("Package removed"))), + Effect.catch((error) => + Effect.sync(() => { + progress.stop("Package manager uninstall failed", 1) + errors.push(errorMessage(error)) + log.warn(`Run manually: ${removal.command.join(" ")}`) + }), + ), + ) + } + if (method === "curl") { + log.message("To finish removing the binary, run:") + log.info(` rm '${process.execPath.replaceAll("'", "'\\''")}'`) + } + if (errors.length) yield* Effect.fail(new Error(errors.join("\n"))) + outro("Done") + }, handlePromptErrors), +) + +const shellConfigs = Effect.fnUntraced(function* (home: string) { + const fs = yield* FileSystem.FileSystem + const bin = path.dirname(process.execPath) + // V1 and V2 curl installs share a PATH entry; retain it while another binary uses it. + if ((yield* fs.readDirectory(bin)).some((name) => name !== path.basename(process.execPath))) return [] + const xdg = process.env.XDG_CONFIG_HOME || path.join(home, ".config") + const zsh = process.env.ZDOTDIR || home + const candidates: Record = { + fish: [path.join(home, ".config/fish/config.fish"), path.join(xdg, "fish/config.fish")], + zsh: [ + path.join(zsh, ".zshrc"), + path.join(zsh, ".zshenv"), + path.join(xdg, "zsh/.zshrc"), + path.join(xdg, "zsh/.zshenv"), + ], + bash: [ + path.join(home, ".bashrc"), + path.join(home, ".bash_profile"), + path.join(home, ".profile"), + path.join(xdg, "bash/.bashrc"), + path.join(xdg, "bash/.bash_profile"), + ], + ash: [path.join(home, ".ashrc"), path.join(home, ".profile")], + sh: [path.join(home, ".ashrc"), path.join(home, ".profile")], + } + const files = [...new Set(candidates[path.basename(process.env.SHELL || "bash")] ?? candidates.bash)] + return yield* Effect.filter(files, (file) => + fs.readFileString(file).pipe( + Effect.map((content) => cleanShellConfig(content) !== content), + Effect.orElseSucceed(() => false), + ), + ) +}) + +function cleanShellConfig(content: string) { + const lines = content.split("\n") + const entry = (line: string) => + /^(?:export PATH=|fish_add_path\s)/.test(line.trim()) && line.includes(".opencode/bin") + return lines + .filter((line, index) => !entry(line) && !(line.trim() === "# opencode" && entry(lines[index + 1] ?? ""))) + .join("\n") +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 9bd36dfff20..9ff4fac6943 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -23,6 +23,7 @@ if (process.env.OPENCODE_SSH_ASKPASS_PORT) { const Handlers = Runtime.handlers(Commands, { $: () => import("./commands/handlers/default"), upgrade: () => import("./commands/handlers/upgrade"), + uninstall: () => import("./commands/handlers/uninstall"), acp: () => import("./commands/handlers/acp"), api: () => import("./commands/handlers/api"), auth: { diff --git a/packages/cli/src/services/updater.ts b/packages/cli/src/services/updater.ts index b9b6e2c2c7b..683893e3fdb 100644 --- a/packages/cli/src/services/updater.ts +++ b/packages/cli/src/services/updater.ts @@ -19,6 +19,9 @@ export interface Interface { readonly method: () => Effect.Effect readonly latest: () => Effect.Effect readonly upgrade: (method: Method, version: string) => Effect.Effect + readonly removal: (method: Method) => + | { readonly command: ReadonlyArray; readonly run: Effect.Effect } + | undefined } export const pollUpdates = Effect.fnUntraced(function* (input: { @@ -64,6 +67,8 @@ const make = Effect.gen(function* () { const manifest: { name: string; bin?: Record } = yield* fs .readFileString(path.join(directory, "package.json")) .pipe(Effect.flatMap((text) => Effect.try(() => JSON.parse(text)))) + // Source invocations run inside Bun or Node, which may themselves be npm packages. + if (!/^@opencode(?:-ai)?\/cli(?:-node)?$/.test(manifest.name)) return if (Object.values(manifest.bin ?? {}).some((bin) => path.resolve(directory, bin) === executable)) return manifest.name }).pipe(Effect.orElseSucceed(() => undefined)) @@ -119,6 +124,27 @@ const make = Effect.gen(function* () { return results.find((result) => result.result.stdout.includes(installedPackage))?.check.method }) + const removal = (method: Method) => { + if (method === "curl" || !installedPackage) return undefined + const commands = { + npm: ["npm", "uninstall", "--global", installedPackage], + pnpm: ["pnpm", "remove", "--global", installedPackage], + bun: ["bun", "remove", "--global", installedPackage], + yarn: ["yarn", "global", "remove", installedPackage], + } + const command = commands[method] + return { + command, + run: exec(command, "5 minutes").pipe( + Effect.flatMap((result) => + result.code === 0 + ? Effect.void + : Effect.fail(new Error(result.stderr.trim() || `Failed to uninstall with ${method}`)), + ), + ), + } + } + const release = Effect.fnUntraced(function* () { const response = yield* Effect.tryPromise({ try: (signal) => @@ -263,7 +289,7 @@ const make = Effect.gen(function* () { Effect.catch((error) => Effect.logWarning("update check failed", { error }).pipe(Effect.as(undefined))), ) - return Service.of({ run, check, apply, method, latest, upgrade }) + return Service.of({ run, check, apply, method, latest, upgrade, removal }) }) export const layer = Layer.effect(Service, make) diff --git a/packages/cli/test/fixture/upgrade.ts b/packages/cli/test/fixture/upgrade.ts index f6440a934d4..2cf2d39f163 100644 --- a/packages/cli/test/fixture/upgrade.ts +++ b/packages/cli/test/fixture/upgrade.ts @@ -15,6 +15,7 @@ await Effect.runPromise( run: () => Effect.die("Manual upgrades must not check for automatic updates"), check: () => Effect.die("Manual upgrades must not check for TUI updates"), apply: () => Effect.die("Manual upgrades must not apply TUI updates"), + removal: () => undefined, method: () => Effect.sync(() => { record("method") diff --git a/services/www/src/docs/content/cli/index.mdx b/services/www/src/docs/content/cli/index.mdx index 1d523d72d9d..153c79872ab 100644 --- a/services/www/src/docs/content/cli/index.mdx +++ b/services/www/src/docs/content/cli/index.mdx @@ -56,3 +56,26 @@ opencode2 --server http://localhost:4096 ``` See [Troubleshooting](/troubleshooting) for shared service diagnostics and the [API reference](/api) for server endpoints. + +## Uninstall + +Preview the files and installation that will be removed: + +```bash +opencode2 uninstall --dry-run +``` + +Run `opencode2 uninstall` to confirm removal. OpenCode stops registered background services and persistent terminals before +removing global data, cache, configuration, and state. These directories are shared by OpenCode versions and channels. + +To retain configuration and session data: + +```bash +opencode2 uninstall --keep-config --keep-data +``` + +- `--keep-config` (`-c`) retains configuration files. +- `--keep-data` (`-d`) retains session data and snapshots. Cache and state are still removed. +- `--force` (`-f`) skips confirmation; use it for noninteractive removal. +- Package-manager installations use the detected package manager. Curl installations print the final command to remove + the executable manually.