|
| 1 | +import { Global } from "@opencode-ai/core/global" |
| 2 | +import { Flag } from "@opencode-ai/core/flag/flag" |
| 3 | +import { AppProcess } from "@opencode-ai/core/process" |
| 4 | +import { Flock } from "@opencode-ai/core/util/flock" |
| 5 | +import { |
| 6 | + InstallationChannel, |
| 7 | + InstallationLocal, |
| 8 | + InstallationVersion, |
| 9 | +} from "@opencode-ai/core/installation/version" |
| 10 | +import { Context, Duration, Effect, FileSystem, Layer, Option, Path, Schema, Terminal } from "effect" |
| 11 | +import { Prompt } from "effect/unstable/cli" |
| 12 | +import { ChildProcess } from "effect/unstable/process" |
| 13 | +import { parse, type ParseError } from "jsonc-parser" |
| 14 | +import path from "node:path" |
| 15 | +import semver from "semver" |
| 16 | + |
| 17 | +export type Policy = boolean | "notify" |
| 18 | +export type Action = "none" | "confirm" | "upgrade" |
| 19 | +type Method = "npm" | "pnpm" | "bun" | "yarn" |
| 20 | + |
| 21 | +const packageName = "@opencode-ai/cli" |
| 22 | +const checkInterval = 24 * 60 * 60 * 1_000 |
| 23 | + |
| 24 | +const State = Schema.Struct({ |
| 25 | + checked: Schema.Number, |
| 26 | + latest: Schema.String, |
| 27 | + dismissed: Schema.optional(Schema.String), |
| 28 | +}) |
| 29 | +type State = typeof State.Type |
| 30 | + |
| 31 | +export interface Interface { |
| 32 | + readonly check: (options: { interactive: boolean }) => Effect.Effect<void> |
| 33 | +} |
| 34 | + |
| 35 | +export class Service extends Context.Service<Service, Interface>()("@opencode/cli/Updater") {} |
| 36 | + |
| 37 | +export function decodePolicy(text: string): Policy | undefined { |
| 38 | + // The CLI only projects this host-level preference instead of initializing |
| 39 | + // the location-scoped server configuration graph. |
| 40 | + const errors: ParseError[] = [] |
| 41 | + const input: unknown = parse(text, errors, { allowTrailingComma: true }) |
| 42 | + if (errors.length || typeof input !== "object" || input === null || !("autoupdate" in input)) return |
| 43 | + const value = input.autoupdate |
| 44 | + if (typeof value === "boolean" || value === "notify") return value |
| 45 | +} |
| 46 | + |
| 47 | +export function action(current: string, latest: string, policy: Policy, interactive: boolean): Action { |
| 48 | + if (policy === false) return "none" |
| 49 | + if (!semver.valid(current) || !semver.valid(latest) || !semver.gt(latest, current)) return "none" |
| 50 | + // Major upgrades are never offered or installed automatically. |
| 51 | + if (semver.major(latest) !== semver.major(current)) return "none" |
| 52 | + if (semver.minor(latest) !== semver.minor(current)) return interactive ? "confirm" : "none" |
| 53 | + if (policy === "notify") return interactive ? "confirm" : "none" |
| 54 | + return "upgrade" |
| 55 | +} |
| 56 | + |
| 57 | +export const layer = Layer.effect( |
| 58 | + Service, |
| 59 | + Effect.gen(function* () { |
| 60 | + const fs = yield* FileSystem.FileSystem |
| 61 | + const global = yield* Global.Service |
| 62 | + const appProcess = yield* AppProcess.Service |
| 63 | + const effectPath = yield* Path.Path |
| 64 | + const terminal = yield* Terminal.Terminal |
| 65 | + const channel = InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-") |
| 66 | + const stateFile = path.join(global.state, `updater-${channel}.json`) |
| 67 | + const decodeState = Schema.decodeUnknownOption(Schema.fromJsonString(State)) |
| 68 | + |
| 69 | + const readPolicy = Effect.fnUntraced(function* () { |
| 70 | + const values = yield* Effect.forEach(["config.json", "opencode.json", "opencode.jsonc"], (name) => |
| 71 | + fs |
| 72 | + .readFileString(path.join(global.config, name)) |
| 73 | + .pipe(Effect.map(decodePolicy), Effect.catch(() => Effect.succeed(undefined))), |
| 74 | + ) |
| 75 | + return values.findLast((value) => value !== undefined) ?? true |
| 76 | + }) |
| 77 | + |
| 78 | + const readState = Effect.fnUntraced(function* () { |
| 79 | + const text = yield* fs.readFileString(stateFile).pipe(Effect.catch(() => Effect.succeed(undefined))) |
| 80 | + if (!text) return |
| 81 | + return Option.getOrUndefined(decodeState(text)) |
| 82 | + }) |
| 83 | + |
| 84 | + const writeState = Effect.fnUntraced(function* (state: State) { |
| 85 | + const temp = stateFile + ".tmp" |
| 86 | + yield* fs.makeDirectory(global.state, { recursive: true }) |
| 87 | + yield* fs.writeFileString(temp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 }) |
| 88 | + yield* fs.rename(temp, stateFile) |
| 89 | + }) |
| 90 | + |
| 91 | + const run = Effect.fnUntraced(function* (command: string[], timeout: Duration.Input = "10 seconds") { |
| 92 | + return yield* appProcess |
| 93 | + .run(ChildProcess.make(command[0], command.slice(1)), { |
| 94 | + timeout, |
| 95 | + maxOutputBytes: 100_000, |
| 96 | + maxErrorBytes: 100_000, |
| 97 | + }) |
| 98 | + .pipe( |
| 99 | + Effect.map((result) => ({ |
| 100 | + code: result.exitCode, |
| 101 | + stdout: result.stdout.toString("utf8"), |
| 102 | + stderr: result.stderr.toString("utf8"), |
| 103 | + })), |
| 104 | + Effect.catch(() => Effect.succeed({ code: 1, stdout: "", stderr: "" })), |
| 105 | + ) |
| 106 | + }) |
| 107 | + |
| 108 | + const method = Effect.fnUntraced(function* () { |
| 109 | + const checks: ReadonlyArray<{ method: Method; command: string[] }> = [ |
| 110 | + { method: "npm", command: ["npm", "list", "-g", "--depth=0", packageName] }, |
| 111 | + { method: "pnpm", command: ["pnpm", "list", "-g", "--depth=0", packageName] }, |
| 112 | + { method: "bun", command: ["bun", "pm", "ls", "-g"] }, |
| 113 | + { method: "yarn", command: ["yarn", "global", "list"] }, |
| 114 | + ] |
| 115 | + const results = yield* Effect.forEach( |
| 116 | + checks, |
| 117 | + (check) => run(check.command).pipe(Effect.map((result) => ({ check, result }))), |
| 118 | + { concurrency: "unbounded" }, |
| 119 | + ) |
| 120 | + return results.find((result) => result.result.stdout.includes(packageName))?.check.method |
| 121 | + }) |
| 122 | + |
| 123 | + const latest = Effect.fnUntraced(function* () { |
| 124 | + const response = yield* Effect.tryPromise({ |
| 125 | + try: () => |
| 126 | + fetch( |
| 127 | + `https://registry.npmjs.org/${encodeURIComponent(packageName)}/${encodeURIComponent(InstallationChannel)}`, |
| 128 | + { headers: { "User-Agent": `opencode/${InstallationVersion}` }, signal: AbortSignal.timeout(10_000) }, |
| 129 | + ), |
| 130 | + catch: (cause) => new Error("Failed to check for updates", { cause }), |
| 131 | + }) |
| 132 | + if (!response.ok) return yield* Effect.fail(new Error(`Update check failed with status ${response.status}`)) |
| 133 | + const data = yield* Effect.tryPromise({ |
| 134 | + try: () => response.json(), |
| 135 | + catch: (cause) => new Error("Failed to read update information", { cause }), |
| 136 | + }) |
| 137 | + if (typeof data !== "object" || data === null || !("version" in data) || typeof data.version !== "string") { |
| 138 | + return yield* Effect.fail(new Error("Update information did not include a version")) |
| 139 | + } |
| 140 | + return data.version |
| 141 | + }) |
| 142 | + |
| 143 | + const upgrade = Effect.fnUntraced(function* (method: Method, version: string) { |
| 144 | + const target = `${packageName}@${version}` |
| 145 | + const commands: Record<Method, string[]> = { |
| 146 | + npm: ["npm", "install", "--global", target], |
| 147 | + pnpm: ["pnpm", "install", "--global", target], |
| 148 | + bun: ["bun", "install", "--global", target], |
| 149 | + yarn: ["yarn", "global", "add", target], |
| 150 | + } |
| 151 | + const result = yield* run(commands[method], "5 minutes") |
| 152 | + if (result.code === 0) return |
| 153 | + return yield* Effect.fail(new Error(result.stderr.trim() || `Failed to update with ${method}`)) |
| 154 | + }) |
| 155 | + |
| 156 | + const confirm = (version: string) => |
| 157 | + Prompt.confirm({ |
| 158 | + message: `Update OpenCode from ${InstallationVersion} to ${version}?`, |
| 159 | + initial: true, |
| 160 | + }).pipe( |
| 161 | + Effect.provideService(FileSystem.FileSystem, fs), |
| 162 | + Effect.provideService(Path.Path, effectPath), |
| 163 | + Effect.provideService(Terminal.Terminal, terminal), |
| 164 | + Effect.orElseSucceed(() => false), |
| 165 | + ) |
| 166 | + |
| 167 | + const check = Effect.fn("cli.updater.check")(function* (options: { interactive: boolean }) { |
| 168 | + if (InstallationLocal || Flag.OPENCODE_DISABLE_AUTOUPDATE) return |
| 169 | + const policy = yield* readPolicy() |
| 170 | + if (policy === false) return |
| 171 | + |
| 172 | + return yield* Effect.scoped( |
| 173 | + Effect.gen(function* () { |
| 174 | + yield* Flock.effect(`opencode-cli-updater-${channel}`, { dir: path.join(global.state, "locks") }) |
| 175 | + const previous = yield* readState() |
| 176 | + const now = Date.now() |
| 177 | + const version = |
| 178 | + previous && now - previous.checked < checkInterval |
| 179 | + ? previous.latest |
| 180 | + : yield* latest().pipe( |
| 181 | + Effect.tap((value) => |
| 182 | + writeState({ checked: now, latest: value, dismissed: previous?.dismissed }), |
| 183 | + ), |
| 184 | + ) |
| 185 | + const next = action( |
| 186 | + InstallationVersion, |
| 187 | + version, |
| 188 | + Flag.OPENCODE_ALWAYS_NOTIFY_UPDATE ? "notify" : policy, |
| 189 | + options.interactive && process.stdin.isTTY && process.stdout.isTTY, |
| 190 | + ) |
| 191 | + if (next === "none" || (next === "confirm" && previous?.dismissed === version)) return |
| 192 | + const install = next === "upgrade" || (yield* confirm(version)) |
| 193 | + if (!install) { |
| 194 | + yield* writeState({ checked: previous?.checked ?? now, latest: version, dismissed: version }) |
| 195 | + return |
| 196 | + } |
| 197 | + const detected = yield* method() |
| 198 | + if (!detected) return yield* Effect.logWarning("automatic update skipped: installation method not found") |
| 199 | + yield* upgrade(detected, version) |
| 200 | + yield* Effect.logInfo("updated OpenCode", { from: InstallationVersion, to: version, method: detected }) |
| 201 | + }), |
| 202 | + ) |
| 203 | + }, Effect.catchCause((cause) => Effect.logWarning("automatic update failed", { cause }))) |
| 204 | + |
| 205 | + return Service.of({ check }) |
| 206 | + }), |
| 207 | +) |
| 208 | + |
| 209 | +export const defaultLayer = layer.pipe(Layer.provide(AppProcess.defaultLayer), Layer.provide(Global.defaultLayer)) |
| 210 | + |
| 211 | +export * as Updater from "./updater" |
0 commit comments