From d46588fe90b481afb6cd7f1442fad4f2786d4556 Mon Sep 17 00:00:00 2001 From: Filip <34747899+neriousy@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:03:35 +0200 Subject: [PATCH] feat(cli): publish and upgrade official WinGet packages (#54808) --- .github/workflows/publish.yml | 1 + packages/cli/src/services/retained-image.ts | 3 +- packages/cli/src/services/updater.ts | 91 +++++++- packages/cli/test/retained-image.test.ts | 13 ++ packages/cli/test/updater-install.test.ts | 65 ++++++ script/publish-winget.ts | 222 ++++++++++++++++++++ script/publish.ts | 7 + 7 files changed, 393 insertions(+), 9 deletions(-) create mode 100644 script/publish-winget.ts diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index eb6e1c3b2b3..04f1232aa70 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -652,6 +652,7 @@ jobs: TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} OPENCODE_DESKTOP_DIST: /tmp/desktop + WINGET_GITHUB_TOKEN: ${{ secrets.WINGET_GITHUB_TOKEN }} CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968 CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} diff --git a/packages/cli/src/services/retained-image.ts b/packages/cli/src/services/retained-image.ts index 503e8dbd8c5..ef1521ac3ac 100644 --- a/packages/cli/src/services/retained-image.ts +++ b/packages/cli/src/services/retained-image.ts @@ -52,7 +52,7 @@ export const relocate = Effect.fnUntraced(function* (directory: string, destinat /** * Whether the running binary was installed by a package manager or the curl installer, the installs - * bun can hang on. The updater decides the same question from the package manifest it already reads. + * whose upgrades replace it in place. The updater decides the same question from the install location. */ export function installed(home: string) { const runtime = path.basename(process.execPath, path.extname(process.execPath)).toLowerCase() @@ -60,6 +60,7 @@ export function installed(home: string) { const executable = path.resolve(process.execPath) return ( executable.split(path.sep).includes("node_modules") || + /[\\/]winget[\\/]packages[\\/]/i.test(executable) || executable === path.resolve(home, ".opencode", "bin", "opencode.exe") ) } diff --git a/packages/cli/src/services/updater.ts b/packages/cli/src/services/updater.ts index 618265edc3c..736e8f8ee70 100644 --- a/packages/cli/src/services/updater.ts +++ b/packages/cli/src/services/updater.ts @@ -11,7 +11,7 @@ import { RetainedImage } from "./retained-image" import { action, parseReleaseVersion, type Policy } from "./updater-action" import { errorMessage } from "../util/error" -export const methods = ["curl", "npm", "pnpm", "bun", "yarn", "vp", "brew"] as const +export const methods = ["curl", "npm", "pnpm", "bun", "yarn", "vp", "brew", "winget"] as const export type Method = (typeof methods)[number] export type RunResult = { readonly type: "available" | "installed"; readonly version: string } @@ -53,8 +53,20 @@ const installNames: Record = { yarn: "Yarn", vp: "Vite+", brew: "Homebrew", + winget: "WinGet", } +const wingetPackage = "Anomaly.OpenCode" +const wingetArgs = [ + "--id", + wingetPackage, + "--exact", + "--source", + "winget", + "--accept-source-agreements", + "--disable-interactivity", +] + function conciseDetail(input: string) { const lines = stripVTControlCharacters(input) .trim() @@ -146,6 +158,8 @@ const make = Effect.gen(function* () { const installedFormula = ["opencode", "opencode-beta", "opencode-v2"].find((name) => executable.includes(`${path.sep}Cellar${path.sep}${name}${path.sep}`), ) + // WinGet extracts portable packages into a directory named after the package identifier. + const installedWinget = /[\\/]winget[\\/]packages[\\/]anomaly\.opencode_/i.test(executable) const readPolicy = Effect.fnUntraced(function* () { const values = yield* Effect.forEach(["config.json", "opencode.json", "opencode.jsonc"], (name) => @@ -200,6 +214,7 @@ const make = Effect.gen(function* () { const method = Effect.fnUntraced(function* () { if (executable === curlBinary) return "curl" if (installedFormula) return "brew" + if (installedWinget) return "winget" if (!installedPackage) return const parts = executable.toLowerCase().split(path.sep).map((part) => part.replace(/^\./, "")) @@ -229,7 +244,8 @@ const make = Effect.gen(function* () { })?.check.method }) - const removal = (method: Method) => { + const removalCommand = (method: Method) => { + if (method === "winget") return ["winget", "uninstall", ...wingetArgs] if (method === "curl" || method === "brew" || !installedPackage) return undefined const commands = { npm: ["npm", "uninstall", "--global", installedPackage], @@ -238,7 +254,12 @@ const make = Effect.gen(function* () { yarn: ["yarn", "global", "remove", installedPackage], vp: ["vp", "uninstall", "-g", installedPackage], } - const command = commands[method] + return commands[method] + } + + const removal = (method: Method) => { + const command = removalCommand(method) + if (!command) return undefined return { command, run: retaining( @@ -309,10 +330,39 @@ const make = Effect.gen(function* () { return { package: packageName, version } }) + // WinGet moderates every submission, so only its own index knows which release it can install. + const wingetVersion = Effect.fnUntraced(function* () { + const failure = (detail: string, cause?: unknown) => + new UpgradeError( + { + title: "Could not check for OpenCode updates", + detail, + command: ["winget", "search", ...wingetArgs].join(" "), + retry: "Fix the issue above, then run opencode upgrade again.", + }, + cause === undefined ? undefined : { cause }, + ) + const result = yield* exec(["winget", "search", ...wingetArgs], "1 minute").pipe( + Effect.mapError((cause) => failure(errorDetail(cause), cause)), + ) + // Column headers are localized, but the result row always lists the identifier followed by the version. + const version = result.stdout + .split(/\r?\n|\r/) + .map((line) => line.trim().split(/\s+/)) + .flatMap((tokens) => { + const index = tokens.findIndex((token) => token.toLowerCase() === wingetPackage.toLowerCase()) + return index === -1 ? [] : tokens.slice(index + 1, index + 2) + }) + .find((token) => parseReleaseVersion(token)) + if (result.code !== 0 || !version) return yield* Effect.fail(failure(resultDetail(result))) + return version + }) + const latest = (selected?: Method) => (selected ? Effect.succeed(selected) : method()).pipe( - Effect.flatMap(release), - Effect.map((data) => data.version), + Effect.flatMap((method) => + method === "winget" ? wingetVersion() : release(method).pipe(Effect.map((data) => data.version)), + ), ) const temporaryDirectory = (prefix: string) => @@ -326,7 +376,12 @@ const make = Effect.gen(function* () { const retaining = (method: Method, effect: Effect.Effect, directory = global.cache) => { if (process.platform !== "win32" || method === "brew") return effect // Only the installed binary is at stake; source checkouts run inside bun or node. - const owned = method === "curl" ? executable === curlBinary : installedPackage !== undefined + const owned = + method === "curl" + ? executable === curlBinary + : method === "winget" + ? installedWinget + : installedPackage !== undefined if (!owned) return effect return Effect.scoped(RetainedImage.retain(directory, "upgrade").pipe(Effect.andThen(effect))).pipe( Effect.provideService(FileSystem.FileSystem, fs), @@ -371,12 +426,16 @@ const make = Effect.gen(function* () { if (!parseReleaseVersion(input)) return yield* Effect.fail(new Error(`Invalid version: ${input}`)) const version = input.trim().replace(/^v/, "") const packageName = - method === "brew" && installedFormula === "opencode" ? "opencode" : (yield* release(method)).package + method === "winget" + ? wingetPackage + : method === "brew" && installedFormula === "opencode" + ? "opencode" + : (yield* release(method)).package const target = `${packageName}@${version}` if (installedPackage && packageName !== installedPackage && (method === "pnpm" || method === "yarn")) { return yield* Effect.fail(new Error(`Reinstall ${target} with ${method} to migrate from ${installedPackage}.`)) } - const commands: Record, string[]> = { + const commands: Record, string[]> = { // Keep the old package: uninstalling it can unlink the replacement command. npm: [ "npm", @@ -436,6 +495,22 @@ const make = Effect.gen(function* () { ) } if (method === "brew") return yield* runUpgrade({ method, command: ["brew", "upgrade", packageName] }) + if (method === "winget") + return yield* retaining( + method, + runUpgrade({ + method, + command: [ + "winget", + "upgrade", + ...wingetArgs, + "--version", + version, + "--silent", + "--accept-package-agreements", + ], + }), + ) return yield* retaining(method, runUpgrade({ method, command: commands[method] })) }), ).pipe( diff --git a/packages/cli/test/retained-image.test.ts b/packages/cli/test/retained-image.test.ts index 6133b4ba728..e6e8f659327 100644 --- a/packages/cli/test/retained-image.test.ts +++ b/packages/cli/test/retained-image.test.ts @@ -68,6 +68,19 @@ windows("installed accepts package-manager and curl binaries only", () => const cases = [ [path.join(home, ".bun", "install", "global", "node_modules", "@opencode", "cli", "bin", "opencode.exe"), true], [path.join(home, ".opencode", "bin", "opencode.exe"), true], + [ + path.join( + home, + "AppData", + "Local", + "Microsoft", + "WinGet", + "Packages", + "Anomaly.OpenCode_Microsoft.Winget.Source_8wekyb3d8bbwe", + "opencode.exe", + ), + true, + ], [path.join(home, "AppData", "Local", "Programs", "OpenCode", "resources", "opencode-cli.exe"), false], [path.join(home, "node_modules", "bun", "bin", "bun.exe"), false], ] as const diff --git a/packages/cli/test/updater-install.test.ts b/packages/cli/test/updater-install.test.ts index 675c6a45b82..8c7bc742c44 100644 --- a/packages/cli/test/updater-install.test.ts +++ b/packages/cli/test/updater-install.test.ts @@ -340,6 +340,71 @@ it.live("Homebrew Core installs check and upgrade the Core formula", () => ) }) +const winget = (search: Partial) => + fixture( + (command) => (command.args[0] === "search" ? search : {}), + "@opencode/cli", + false, + "@opencode/cli", + undefined, + (root) => + Effect.succeed( + path.join( + root, + "AppData", + "Local", + "Microsoft", + "WinGet", + "Packages", + "Anomaly.OpenCode_Microsoft.Winget.Source_8wekyb3d8bbwe", + "opencode.exe", + ), + ), + ) +const wingetArgs = [ + "--id", + "Anomaly.OpenCode", + "--exact", + "--source", + "winget", + "--accept-source-agreements", + "--disable-interactivity", +] + +it.live("WinGet installs check, upgrade, and remove the version in the WinGet index", () => + Effect.gen(function* () { + const test = yield* winget({ + stdout: Buffer.from( + "Name Id Version\r\n------------------------------\r\nOpenCode Anomaly.OpenCode 2.0.28\r\n", + ), + }) + expect(yield* test.updater.method()).toBe("winget") + expect(yield* test.updater.latest()).toBe("2.0.28") + yield* test.updater.upgrade("winget", "v2.0.28") + const removal = test.updater.removal("winget") + if (!removal) return yield* Effect.die("Expected winget removal command") + yield* removal.run + expect(test.commands).toEqual([ + ["winget", "search", ...wingetArgs], + ["winget", "upgrade", ...wingetArgs, "--version", "2.0.28", "--silent", "--accept-package-agreements"], + ["winget", "uninstall", ...wingetArgs], + ]) + // WinGet moderates submissions, so the OpenCode release service may list a version WinGet cannot install yet. + expect(test.requests).toEqual([]) + }), +) + +it.live("WinGet update checks report a missing package instead of a version", () => + Effect.gen(function* () { + const test = yield* winget({ + exitCode: -1978335212, + stdout: Buffer.from("No package found matching input criteria.\r\n"), + }) + const error = yield* test.updater.latest().pipe(Effect.flip) + expect(error.message).toBe("No package found matching input criteria.") + }), +) + // Links are named opencode-upgrade--.exe; read them from inside the installer run. const links = (directory: string) => existsSync(directory) ? readdirSync(directory).filter((name) => name.startsWith("opencode-")) : [] diff --git a/script/publish-winget.ts b/script/publish-winget.ts new file mode 100644 index 00000000000..9a38abdc153 --- /dev/null +++ b/script/publish-winget.ts @@ -0,0 +1,222 @@ +#!/usr/bin/env bun + +import { Script } from "@opencode/script" +import { mkdir, rm } from "node:fs/promises" +import path from "node:path" +import { fileURLToPath } from "node:url" + +if (Script.channel !== "latest" || !/^\d+\.\d+\.\d+$/.test(Script.version)) { + throw new Error("WinGet publishing requires a latest release version") +} + +const root = fileURLToPath(new URL("..", import.meta.url)) +const dryRun = process.argv.includes("--dry-run") +const token = process.env.WINGET_GITHUB_TOKEN +const cli = path.resolve(process.env.OPENCODE_CLI_DIST ?? path.join(root, "packages", "cli", "dist")) +const desktop = process.env.OPENCODE_DESKTOP_DIST +if (!desktop) throw new Error("OPENCODE_DESKTOP_DIST is required") +const outdir = path.join(cli, "winget") +const manifestVersion = "1.12.0" + +const packages = [ + { + identifier: "Anomaly.OpenCode", + name: "OpenCode CLI", + moniker: "opencode", + description: "The open source AI coding agent for the terminal.", + installer: [ + "InstallerType: zip", + "NestedInstallerType: portable", + "NestedInstallerFiles:", + "- RelativeFilePath: opencode.exe", + " PortableCommandAlias: opencode", + "Commands:", + "- opencode", + ], + files: [ + { architecture: "x64", file: path.join(cli, "opencode-windows-x64-baseline.zip") }, + { architecture: "arm64", file: path.join(cli, "opencode-windows-arm64.zip") }, + ], + }, + { + identifier: "Anomaly.OpenCode.Desktop", + // Matches the display name the installer registers with Windows, without its version suffix. + name: "OpenCode", + moniker: "opencode-desktop", + description: "The open source AI coding agent as a desktop app.", + installer: [ + "InstallerType: nullsoft", + "Scope: user", + "UpgradeBehavior: install", + // electron-builder derives the NSIS uninstall key from the production app ID, ai.opencode.desktop. + "ProductCode: d074f30d-5f88-5885-b075-be1348cc7676", + "Protocols:", + "- opencode", + ], + files: [ + { architecture: "x64", file: path.join(desktop, "opencode-desktop-win-x64.exe") }, + { architecture: "arm64", file: path.join(desktop, "opencode-desktop-win-arm64.exe") }, + ], + }, +] + +await rm(outdir, { recursive: true, force: true }) +const prepared = await Promise.all(packages.map(prepare)) +prepared.forEach((item) => console.log(`Prepared ${item.identifier} ${Script.version} in ${item.directory}`)) +if (dryRun) process.exit(0) +if (!token) { + console.log("skipped WinGet submission: WINGET_GITHUB_TOKEN is not set") + process.exit(0) +} +for (const item of prepared) await submit(item) + +async function prepare(input: (typeof packages)[number]) { + const directory = path.join(outdir, input.identifier) + const header = (type: string) => [ + `# yaml-language-server: $schema=https://aka.ms/winget-manifest.${type}.${manifestVersion}.schema.json`, + "", + `PackageIdentifier: ${input.identifier}`, + `PackageVersion: ${Script.version}`, + ] + const footer = (type: string) => [`ManifestType: ${type}`, `ManifestVersion: ${manifestVersion}`, ""] + const installers = await Promise.all( + input.files.map(async (item) => { + const file = Bun.file(item.file) + if (!(await file.exists()) || !file.size) throw new Error(`Missing WinGet installer: ${item.file}`) + const sha256 = new Bun.CryptoHasher("sha256") + for await (const chunk of file.stream()) sha256.update(chunk) + return [ + `- Architecture: ${item.architecture}`, + ` InstallerUrl: https://opencode.ai/files/bin/${encodeURIComponent(Script.version)}/${path.basename(item.file)}`, + ` InstallerSha256: ${sha256.digest("hex").toUpperCase()}`, + ] + }), + ) + const manifests = { + [`${input.identifier}.yaml`]: [...header("version"), "DefaultLocale: en-US", ...footer("version")], + [`${input.identifier}.installer.yaml`]: [ + ...header("installer"), + ...input.installer, + `ReleaseDate: ${new Date().toISOString().slice(0, 10)}`, + "Installers:", + ...installers.flat(), + ...footer("installer"), + ], + [`${input.identifier}.locale.en-US.yaml`]: [ + ...header("defaultLocale"), + "PackageLocale: en-US", + // Matches the publisher the desktop installer registers with Windows. + "Publisher: OpenCode", + "PublisherUrl: https://anoma.ly/", + "PublisherSupportUrl: https://github.com/anomalyco/opencode/issues", + `PackageName: ${input.name}`, + "PackageUrl: https://opencode.ai/", + "License: MIT", + "LicenseUrl: https://github.com/anomalyco/opencode/blob/HEAD/LICENSE", + `ShortDescription: ${input.description}`, + `Moniker: ${input.moniker}`, + "Tags:", + "- ai", + "- coding-agent", + "- developer-tools", + "Documentations:", + "- DocumentLabel: Docs", + " DocumentUrl: https://opencode.ai/docs/", + ...footer("defaultLocale"), + ], + } + const files = Object.fromEntries(Object.entries(manifests).map(([name, lines]) => [name, lines.join("\n")])) + await mkdir(directory, { recursive: true }) + await Promise.all(Object.entries(files).map(([name, content]) => Bun.write(path.join(directory, name), content))) + return { identifier: input.identifier, directory, files } +} + +// Opens the pull request from the token owner's fork, the only way to contribute to microsoft/winget-pkgs. +async function submit(input: Awaited>) { + const upstream = "microsoft/winget-pkgs" + const folder = ["manifests", "a", ...input.identifier.split("."), Script.version].join("/") + const branch = `${input.identifier}-${Script.version}` + if ((await github(`/repos/${upstream}/contents/${folder}`)).status === 200) { + console.log(`${input.identifier} ${Script.version} is already in ${upstream}`) + return + } + const fork: { owner: { login: string }; full_name: string } = await json( + await github(`/repos/${upstream}/forks`, { method: "POST", body: { default_branch_only: true } }), + ) + const pulls: unknown[] = await json( + await github(`/repos/${upstream}/pulls?state=all&head=${encodeURIComponent(`${fork.owner.login}:${branch}`)}`), + ) + if (pulls.length) { + console.log(`${input.identifier} ${Script.version} already has a pull request`) + return + } + // Forks share objects with their upstream, so the branch can start from upstream master without syncing the fork. + const head: { object: { sha: string } } = await json(await github(`/repos/${upstream}/git/ref/heads/master`)) + const base: { tree: { sha: string } } = await json(await github(`/repos/${upstream}/git/commits/${head.object.sha}`)) + const tree: { sha: string } = await json( + await github(`/repos/${fork.full_name}/git/trees`, { + method: "POST", + body: { + base_tree: base.tree.sha, + tree: Object.entries(input.files).map(([name, content]) => ({ + path: `${folder}/${name}`, + mode: "100644", + type: "blob", + content, + })), + }, + }), + ) + const title = `New version: ${input.identifier} version ${Script.version}` + const commit: { sha: string } = await json( + await github(`/repos/${fork.full_name}/git/commits`, { + method: "POST", + body: { message: title, tree: tree.sha, parents: [head.object.sha] }, + }), + ) + const created = await github(`/repos/${fork.full_name}/git/refs`, { + method: "POST", + body: { ref: `refs/heads/${branch}`, sha: commit.sha }, + }) + // A retried release can find the branch from an attempt that failed before opening its pull request. + await json( + created.status === 422 + ? await github(`/repos/${fork.full_name}/git/refs/heads/${branch}`, { + method: "PATCH", + body: { sha: commit.sha, force: true }, + }) + : created, + ) + const run = process.env.GITHUB_RUN_ID + ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}` + : undefined + const pull: { html_url: string } = await json( + await github(`/repos/${upstream}/pulls`, { + method: "POST", + body: { + title, + head: `${fork.owner.login}:${branch}`, + base: "master", + body: `Published by the [OpenCode](https://github.com/anomalyco/opencode) release workflow${run ? ` in ${run}` : ""}.`, + }, + }), + ) + console.log(`Opened ${pull.html_url}`) +} + +function github(route: string, init?: { method?: string; body?: unknown }) { + return fetch(`https://api.github.com${route}`, { + method: init?.method ?? "GET", + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + body: init?.body === undefined ? undefined : JSON.stringify(init.body), + }) +} + +async function json(response: Response) { + if (!response.ok) throw new Error(`GitHub ${response.url} returned ${response.status}: ${await response.text()}`) + return response.json() +} diff --git a/script/publish.ts b/script/publish.ts index 4944ff45cca..f3c10dcf820 100755 --- a/script/publish.ts +++ b/script/publish.ts @@ -116,3 +116,10 @@ if (Script.release) { console.log("\n=== desktop ===\n") await $`bun ./packages/desktop/scripts/publish.ts` } + +if (Script.release && Script.channel === "latest") { + console.log("\n=== winget ===\n") + // Everything else is published by now, and WinGet validation can reject a submission for reasons unrelated to the release. + if ((await $`bun ./script/publish-winget.ts`.nothrow()).exitCode !== 0) + console.log("::warning::WinGet submission failed; see the winget step output above") +}