chore: merge dev into beta

This commit is contained in:
vimtor 2026-10-26 22:57:27 +00:00
commit 2fca0148dd
599 changed files with 15266 additions and 15142 deletions

4
.github/CODEOWNERS vendored
View file

@ -1,3 +1,7 @@
# web + desktop packages
packages/app/ @Hona @Brendonovich
packages/desktop/ @Hona @Brendonovich
# CI and releases. Release jobs that hold secrets run only .github/workflows/release.yml and .github/release/,
# which makes this path the release security boundary.
/.github/ @anomalyco/ci-owners

View file

@ -1,71 +0,0 @@
#
# This file is intentionally in the wrong dir, will move and add later....
#
# name: publish-python-sdk
# on:
# release:
# types: [published]
# workflow_dispatch:
# jobs:
# publish:
# runs-on: ubuntu-latest
# permissions:
# contents: read
# steps:
# - name: Checkout repository
# uses: actions/checkout@v4
# - name: Setup Bun
# uses: oven-sh/setup-bun@v1
# with:
# bun-version: 1.2.21
# - name: Install dependencies (JS/Bun)
# run: bun install
# - name: Install uv
# shell: bash
# run: curl -LsSf https://astral.sh/uv/install.sh | sh
# - name: Generate Python SDK from OpenAPI (CLI)
# shell: bash
# run: |
# ~/.local/bin/uv run --project packages/sdk/python python packages/sdk/python/scripts/generate.py --source cli
# - name: Sync Python dependencies
# shell: bash
# run: |
# ~/.local/bin/uv sync --dev --project packages/sdk/python
# - name: Set version from release tag
# shell: bash
# run: |
# TAG="${GITHUB_REF_NAME:-}"
# if [ -z "$TAG" ]; then
# TAG="$(git describe --tags --abbrev=0 || echo 0.0.0)"
# fi
# echo "Using version: $TAG"
# VERSION="$TAG" ~/.local/bin/uv run --project packages/sdk/python python - <<'PY'
# import os, re, pathlib
# root = pathlib.Path('packages/sdk/python')
# pt = (root / 'pyproject.toml').read_text()
# version = os.environ.get('VERSION','0.0.0').lstrip('v')
# pt = re.sub(r'(?m)^(version\s*=\s*")[^"]+("\s*)$', f"\\1{version}\\2", pt)
# (root / 'pyproject.toml').write_text(pt)
# # Also update generator config override for consistency
# cfgp = root / 'openapi-python-client.yaml'
# if cfgp.exists():
# cfg = cfgp.read_text()
# cfg = re.sub(r'(?m)^(package_version_override:\s*)\S+$', f"\\1{version}", cfg)
# cfgp.write_text(cfg)
# PY
# - name: Build and publish to PyPI
# env:
# PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
# shell: bash
# run: |
# ~/.local/bin/uv run --project packages/sdk/python python packages/sdk/python/scripts/publish.py

21
.github/release/download/action.yml vendored Normal file
View file

@ -0,0 +1,21 @@
name: Download release artifacts
description: Downloads artifacts into $RUNNER_TEMP/in/<name> and verifies each against its SHA256SUMS.
inputs:
pattern:
description: Artifact name pattern
required: true
digests:
description: Space-separated name=digest pairs for artifacts made by sign jobs, from their job outputs
required: false
default: ""
runs:
using: composite
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
pattern: ${{ inputs.pattern }}
path: ${{ runner.temp }}/in
- shell: bash
run: bash "${GITHUB_ACTION_PATH//\\//}/../verify-artifacts.sh" "$RUNNER_TEMP/in"
env:
OPENCODE_DIGESTS: ${{ inputs.digests }}

109
.github/release/lib.sh vendored Normal file
View file

@ -0,0 +1,109 @@
# Shared helpers for the release scripts. Sourced, never executed.
#
# These scripts run in sign and publish jobs that hold secrets. They must never execute repository code
# or artifact contents: artifacts are data, and every value that names a destination comes from the
# environment the workflow sets (OPENCODE_VERSION, OPENCODE_CHANNEL, OPENCODE_DRY_RUN, ...).
set -euo pipefail
# shellcheck disable=SC2034 # used by the scripts that source this file
release_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
die() {
echo "::error::$*" >&2
exit 1
}
dry_run() {
[ "${OPENCODE_DRY_RUN:-false}" = true ]
}
sha256() {
if command -v sha256sum > /dev/null; then sha256sum "$@"; else shasum -a 256 "$@"; fi
}
# Windows runners pass D:\a\_temp style paths; Git Bash tools want /d/a/_temp.
posix() {
if command -v cygpath > /dev/null; then cygpath -u "$1"; else printf '%s' "$1"; fi
}
size() {
wc -c < "$1" | tr -d ' '
}
# Uploads files to opencode.ai/files/bin/<version>/ and prints the update-server file map.
upload_files() {
local credentials=false
for file in "$@"; do
test -s "$file" || die "Missing release file: $file"
local name type
name=$(basename "$file")
case "$name" in
*.tar.gz) type=application/gzip ;;
*.zip) type=application/zip ;;
*) type=application/octet-stream ;;
esac
if dry_run; then
echo "dry-run upload: bin/$OPENCODE_VERSION/$name" >&2
else
if [ "$credentials" = false ]; then
r2_credentials
credentials=true
fi
aws s3 cp "$file" "s3://opencode-production-files/bin/$OPENCODE_VERSION/$name" --only-show-errors \
--endpoint-url "https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com" \
--content-type "$type" --content-disposition "attachment; filename=\"$name\"" \
--cache-control "public, max-age=31536000, immutable" >&2
fi
jq -n --arg name "$name" --arg url "https://opencode.ai/files/bin/$OPENCODE_VERSION/$name" \
--arg sha256 "$(sha256 "$file" | cut -c1-64)" --argjson size "$(size "$file")" \
'{($name): {url: $url, sha256: $sha256, size: $size}}'
done | jq -s 'add'
}
# R2 accepts the API token ID as the access key and SHA-256(token) as the secret.
r2_credentials() {
local id
id=$(curl -fsS -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
"https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/tokens/verify" | jq -er .result.id)
export AWS_ACCESS_KEY_ID="$id"
AWS_SECRET_ACCESS_KEY=$(printf '%s' "$CLOUDFLARE_API_TOKEN" | sha256 | cut -c1-64)
export AWS_SECRET_ACCESS_KEY
export AWS_DEFAULT_REGION=auto AWS_REQUEST_CHECKSUM_CALCULATION=when_required AWS_RESPONSE_CHECKSUM_VALIDATION=when_required
}
# Registers one artifact with the update server: publish_update <name> <distribution> <metadata json>.
publish_update() {
local body status token attempt
body=$(jq -n --arg channel "$OPENCODE_CHANNEL" --arg version "$OPENCODE_VERSION" --arg name "$1" --arg distribution "$2" \
--argjson metadata "$3" '{channel: $channel, name: $name, distribution: $distribution, version: $version, metadata: $metadata}')
echo "$body" | jq .
if dry_run; then return; fi
token=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://update.opencode.ai" | jq -er .value)
for attempt in 1 2 3; do
status=$(curl -sS -o "$RUNNER_TEMP/update-response" -w '%{http_code}' -X POST https://opencode.ai/update/api/publish \
-H "Authorization: Bearer $token" -H "Content-Type: application/json" --data "$body")
if [ "$status" -lt 300 ]; then return; fi
cat "$RUNNER_TEMP/update-response"
# D1 can commit the upsert and still time out. Replaying the same artifact is safe.
if [ "$status" -lt 500 ] || [ "$attempt" = 3 ]; then die "Update server returned $status"; fi
sleep "$attempt"
done
}
# Clones a repository, lets a render script fill it, then commits and pushes any change:
# push_git <clone url> <commit message> <render script> [args...]. Dry runs render into an empty directory.
push_git() {
local url=$1 message=$2 dir
shift 2
dir=$(mktemp -d)
if ! dry_run; then git clone -q "$url" "$dir"; fi
"$@" "$dir"
if dry_run; then return; fi
git -C "$dir" add -A
if git -C "$dir" diff --cached --quiet; then return; fi
git -C "$dir" -c user.name="opencode-agent[bot]" -c user.email="opencode-agent[bot]@users.noreply.github.com" \
commit -q -m "$message"
git -C "$dir" push -q origin HEAD:master
}

65
.github/release/plan-release.sh vendored Executable file
View file

@ -0,0 +1,65 @@
#!/usr/bin/env bash
# plan-release.sh: decides version, channel and npm dist-tag from the event, ref and dispatch inputs
# (INPUT_BUMP, INPUT_VERSION) only, and writes them to $GITHUB_OUTPUT. Nothing here reads repository files.
#
# push or dispatch on dev -> dev 0.0.0-dev-<run> npm tag dev
# dispatch on dev with bump/version -> latest x.y.z npm tag latest
# push or dispatch on beta -> beta 0.0.0-beta-<run> desktop only
# pull_request -> pr 0.0.0-pr-<run> everything, dry run
. "$(dirname "$0")/lib.sh"
versioned=false
if [ -n "${INPUT_BUMP:-}" ] || [ -n "${INPUT_VERSION:-}" ]; then versioned=true; fi
case "$GITHUB_EVENT_NAME:$GITHUB_REF:$versioned" in
push:refs/heads/dev:false | workflow_dispatch:refs/heads/dev:false) channel="dev" ;;
workflow_dispatch:refs/heads/dev:true) channel="latest" ;;
push:refs/heads/beta:false | workflow_dispatch:refs/heads/beta:false) channel="beta" ;;
pull_request:*:false) channel="pr" ;;
*) die "$GITHUB_EVENT_NAME on $GITHUB_REF cannot publish (versioned: $versioned)" ;;
esac
if [ "$channel" = latest ] && [ -n "${INPUT_VERSION:-}" ]; then
version=$INPUT_VERSION
elif [ "$channel" = latest ]; then
current=$(curl -fsS https://registry.npmjs.org/-/package/@opencode%2fcli/dist-tags | jq -r .latest)
[[ "$current" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] || die "Unexpected latest version: $current"
major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]} patch=${BASH_REMATCH[3]}
case "$INPUT_BUMP" in
major) version="$((major + 1)).0.0" ;;
minor) version="$major.$((minor + 1)).0" ;;
*) version="$major.$minor.$((patch + 1))" ;;
esac
if [ "$major" -lt 2 ]; then version=2.0.0; fi
else
version="0.0.0-$channel-$GITHUB_RUN_NUMBER"
if [ "$GITHUB_RUN_ATTEMPT" != 1 ]; then version="$version.$GITHUB_RUN_ATTEMPT"; fi
fi
if [ "$channel" = latest ]; then
if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || [[ "$version" == 0.0.0-* ]]; then
die "Invalid release version: $version"
fi
status=$(curl -sS -o /dev/null -w '%{http_code}' "https://registry.npmjs.org/@opencode%2fcli/$version")
[ "$status" != 200 ] || die "@opencode/cli@$version is already published"
fi
# What each channel builds and publishes.
case "$channel" in
latest) npm_tag=latest cli=true desktop=true node=false release=true ;;
dev) npm_tag=dev cli=true desktop=false node=true release=false ;;
beta) npm_tag="" cli=false desktop=true node=false release=false ;;
pr) npm_tag=pr cli=true desktop=true node=true release=true ;;
esac
dry_run=false
if [ "$channel" = pr ]; then dry_run=true; fi
{
echo "version=$version"
echo "channel=$channel"
echo "npm_tag=$npm_tag"
echo "dry_run=$dry_run"
echo "cli=$cli"
echo "desktop=$desktop"
echo "node=$node"
echo "release=$release"
} | tee -a "$GITHUB_OUTPUT"

15
.github/release/publish-aur.sh vendored Executable file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env bash
# publish-aur.sh <build-npm dir>: updates opencode-beta on the AUR over SSH (AUR_KEY, pinned host key) and
# registers the aur update artifact.
. "$(dirname "$0")/lib.sh"
if ! dry_run; then
mkdir -p ~/.ssh
printf '%s\n' "$AUR_KEY" > ~/.ssh/aur
chmod 600 ~/.ssh/aur
echo "aur.archlinux.org ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEuBKrPzbawxA/k2g6NcyV5jmqwJ2s+zpgZGZ7tpLIcN" > ~/.ssh/known_hosts
export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/aur -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes"
fi
push_git ssh://aur@aur.archlinux.org/opencode-beta.git "chore: update opencode-beta to ${OPENCODE_VERSION//-/.}" \
bash "$release_dir/render-aur.sh" "$1"
publish_update cli aur '{"package": "opencode-beta"}'

23
.github/release/publish-cli.sh vendored Executable file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env bash
# publish-cli.sh <build-archives dir> <sign-macos dir> <sign-windows dir>: uploads the standalone CLI
# archives to opencode.ai/files and registers the cli (and, off latest, cli-node) update artifacts.
. "$(dirname "$0")/lib.sh"
archives=$1 macos=$2 windows=$3
cli=()
for target in linux-arm64 linux-x64 linux-x64-baseline linux-arm64-musl linux-x64-musl linux-x64-baseline-musl; do cli+=("$archives/opencode-$target.tar.gz"); done
for target in darwin-arm64 darwin-x64 darwin-x64-baseline; do cli+=("$macos/opencode-$target.zip"); done
for target in windows-arm64 windows-x64 windows-x64-baseline; do cli+=("$windows/opencode-$target.zip"); done
files=$(upload_files "${cli[@]}")
publish_update cli npm '{"package": "@opencode/cli"}'
publish_update cli opencode "$(jq -n --argjson files "$files" '{files: $files}')"
if [ "$OPENCODE_CHANNEL" != latest ]; then
node=()
for target in linux-arm64 linux-x64; do node+=("$archives/opencode2-node-$target.tar.gz"); done
for target in darwin-arm64 windows-arm64 windows-x64; do node+=("$archives/opencode2-node-$target.zip"); done
files=$(upload_files "${node[@]}")
publish_update cli-node npm '{"package": "@opencode/cli-node"}'
publish_update cli-node opencode "$(jq -n --argjson files "$files" '{files: $files}')"
fi

30
.github/release/publish-desktop.sh vendored Executable file
View file

@ -0,0 +1,30 @@
#!/usr/bin/env bash
# publish-desktop.sh <sign-macos dir> <sign-desktop-windows-installer dir> <build-desktop-linux-x64 dir>
# <build-desktop-linux-arm64 dir>: uploads the desktop builds to opencode.ai/files and registers the desktop update
# artifact. The electron-updater feeds (latest*.yml) are computed here from the final signed files.
. "$(dirname "$0")/lib.sh"
macos=$1 windows=$2 linux_x64=$3 linux_arm64=$4
win=("$windows/opencode-desktop-win-arm64.exe" "$windows/opencode-desktop-win-x64.exe")
mac=("$macos/opencode-desktop-mac-arm64.zip" "$macos/opencode-desktop-mac-arm64.dmg" "$macos/opencode-desktop-mac-x64.zip" "$macos/opencode-desktop-mac-x64.dmg")
linux=("$linux_x64/opencode-desktop-linux-x86_64.AppImage" "$linux_x64/opencode-desktop-linux-amd64.deb" "$linux_x64/opencode-desktop-linux-x86_64.rpm")
linux_arm=("$linux_arm64/opencode-desktop-linux-arm64.AppImage" "$linux_arm64/opencode-desktop-linux-arm64.deb" "$linux_arm64/opencode-desktop-linux-aarch64.rpm")
# Beta skips the .app.tar.gz, which only the retired Tauri updater feed read.
bundles=()
if [ "$OPENCODE_CHANNEL" != beta ]; then
bundles=("$macos/opencode-desktop-mac-arm64.app.tar.gz" "$macos/opencode-desktop-mac-x64.app.tar.gz")
fi
feed() {
for file in "$@"; do
jq -n --arg url "https://opencode.ai/files/bin/$OPENCODE_VERSION/$(basename "$file")" \
--arg sha512 "$(openssl dgst -sha512 -binary "$file" | base64 | tr -d '\n')" --argjson size "$(size "$file")" \
'{url: $url, sha512: $sha512, size: $size}'
done | jq -s --arg date "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" '{files: ., releaseDate: $date}'
}
files=$(upload_files "${win[@]}" "${mac[@]}" "${linux[@]}" "${linux_arm[@]}" "${bundles[@]}")
manifests=$(jq -n --argjson win "$(feed "${win[@]}")" --argjson mac "$(feed "${mac[@]}")" \
--argjson linux "$(feed "${linux[@]}")" --argjson linux_arm64 "$(feed "${linux_arm[@]}")" \
'{"desktop.yml": $win, "desktop-mac.yml": $mac, "desktop-linux.yml": $linux, "desktop-linux-arm64.yml": $linux_arm64}')
publish_update desktop opencode "$(jq -n --argjson files "$files" --argjson manifests "$manifests" '{files: $files, manifests: $manifests}')"

10
.github/release/publish-docker.sh vendored Executable file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env bash
# publish-docker.sh <build-docker dir>: pushes the multi-arch OCI image to ghcr.io/anomalyco/opencode:<version>
# without building anything (GH_TOKEN with packages: write).
. "$(dirname "$0")/lib.sh"
image="$1/opencode-image.tar"
skopeo inspect --raw "oci-archive:$image" | jq .
if dry_run; then exit 0; fi
printf '%s' "$GH_TOKEN" | skopeo login ghcr.io --username "$GITHUB_ACTOR" --password-stdin
skopeo copy --all "oci-archive:$image" "docker://ghcr.io/anomalyco/opencode:$OPENCODE_VERSION"

19
.github/release/publish-github-release.sh vendored Executable file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
# publish-github-release.sh <dir>...: attaches the CLI archives and desktop builds in the given artifact dirs, plus
# a SHA256SUMS, to the v<version> GitHub release with OPENCODE_RELEASE_NOTES. Immutable releases lock assets once
# published, so they go to a draft first.
. "$(dirname "$0")/lib.sh"
assets=$(mktemp -d)
for dir in "$@"; do
find "$dir" -maxdepth 1 -type f \( -name 'opencode-*.zip' -o -name 'opencode-*.tar.gz' -o -name 'opencode-desktop-*' \) \
! -name '*.tgz' ! -name '*.app.tar' -exec cp {} "$assets/" \;
done
(cd "$assets" && sha256 -- * > SHA256SUMS && cat SHA256SUMS)
printf '%s\n' "${OPENCODE_RELEASE_NOTES:-}" > "$assets.md"
if dry_run; then exit 0; fi
tag="v$OPENCODE_VERSION"
gh release view "$tag" > /dev/null 2>&1 || gh release create "$tag" --draft --verify-tag --title "$tag" --notes-file "$assets.md"
gh release upload "$tag" "$assets"/* --clobber
gh release edit "$tag" --draft=false

8
.github/release/publish-homebrew.sh vendored Executable file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env bash
# publish-homebrew.sh <sign-macos dir> <build-archives dir>: updates opencode-v2 in anomalyco/homebrew-tap
# (HOMEBREW_TOKEN) and registers the homebrew update artifact.
. "$(dirname "$0")/lib.sh"
push_git "https://x-access-token:${HOMEBREW_TOKEN:-}@github.com/anomalyco/homebrew-tap.git" \
"chore: update opencode-v2 to $OPENCODE_VERSION" bash "$release_dir/render-homebrew.sh" "$1" "$2"
publish_update cli homebrew '{"package": "anomalyco/tap/opencode-v2"}'

64
.github/release/publish-npm.sh vendored Executable file
View file

@ -0,0 +1,64 @@
#!/usr/bin/env bash
# publish-npm.sh <build-npm dir> <signed dir>...: publishes every release tarball to npm with OPENCODE_NPM_TAG.
# Names, the version and the package set come from this script, never from the tarballs: each tarball's
# package.json is read as data and must match. macOS and Windows CLI packages must come from a signed dir.
. "$(dirname "$0")/lib.sh"
npm_dir=$1
shift
targets="linux-arm64 linux-x64 linux-x64-baseline linux-arm64-musl linux-x64-musl linux-x64-baseline-musl darwin-arm64 darwin-x64 darwin-x64-baseline windows-arm64 windows-x64 windows-x64-baseline"
expected="@opencode/cli"
for target in $targets; do expected="$expected @opencode/cli-$target"; done
for lib in schema codemode theme ai util protocol client plugin plugin-browser core simulation server sdk ui; do expected="$expected @opencode/$lib"; done
if [ "$OPENCODE_CHANNEL" != latest ]; then
expected="$expected @opencode/cli-node"
for target in linux-arm64 linux-x64 darwin-arm64 windows-arm64 windows-x64; do expected="$expected @opencode/cli-node-$target"; done
fi
if ! dry_run; then
for file in "$npm_dir"/*.tgz; do
gh attestation verify "$file" --repo anomalyco/opencode --signer-workflow anomalyco/opencode/.github/workflows/release.yml > /dev/null
done
fi
shopt -s nullglob
files=()
for dir in "$@"; do files+=("$dir"/*.tgz); done
files+=("$npm_dir"/*.tgz)
list=$(mktemp)
for file in "${files[@]}"; do
IFS=$'\t' read -r name version config install < <(tar -xzOf "$file" package/package.json |
jq -r '[.name, .version, ((.publishConfig // {}) | keys - ["access"] | length > 0),
((.scripts // {}) | (has("preinstall") or has("install") or has("postinstall")))] | @tsv')
# shellcheck disable=SC2086 # $expected is a word list
printf '%s\n' $expected | grep -qxF -- "$name" || die "Unexpected package $name in $file"
# The signed copy of a macOS or Windows CLI package replaces the unsigned one from the build.
if cut -f1 "$list" | grep -qxF -- "$name"; then continue; fi
case "$name:$file" in
@opencode/cli-darwin-*:"$npm_dir"/* | @opencode/cli-windows-*:"$npm_dir"/*) die "$name is not signed" ;;
esac
[ "$version" = "$OPENCODE_VERSION" ] || die "$name has version $version, expected $OPENCODE_VERSION"
[ "$config" = false ] || die "$name sets publishConfig beyond access"
[ "$install" = false ] || [ "$name" = @opencode/cli ] || [ "$name" = @opencode/cli-node ] || die "$name has an install script"
printf '%s\t%s\n' "$name" "$file" >> "$list"
done
for name in $expected; do cut -f1 "$list" | grep -qxF -- "$name" || die "Missing package $name"; done
# The CLI wrappers resolve their platform packages, so they publish last.
order=$(mktemp)
{ grep -vP '^@opencode/cli(-node)?\t' "$list" || true; grep -P '^@opencode/cli(-node)?\t' "$list"; } > "$order"
cat "$order"
# A clean directory and config, so nothing from an artifact can redirect the registry.
printf 'registry=https://registry.npmjs.org/\n' > "$RUNNER_TEMP/npmrc"
export NPM_CONFIG_USERCONFIG="$RUNNER_TEMP/npmrc"
cd "$(mktemp -d)"
flags=(--tag "$OPENCODE_NPM_TAG" --access public --ignore-scripts)
if dry_run; then flags+=(--dry-run); else flags+=(--provenance); fi
while IFS=$'\t' read -r name file; do
if ! dry_run && npm view "$name@$OPENCODE_VERSION" version > /dev/null 2>&1; then
echo "already published $name@$OPENCODE_VERSION"
continue
fi
npm publish "$file" "${flags[@]}"
done < "$order"

11
.github/release/publish-version-pr.sh vendored Executable file
View file

@ -0,0 +1,11 @@
#!/usr/bin/env bash
# publish-version-pr.sh <sha>: opens the pull request that brings the release commit (versions and changelog) back to dev.
# Pushing to dev is blocked by rulesets, so this never merges.
. "$(dirname "$0")/lib.sh"
branch="release-v$OPENCODE_VERSION"
gh api "repos/$GH_REPO/git/refs" -f "ref=refs/heads/$branch" -f "sha=$1" > /dev/null ||
gh api "repos/$GH_REPO/git/refs/heads/$branch" > /dev/null
body="Brings the versions and changelog of the published \`v$OPENCODE_VERSION\` release back to \`dev\`. The \`v$OPENCODE_VERSION\` tag points at this commit."
gh pr create --base dev --head "$branch" --title "release: v$OPENCODE_VERSION" --body "$body" ||
echo "::warning::Could not open the release PR. Open it by hand: gh pr create --base dev --head $branch"

80
.github/release/render-aur.sh vendored Executable file
View file

@ -0,0 +1,80 @@
#!/usr/bin/env bash
# render-aur.sh <build-npm dir> <aur dir>: writes PKGBUILD, .SRCINFO and the opencode2 shim for opencode-beta.
# The package installs the published npm tarballs, so their hashes come from the build-npm artifact.
# LICENSE comes from the AUR repository itself.
. "$(dirname "$0")/lib.sh"
npm=$1 aur=$2
name=opencode-beta
pkgver="${OPENCODE_VERSION//-/.}"
if dry_run && [ ! -f "$aur/LICENSE" ]; then printf 'MIT License\n' > "$aur/LICENSE"; fi
test -s "$aur/LICENSE" || die "The AUR repository has no LICENSE"
printf '#!/bin/sh\nexec "$(dirname "$0")/opencode" "$@"\n' > "$aur/opencode2"
sum() { sha256 "$1" | cut -c1-64; }
x64=$(sum "$npm/opencode-cli-linux-x64-baseline-$OPENCODE_VERSION.tgz")
arm64=$(sum "$npm/opencode-cli-linux-arm64-$OPENCODE_VERSION.tgz")
x64_url="https://registry.npmjs.org/@opencode/cli-linux-x64-baseline/-/cli-linux-x64-baseline-$OPENCODE_VERSION.tgz"
arm64_url="https://registry.npmjs.org/@opencode/cli-linux-arm64/-/cli-linux-arm64-$OPENCODE_VERSION.tgz"
license=$(sum "$aur/LICENSE")
shim=$(sum "$aur/opencode2")
# Stripping a compiled Bun executable can damage its embedded application.
cat > "$aur/PKGBUILD" <<PKGBUILD
# Maintainer: Dax <mail@thdxr.com>
pkgname=$name
pkgver=$pkgver
pkgrel=1
pkgdesc='OpenCode beta - the AI coding agent for the terminal'
url='https://github.com/anomalyco/opencode'
arch=('x86_64' 'aarch64')
license=('MIT')
depends=('glibc' 'gcc-libs' 'ripgrep')
provides=('opencode' 'opencode2')
conflicts=('opencode' 'opencode2')
options=('!strip' '!debug')
source=('LICENSE' 'opencode2')
sha256sums=('$license' '$shim')
source_x86_64=('$name-$pkgver-x86_64.tgz::$x64_url')
sha256sums_x86_64=('$x64')
source_aarch64=('$name-$pkgver-aarch64.tgz::$arm64_url')
sha256sums_aarch64=('$arm64')
package() {
install -Dm755 "\$srcdir/package/bin/opencode" "\$pkgdir/usr/bin/opencode"
install -Dm755 "\$srcdir/opencode2" "\$pkgdir/usr/bin/opencode2"
install -Dm644 "\$srcdir/LICENSE" "\$pkgdir/usr/share/licenses/\$pkgname/LICENSE"
}
PKGBUILD
# What makepkg --printsrcinfo prints for the PKGBUILD above.
t=$'\t'
cat > "$aur/.SRCINFO" <<SRCINFO
pkgbase = $name
${t}pkgdesc = OpenCode beta - the AI coding agent for the terminal
${t}pkgver = $pkgver
${t}pkgrel = 1
${t}url = https://github.com/anomalyco/opencode
${t}arch = x86_64
${t}arch = aarch64
${t}license = MIT
${t}depends = glibc
${t}depends = gcc-libs
${t}depends = ripgrep
${t}provides = opencode
${t}provides = opencode2
${t}conflicts = opencode
${t}conflicts = opencode2
${t}options = !strip
${t}options = !debug
${t}source = LICENSE
${t}source = opencode2
${t}sha256sums = $license
${t}sha256sums = $shim
${t}source_x86_64 = $name-$pkgver-x86_64.tgz::$x64_url
${t}sha256sums_x86_64 = $x64
${t}source_aarch64 = $name-$pkgver-aarch64.tgz::$arm64_url
${t}sha256sums_aarch64 = $arm64
pkgname = $name
SRCINFO
cat "$aur/PKGBUILD" "$aur/.SRCINFO"

47
.github/release/render-homebrew.sh vendored Executable file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env bash
# render-homebrew.sh <sign-macos dir> <build-archives dir> <tap dir>: writes Formula opencode-v2.rb with the
# hashes of the signed macOS and the Linux archives.
. "$(dirname "$0")/lib.sh"
macos=$1 archives=$2 tap=$3
sum() { sha256 "$1" | cut -c1-64; }
base="https://opencode.ai/files/bin/$OPENCODE_VERSION"
cat > "$tap/opencode-v2.rb" <<FORMULA
# typed: false
# frozen_string_literal: true
class OpencodeV2 < Formula
desc "OpenCode V2 - the AI coding agent for the terminal"
homepage "https://github.com/anomalyco/opencode"
version "$OPENCODE_VERSION"
license "MIT"
depends_on "ripgrep"
conflicts_with "opencode", because: "both install an opencode binary"
on_macos do
if Hardware::CPU.arm?
url "$base/opencode-darwin-arm64.zip"
sha256 "$(sum "$macos/opencode-darwin-arm64.zip")"
else
url "$base/opencode-darwin-x64-baseline.zip"
sha256 "$(sum "$macos/opencode-darwin-x64-baseline.zip")"
end
end
on_linux do
if Hardware::CPU.arm?
url "$base/opencode-linux-arm64.tar.gz"
sha256 "$(sum "$archives/opencode-linux-arm64.tar.gz")"
else
url "$base/opencode-linux-x64-baseline.tar.gz"
sha256 "$(sum "$archives/opencode-linux-x64-baseline.tar.gz")"
end
end
def install
bin.install "opencode"
end
end
FORMULA
cat "$tap/opencode-v2.rb"

45
.github/release/render-winget.sh vendored Executable file
View file

@ -0,0 +1,45 @@
#!/usr/bin/env bash
# render-winget.sh <sign-windows dir> <sign-desktop-windows-installer dir> <out dir>: writes the WinGet manifests for
# Anomaly.OpenCode and Anomaly.OpenCode.Desktop. Submission to microsoft/winget-pkgs is paused until the packages
# are accepted, so the workflow only uploads them.
. "$(dirname "$0")/lib.sh"
cli=$1 desktop=$2 out=$3
sum() { sha256 "$1" | cut -c1-64 | tr a-f A-F; }
base="https://opencode.ai/files/bin/$OPENCODE_VERSION"
date=$(date -u +%F)
header() {
printf '# yaml-language-server: $schema=https://aka.ms/winget-manifest.%s.1.12.0.schema.json\n\nPackageIdentifier: %s\nPackageVersion: %s\n' \
"$2" "$1" "$OPENCODE_VERSION"
}
footer() { printf 'ManifestType: %s\nManifestVersion: 1.12.0\n' "$1"; }
manifests() {
local id=$1 name=$2 description=$3 moniker=$4
shift 4
mkdir -p "$out/$id"
{ header "$id" version; echo "DefaultLocale: en-US"; footer version; } > "$out/$id/$id.yaml"
{ header "$id" installer; printf '%s\n' "$@" "ReleaseDate: $date"; footer installer; } > "$out/$id/$id.installer.yaml"
{
header "$id" defaultLocale
printf '%s\n' "PackageLocale: en-US" "Publisher: OpenCode" "PublisherUrl: https://anoma.ly/" \
"PublisherSupportUrl: https://github.com/anomalyco/opencode/issues" "PrivacyUrl: https://opencode.ai/legal/privacy-policy" \
"PackageName: $name" "PackageUrl: https://opencode.ai/" "License: MIT" "LicenseUrl: https://github.com/anomalyco/opencode/blob/HEAD/LICENSE" \
"ShortDescription: $description" "Moniker: $moniker" "Tags:" "- ai" "- coding-agent" "- developer-tools" \
"Documentations:" "- DocumentLabel: Docs" " DocumentUrl: https://opencode.ai/v2/docs"
footer defaultLocale
} > "$out/$id/$id.locale.en-US.yaml"
}
manifests Anomaly.OpenCode "OpenCode CLI" "The open source AI coding agent for the terminal." opencode \
"InstallerType: zip" "NestedInstallerType: portable" "NestedInstallerFiles:" \
"- RelativeFilePath: opencode.exe" " PortableCommandAlias: opencode" "Commands:" "- opencode" "Installers:" \
"- Architecture: x64" " InstallerUrl: $base/opencode-windows-x64-baseline.zip" " InstallerSha256: $(sum "$cli/opencode-windows-x64-baseline.zip")" \
"- Architecture: arm64" " InstallerUrl: $base/opencode-windows-arm64.zip" " InstallerSha256: $(sum "$cli/opencode-windows-arm64.zip")"
# The display name and uninstall key match what the NSIS installer registers for ai.opencode.desktop.
manifests Anomaly.OpenCode.Desktop "OpenCode" "The open source AI coding agent as a desktop app." opencode-desktop \
"InstallerType: nullsoft" "Scope: user" "UpgradeBehavior: install" "ProductCode: d074f30d-5f88-5885-b075-be1348cc7676" \
"Protocols:" "- opencode" "Installers:" \
"- Architecture: x64" " InstallerUrl: $base/opencode-desktop-win-x64.exe" " InstallerSha256: $(sum "$desktop/opencode-desktop-win-x64.exe")" \
"- Architecture: arm64" " InstallerUrl: $base/opencode-desktop-win-arm64.exe" " InstallerSha256: $(sum "$desktop/opencode-desktop-win-arm64.exe")"
tail -n +1 "$out"/*/*

13
.github/release/repack-windows.sh vendored Executable file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env bash
# repack-windows.sh <work dir> <out dir>: checks every signature in <work dir>, then writes the signed CLI back
# into npm tarballs and opencode-<target>.zip archives in <out dir>.
. "$(dirname "$0")/lib.sh"
work=$(posix "$1") out=$(posix "$2")
bash "$release_dir/verify-signatures-windows.sh" "$work"
mkdir -p "$out"
if [ ! -d "$work/cli" ]; then exit 0; fi
for target in windows-arm64 windows-x64 windows-x64-baseline; do
tar -czf "$out/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work/cli/$target" package
powershell -NoProfile -Command "Compress-Archive -Path '$(cygpath -w "$work/cli/$target/package/bin/opencode.exe")' -DestinationPath '$(cygpath -w "$out/opencode-$target.zip")'"
done

28
.github/release/sign-cli-macos.sh vendored Executable file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env bash
# sign-cli-macos.sh <build-npm dir> <out dir>: signs the three macOS CLI binaries inside their npm tarballs with
# the Developer ID in build.keychain, then writes the re-packed tarballs and the opencode-<target>.zip archives.
# Dry runs sign ad-hoc.
. "$(dirname "$0")/lib.sh"
in=$1 out=$2
mkdir -p "$out"
identity=- timestamp=--timestamp=none
if ! dry_run; then
identity=$(security find-identity -v -p codesigning build.keychain | sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -n 1)
[ -n "$identity" ] || die "Developer ID Application identity not found"
timestamp=--timestamp
fi
export COPYFILE_DISABLE=1
for target in darwin-arm64 darwin-x64 darwin-x64-baseline; do
work=$(mktemp -d)
tar -xzf "$in/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work"
bin="$work/package/bin/opencode"
file -b "$bin" | grep -q '^Mach-O' || die "$target is not a Mach-O binary"
chmod 755 "$bin"
codesign --force "$timestamp" --options runtime --entitlements "$release_dir/entitlements/cli.plist" --sign "$identity" "$bin"
codesign --verify --strict --verbose=2 "$bin"
tar --no-mac-metadata -czf "$out/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work" package
touch -t 198001010000 "$bin"
(cd "$work/package/bin" && zip -X -q "$out/opencode-$target.zip" opencode)
done

87
.github/release/sign-desktop-macos.sh vendored Executable file
View file

@ -0,0 +1,87 @@
#!/usr/bin/env bash
# sign-desktop-macos.sh <out dir> <app tarball>...: signs each unsigned .app inside-out with hardened runtime,
# notarizes them in one submission, staples them, and only then builds opencode-desktop-mac-<arch>.{zip,dmg,app.tar.gz}
# from the stapled apps. Dry runs sign ad-hoc and skip notarization. Beta trades larger files for faster packaging
# (zip and dmg at zlib level 1) and skips the .app.tar.gz, which only the retired Tauri updater feed read.
# Notarization reads APPLE_API_KEY_CONTENT, APPLE_API_KEY_ID and APPLE_API_ISSUER.
. "$(dirname "$0")/lib.sh"
out=$1
shift
mkdir -p "$out"
apps=$(mktemp -d)
identity=- timestamp=--timestamp=none
zip_level=() dmg_level=()
if [ "$OPENCODE_CHANNEL" = beta ]; then zip_level=(--zlibCompressionLevel 1) dmg_level=(-imagekey zlib-level=1); fi
if ! dry_run; then
identity=$(security find-identity -v -p codesigning build.keychain | sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -n 1)
[ -n "$identity" ] || die "Developer ID Application identity not found"
timestamp=--timestamp
fi
sign() {
codesign --force "$timestamp" --options runtime --entitlements "$2" --sign "$identity" "$1"
}
bundle() {
find "$apps/$1" -mindepth 1 -maxdepth 1 -name '*.app' -type d
}
for tarball in "$@"; do
arch=$(basename "$tarball" .app.tar)
arch=${arch#opencode-desktop-mac-}
[ "$arch" = arm64 ] || [ "$arch" = x64 ] || die "Unexpected app tarball: $tarball"
mkdir -p "$apps/$arch"
tar -xf "$tarball" -C "$apps/$arch"
if [ "$(find "$apps/$arch" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ')" != 1 ] || [ -z "$(bundle "$arch")" ]; then
die "Expected exactly one .app bundle in $tarball"
fi
app=$(bundle "$arch")
# Every nested Mach-O file and bundle, deepest first, then the app itself.
list=$(mktemp)
{
find "$app/Contents" -type f -print0 | while IFS= read -r -d '' file; do
case "$(file -b --mime-type "$file")" in application/x-mach-binary*) printf '%s\n' "$file" ;; esac
done
find "$app/Contents" -type d \( -name '*.app' -o -name '*.framework' \) -print
} | awk -F/ '{ print NF "\t" $0 }' | sort -t "$(printf '\t')" -k1,1nr | cut -f2- > "$list"
echo "Signing $(wc -l < "$list" | tr -d ' ') items in $app"
while IFS= read -r item; do
if [ "$item" = "$app/Contents/Resources/opencode-cli" ]; then
# The bundled Bun CLI loads bun-pty's native library; Electron and its helpers do not need this exception.
sign "$item" "$release_dir/entitlements/desktop-cli.plist"
else
sign "$item" "$release_dir/entitlements/desktop.plist"
fi
done < "$list"
sign "$app" "$release_dir/entitlements/desktop.plist"
codesign --verify --deep --strict --verbose=2 "$app"
done
if ! dry_run; then
key=$(mktemp)
printf '%s\n' "$APPLE_API_KEY_CONTENT" > "$key"
ditto -c -k --sequesterRsrc "$apps" "$apps.zip"
xcrun notarytool submit "$apps.zip" --key "$key" --key-id "$APPLE_API_KEY_ID" --issuer "$APPLE_API_ISSUER" \
--wait --timeout 60m --output-format json > "$apps.json"
rm -f "$key"
cat "$apps.json"
[ "$(jq -r .status "$apps.json")" = Accepted ] || die "Notarization was not accepted"
fi
for dir in "$apps"/*; do
arch=$(basename "$dir")
app=$(bundle "$arch")
name=$(basename "$app")
if ! dry_run; then
xcrun stapler staple "$app"
xcrun stapler validate "$app"
spctl --assess --type execute --verbose=2 "$app"
fi
ditto -c -k ${zip_level[@]+"${zip_level[@]}"} --sequesterRsrc --keepParent "$app" "$out/opencode-desktop-mac-$arch.zip"
staging=$(mktemp -d)
ditto "$app" "$staging/$name"
ln -s /Applications "$staging/Applications"
hdiutil create -volname "${name%.app}" -srcfolder "$staging" -fs HFS+ -format UDZO ${dmg_level[@]+"${dmg_level[@]}"} -ov "$out/opencode-desktop-mac-$arch.dmg"
if [ "$OPENCODE_CHANNEL" = beta ]; then continue; fi
COPYFILE_DISABLE=1 tar --no-mac-metadata -czf "$out/opencode-desktop-mac-$arch.app.tar.gz" -C "$dir" "$name"
done

40
.github/release/tag-release.sh vendored Executable file
View file

@ -0,0 +1,40 @@
#!/usr/bin/env bash
# tag-release.sh: in a checkout of the dispatched dev commit, commits the release versions and changelog
# (OPENCODE_RELEASE_NOTES) and pushes only the v<version> tag at it. Writes sha=<commit> to $GITHUB_OUTPUT.
# Runs git only, with hooks disabled; no repository code.
. "$(dirname "$0")/lib.sh"
tag="v$OPENCODE_VERSION"
git ls-files -z -- '*package.json' bun.lock | xargs -0 sed -i -E "s/\"version\": \"[^\"]+\"/\"version\": \"$OPENCODE_VERSION\"/g"
if [ -n "${OPENCODE_RELEASE_NOTES:-}" ] && ! grep -qF -x "## $tag" CHANGELOG.md && ! grep -qF "## $tag " CHANGELOG.md; then
notes=$(mktemp)
printf '%s\n' "$OPENCODE_RELEASE_NOTES" > "$notes"
awk -v entry="## $tag — $(date -u +%F)" -v notes="$notes" '
function emit() { print entry; print ""; while ((getline line < notes) > 0) print line; print ""; done = 1 }
!done && /^## / { emit() }
{ print }
END { if (!done) { print ""; emit() } }
' CHANGELOG.md > "$notes.md"
mv "$notes.md" CHANGELOG.md
fi
if git diff --name-only | grep -vE '(^|/)package\.json$|^bun\.lock$|^CHANGELOG\.md$'; then
die "The release commit may only change versions and the changelog"
fi
git -c core.hooksPath=/dev/null \
-c user.name="github-actions[bot]" \
-c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
commit --no-verify -q -am "release: $tag"
# A rerun reuses the tag when it holds the same tree.
existing=$(git ls-remote origin "refs/tags/$tag" | cut -f1)
if [ -n "$existing" ]; then
git fetch -q --depth=1 origin "refs/tags/$tag"
[ "$(git rev-parse "$existing^{tree}")" = "$(git rev-parse "HEAD^{tree}")" ] || die "Tag $tag already exists with different contents"
echo "sha=$existing" >> "$GITHUB_OUTPUT"
exit 0
fi
git push -q origin "HEAD:refs/tags/$tag"
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"

17
.github/release/unpack-windows.sh vendored Executable file
View file

@ -0,0 +1,17 @@
#!/usr/bin/env bash
# unpack-windows.sh <download dir> <work dir>: lays out what the signing action signs in <work dir>:
# cli/<target>/package from the Windows CLI npm tarballs, and desktop-<target>/ from the unpacked desktop apps.
. "$(dirname "$0")/lib.sh"
in=$(posix "$1") work=$(posix "$2")
mkdir -p "$work"
if [ -d "$in/build-npm" ]; then
for target in windows-arm64 windows-x64 windows-x64-baseline; do
mkdir -p "$work/cli/$target"
tar -xzf "$in/build-npm/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work/cli/$target"
test -s "$work/cli/$target/package/bin/opencode.exe" || die "Missing opencode.exe for $target"
done
fi
for target in windows-arm64 windows-x64; do
if [ -d "$in/build-desktop-$target" ]; then mkdir -p "$work/desktop-$target" && cp -R "$in/build-desktop-$target/app" "$work/desktop-$target/app"; fi
done

26
.github/release/upload/action.yml vendored Normal file
View file

@ -0,0 +1,26 @@
name: Upload a release artifact
description: Writes SHA256SUMS for a directory, uploads it, and outputs the manifest digest.
inputs:
name:
description: Artifact name, <stage>-<target>
required: true
path:
description: Directory to upload
required: true
outputs:
digest:
description: SHA-256 of the artifact's SHA256SUMS
value: ${{ steps.checksum.outputs.digest }}
runs:
using: composite
steps:
- id: checksum
shell: bash
run: echo "digest=$(bash "${GITHUB_ACTION_PATH//\\//}/../write-checksums.sh" "$UPLOAD_PATH")" >> "$GITHUB_OUTPUT"
env:
UPLOAD_PATH: ${{ inputs.path }}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
if-no-files-found: error

23
.github/release/verify-artifacts.sh vendored Executable file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env bash
# verify-artifacts.sh <dir>: checks every artifact downloaded into <dir>/<name> against its SHA256SUMS and that it
# holds exactly the listed files. Artifacts made by sign jobs (sign-*) must also match the manifest digest their
# job reported (OPENCODE_DIGESTS="name=digest ..."), so an artifact replaced after that job finished is rejected.
. "$(dirname "$0")/lib.sh"
root=$(posix "$1")
for dir in "$root"/*/; do
name=$(basename "$dir")
digest=""
for pair in ${OPENCODE_DIGESTS:-}; do
if [ "${pair%%=*}" = "$name" ]; then digest=${pair#*=}; fi
done
case "$name" in sign-*) [[ "$digest" =~ ^[0-9a-f]{64}$ ]] || die "Missing digest for $name" ;; esac
(
cd "$dir"
if [ -n "$digest" ] && [ "$(sha256 SHA256SUMS | cut -c1-64)" != "$digest" ]; then die "SHA256SUMS digest mismatch in $name"; fi
sha256 -c SHA256SUMS > /dev/null || die "Checksum mismatch in $name"
diff <(find . -type f ! -name SHA256SUMS | sed 's|^\./||' | LC_ALL=C sort) <(cut -c67- SHA256SUMS | LC_ALL=C sort) ||
die "Unexpected files in $name"
)
echo "verified $name${digest:+ ($digest)}"
done

18
.github/release/verify-signatures-windows.sh vendored Executable file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env bash
# verify-signatures-windows.sh <dir>: fails unless every .exe and .node under <dir> has a valid Authenticode signature.
. "$(dirname "$0")/lib.sh"
if dry_run; then
echo "dry-run: not verifying signatures in $1"
exit 0
fi
powershell -NoProfile -Command "
\$ErrorActionPreference = 'Stop'
\$files = Get-ChildItem '$(cygpath -w "$(posix "$1")")' -Recurse -Include *.exe, *.node
if (-not \$files) { throw 'No signed files found' }
foreach (\$file in \$files) {
\$sig = Get-AuthenticodeSignature \$file.FullName
if (\$sig.Status -ne 'Valid') { throw \"Invalid signature for \$(\$file.FullName): \$(\$sig.Status)\" }
}
Write-Output \"verified \$(\$files.Count) signatures\"
"

11
.github/release/write-checksums.sh vendored Executable file
View file

@ -0,0 +1,11 @@
#!/usr/bin/env bash
# write-checksums.sh <dir>: writes <dir>/SHA256SUMS for every file under <dir> and prints its digest.
# Every artifact carries this manifest; trusted jobs pass the digest on through job outputs.
. "$(dirname "$0")/lib.sh"
cd "$(posix "$1")"
manifest=$(mktemp)
find . -type f ! -name SHA256SUMS | sed 's|^\./||' | LC_ALL=C sort | while IFS= read -r file; do sha256 "$file"; done > "$manifest"
mv "$manifest" SHA256SUMS
cat SHA256SUMS >&2
sha256 SHA256SUMS | cut -c1-64

View file

@ -12,6 +12,7 @@ jobs:
if: false
#if: github.actor != 'opencode-agent[bot]'
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: release
permissions:
contents: write
steps:

View file

@ -1,7 +1,7 @@
name: bot-nix-hashes
permissions:
contents: write
contents: read
on:
workflow_dispatch:
@ -91,6 +91,7 @@ jobs:
needs: compute-hash
if: github.event_name != 'pull_request'
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: release
steps:
- name: Checkout repository

View file

@ -119,10 +119,10 @@ jobs:
TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }}
TURBO_SCM_HEAD: ${{ github.sha }}
- name: Verify published codemode package
- name: Verify packed codemode package
if: runner.os == 'Linux'
working-directory: packages/codemode
run: bun run script/publish.ts --dry-run
run: bun run pack
- name: Verify packed workerd SDK
if: runner.os == 'Linux'

View file

@ -20,6 +20,7 @@ jobs:
deploy:
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev'
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: release
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0

View file

@ -18,7 +18,7 @@ jobs:
deploy:
if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'production')
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: ${{ github.ref_name == 'production' && 'production' || '' }}
environment: ${{ github.ref_name == 'production' && 'production' || 'release' }}
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0

View file

@ -18,7 +18,7 @@ jobs:
deploy:
if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'production')
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: ${{ github.ref_name == 'production' && 'production' || '' }}
environment: ${{ github.ref_name == 'production' && 'production' || 'release' }}
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0

View file

@ -1,14 +0,0 @@
name: notify-discord
on:
release:
types: [released] # fires when a draft release is published
jobs:
notify:
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Send nicely-formatted embed to Discord
uses: SethCohen/github-releases-to-discord@24d166886aee4646d448c8a389ff9e1ebcab3682 # v1.20.0
with:
webhook_url: ${{ secrets.DISCORD_WEBHOOK }}

View file

@ -1,38 +0,0 @@
name: publish-vscode
on:
workflow_dispatch:
push:
tags:
- "vscode-v*.*.*"
concurrency: ${{ github.workflow }}-${{ github.ref }}
permissions:
contents: write
jobs:
publish:
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: release
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
with:
fetch-depth: 0
- uses: ./.github/actions/setup-bun
- run: git fetch --force --tags
- run: bun install -g @vscode/vsce
- name: Install extension dependencies
run: bun install
working-directory: ./sdks/vscode
- name: Publish
run: |
./script/publish
working-directory: ./sdks/vscode
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OPENVSX_TOKEN: ${{ secrets.OPENVSX_TOKEN }}

View file

@ -1,847 +0,0 @@
name: publish
run-name: "${{ format('release {0}', inputs.bump) }}"
on:
push:
branches:
- dev
- beta
workflow_dispatch:
inputs:
bump:
description: "Bump major, minor, or patch"
required: false
type: choice
options:
- major
- minor
- patch
version:
description: "Override version (optional)"
required: false
type: string
release_notes:
description: "Reviewed V2 release notes for CHANGELOG.md and the Discord announcement (optional)"
required: false
type: string
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ (github.ref_name == 'dev' && (inputs.version || inputs.bump) && 'release') || inputs.version || inputs.bump }}
# Beta ships only the newest commit to the team. A cancelled beta run can leave unreferenced files in R2, but only
# its publish job records a release, in one request.
cancel-in-progress: ${{ github.ref_name == 'beta' }}
permissions:
id-token: write
contents: write
packages: write
# Beta desktop jobs poll this run's artifacts while the CLI builds.
actions: read
# Beta desktop builds read who made each change and what it does for "What's new in beta".
pull-requests: read
env:
OPENCODE_CHANNEL: ${{ (github.ref_name == 'dev' && !inputs.bump && !inputs.version && 'dev') || '' }}
jobs:
version:
runs-on: blacksmith-4vcpu-ubuntu-2404
if: github.repository == 'anomalyco/opencode'
# Versioned releases wait for approval in the release environment, which only allows dev.
environment: ${{ (inputs.bump || inputs.version) && 'release' || '' }}
env:
BETA: ${{ github.ref_name == 'beta' }}
steps:
# A beta version only depends on the run number, so beta computes it without a checkout or an install.
- name: Beta version
id: beta
if: env.BETA == 'true'
run: |
# Matches packages/script: 0.0.0-<channel>-<run number>[.<attempt>] for preview channels.
version="0.0.0-beta-${GITHUB_RUN_NUMBER}"
if [ "$GITHUB_RUN_ATTEMPT" != "1" ]; then version="${version}.${GITHUB_RUN_ATTEMPT}"; fi
{
echo "version=$version"
echo "release=true"
echo "tag=v$version"
} >> "$GITHUB_OUTPUT"
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
if: env.BETA != 'true'
with:
fetch-depth: 0
- uses: ./.github/actions/setup-bun
if: env.BETA != 'true'
- name: Setup git committer
id: committer
if: env.BETA != 'true'
uses: ./.github/actions/setup-git-committer
with:
opencode-app-id: ${{ vars.OPENCODE_APP_ID }}
opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }}
- name: Install OpenCode
if: inputs.bump || inputs.version
run: bun i -g opencode-ai
- id: version
if: env.BETA != 'true'
run: |
./script/version.ts
env:
GH_TOKEN: ${{ steps.committer.outputs.token }}
OPENCODE_BUMP: ${{ inputs.bump }}
OPENCODE_VERSION: ${{ inputs.version }}
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
outputs:
version: ${{ steps.version.outputs.version || steps.beta.outputs.version }}
release: ${{ steps.version.outputs.release || steps.beta.outputs.release }}
tag: ${{ steps.version.outputs.tag || steps.beta.outputs.tag }}
build-cli:
needs: version
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
# Beta builds only the CLIs its desktop app bundles, in build-cli-beta.
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta'
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
with:
fetch-tags: true
- uses: ./.github/actions/setup-bun
with:
bun-version: 1.4.4
- name: Setup git committer
id: committer
uses: ./.github/actions/setup-git-committer
with:
opencode-app-id: ${{ vars.OPENCODE_APP_ID }}
opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }}
- name: Build legacy CLI
if: github.ref_name != 'dev' && github.ref_name != 'beta'
run: ./packages/opencode/script/build.ts ${{ (github.ref_name == 'beta' && '--sourcemaps') || '' }}
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ steps.committer.outputs.token }}
- name: Build preview CLI
id: build
run: ./packages/cli/script/build.ts ${{ (github.ref_name == 'beta' && '--sourcemaps') || '' }}
env:
BUN_COMPILE_RELEASE: bun-v1.4.4
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ steps.committer.outputs.token }}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: github.ref_name != 'dev' && github.ref_name != 'beta'
with:
name: opencode-cli
path: |
packages/opencode/dist/opencode-darwin*
packages/opencode/dist/opencode-linux*
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: github.ref_name != 'dev' && github.ref_name != 'beta'
with:
name: opencode-cli-windows
path: packages/opencode/dist/opencode-windows*
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: opencode-preview-cli-unsigned
path: packages/cli/dist/cli-*
outputs:
version: ${{ needs.version.outputs.version }}
# Beta publishes only the desktop app, so it builds just the 6 CLIs the desktop bundles, each in its own job and
# artifact. Desktop jobs start alongside and wait for their CLI only when they need it.
build-cli-beta:
needs: version
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'beta'
strategy:
fail-fast: false
matrix:
# macOS first: notarization makes those desktop jobs the longest.
target:
- darwin-x64-baseline
- darwin-arm64
- linux-arm64
- windows-arm64
- windows-x64-baseline
- linux-x64-baseline
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: ./.github/actions/setup-bun
with:
bun-version: 1.4.4
- name: Build CLI
run: ./packages/cli/script/build.ts --target=opencode-${{ matrix.target }}
env:
BUN_COMPILE_RELEASE: bun-v1.4.4
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: opencode-cli-unsigned-cli-${{ matrix.target }}
path: packages/cli/dist/cli-${{ matrix.target }}
# Deflate level 1 compresses a CLI binary twice as fast as the default for 7% more bytes.
compression-level: 1
if-no-files-found: error
sign-cli-macos:
needs: build-cli
runs-on: macos-26
# Beta publishes only the desktop app, which signs the CLI it bundles.
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta'
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0
with:
keychain: build
p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: opencode-preview-cli-unsigned
path: packages/cli/dist
- name: Sign macOS CLI binaries
run: |
identity=$(security find-identity -v -p codesigning build.keychain | sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -n 1)
if [ -z "$identity" ]; then
echo "Developer ID Application identity not found"
exit 1
fi
found=0
for file in packages/cli/dist/cli-darwin-*/bin/opencode; do
if [ ! -f "$file" ]; then
continue
fi
found=1
codesign \
--force \
--timestamp \
--options runtime \
--entitlements packages/cli/script/entitlements.plist \
--sign "$identity" \
"$file"
codesign --verify --deep --strict --verbose=4 "$file"
codesign --display --requirements - "$file"
done
if [ "$found" -eq 0 ]; then
echo "No macOS CLI binaries found"
exit 1
fi
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: opencode-preview-cli-macos
path: packages/cli/dist/cli-*
if-no-files-found: error
build-node-app-archive:
needs: version
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: ./.github/actions/setup-bun
- name: Build app archive
run: bun packages/cli/script/build-node.ts --app-archive-only --app-archive=.cache/app-archive.bin --skip-install
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: opencode-node-app-archive
path: packages/cli/.cache/app-archive.bin
if-no-files-found: error
build-node-cli:
needs:
- version
- build-node-app-archive
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
strategy:
fail-fast: false
matrix:
settings:
- target: linux-arm64
host: blacksmith-4vcpu-ubuntu-2404-arm
- target: linux-x64
host: blacksmith-4vcpu-ubuntu-2404
- target: darwin-arm64
host: macos-26
- target: windows-arm64
host: blacksmith-4vcpu-windows-2025
bun_install_flags: --cpu=*
- target: windows-x64
host: blacksmith-4vcpu-windows-2025
runs-on: ${{ matrix.settings.host }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: ./.github/actions/setup-bun
with:
install-flags: ${{ matrix.settings.bun_install_flags }}
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: opencode-node-app-archive
path: packages/cli/.cache
- name: Build
run: bun packages/cli/script/build-node.ts --target=${{ matrix.settings.target }} --skip-install --outdir=dist/node --app-archive=.cache/app-archive.bin
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
- name: Verify service lifecycle
if: matrix.settings.target != 'windows-arm64'
working-directory: packages/cli
run: bun run script/service-smoke.ts --node
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: opencode-node-cli-${{ matrix.settings.target }}
path: packages/cli/dist/node/cli-node-*
if-no-files-found: error
sign-cli-windows:
needs:
- sign-cli-macos
runs-on: blacksmith-4vcpu-windows-2025
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev'
env:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: opencode-preview-cli-macos
path: packages/cli/dist
- name: Azure login
uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
with:
client-id: ${{ env.AZURE_CLIENT_ID }}
tenant-id: ${{ env.AZURE_TENANT_ID }}
subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }}
- uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0
with:
endpoint: ${{ env.AZURE_TRUSTED_SIGNING_ENDPOINT }}
signing-account-name: ${{ env.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
certificate-profile-name: ${{ env.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
files: |
${{ github.workspace }}\packages\cli\dist\cli-windows-arm64\bin\opencode.exe
${{ github.workspace }}\packages\cli\dist\cli-windows-x64\bin\opencode.exe
${{ github.workspace }}\packages\cli\dist\cli-windows-x64-baseline\bin\opencode.exe
exclude-environment-credential: true
exclude-workload-identity-credential: true
exclude-managed-identity-credential: true
exclude-shared-token-cache-credential: true
exclude-visual-studio-credential: true
exclude-visual-studio-code-credential: true
exclude-azure-cli-credential: false
exclude-azure-powershell-credential: true
exclude-azure-developer-cli-credential: true
exclude-interactive-browser-credential: true
- name: Verify Windows CLI signatures
shell: pwsh
run: |
$files = @(
"${{ github.workspace }}\packages\cli\dist\cli-windows-arm64\bin\opencode.exe",
"${{ github.workspace }}\packages\cli\dist\cli-windows-x64\bin\opencode.exe",
"${{ github.workspace }}\packages\cli\dist\cli-windows-x64-baseline\bin\opencode.exe"
)
foreach ($file in $files) {
$sig = Get-AuthenticodeSignature $file
if ($sig.Status -ne "Valid") {
throw "Invalid signature for ${file}: $($sig.Status)"
}
}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: opencode-preview-cli
path: packages/cli/dist/cli-*
if-no-files-found: error
build-electron:
# Desktop packaging re-signs the bundled CLI on macOS and Windows, so it starts from the unsigned build.
# Beta skips build-cli and waits for its own CLI from build-cli-beta just before Prepare.
needs:
- version
- build-cli
if: ${{ !cancelled() && !failure() && github.repository == 'anomalyco/opencode' && ((github.ref_name == 'dev' && needs.version.outputs.release != '') || github.ref_name == 'beta') }}
continue-on-error: false
env:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
strategy:
fail-fast: false
matrix:
# Beta packages macOS x64 on Apple Silicon and Windows arm64 on Blacksmith. electron-builder's afterPack rejects
# a bundle whose CLI or node-pty does not match the target CPU.
settings:
- host: ${{ (github.ref_name == 'beta' && 'macos-26') || 'macos-26-intel' }}
target: x86_64-apple-darwin
cli: darwin-x64-baseline
platform_flag: --mac --x64
bun_install_flags: ${{ (github.ref_name == 'beta' && '--os=darwin --cpu=*') || '--os=darwin --cpu=x64' }}
- host: macos-26
target: aarch64-apple-darwin
cli: darwin-arm64
platform_flag: --mac --arm64
bun_install_flags: --os=darwin --cpu=arm64
# Releases keep github-hosted Windows from the Tauri build, which needed an ARM64 MSVC toolchain; Electron
# packaging compiles nothing.
- host: ${{ (github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025') || 'windows-2025' }}
target: aarch64-pc-windows-msvc
cli: windows-arm64
platform_flag: --win --arm64
bun_install_flags: --cpu=*
- host: "blacksmith-4vcpu-windows-2025"
target: x86_64-pc-windows-msvc
cli: windows-x64-baseline
platform_flag: --win
- host: "blacksmith-4vcpu-ubuntu-2404"
target: x86_64-unknown-linux-gnu
cli: linux-x64-baseline
platform_flag: --linux
- host: "blacksmith-4vcpu-ubuntu-2404-arm"
target: aarch64-unknown-linux-gnu
cli: linux-arm64
platform_flag: --linux --arm64
runs-on: ${{ matrix.settings.host }}
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'beta'
with:
name: opencode-preview-cli-unsigned
path: packages/cli/dist
- uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0
if: runner.os == 'macOS'
with:
keychain: build
p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- name: Setup Apple API Key
if: runner.os == 'macOS'
run: echo "${{ secrets.APPLE_API_KEY_PATH }}" > $RUNNER_TEMP/apple-api-key.p8
- uses: ./.github/actions/setup-bun
with:
install-flags: ${{ matrix.settings.bun_install_flags }}
- name: Azure login
if: runner.os == 'Windows'
uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
with:
client-id: ${{ env.AZURE_CLIENT_ID }}
tenant-id: ${{ env.AZURE_TENANT_ID }}
subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }}
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "24"
- name: Cache apt packages
if: contains(matrix.settings.host, 'ubuntu')
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ~/apt-cache
key: ${{ runner.os }}-${{ matrix.settings.target }}-apt-electron-${{ hashFiles('.github/workflows/publish.yml') }}
restore-keys: |
${{ runner.os }}-${{ matrix.settings.target }}-apt-electron-
- name: Install dependencies (ubuntu only)
if: contains(matrix.settings.host, 'ubuntu')
run: |
mkdir -p ~/apt-cache && chmod -R a+rw ~/apt-cache
sudo apt-get update
sudo apt-get install -y --no-install-recommends -o dir::cache::archives="$HOME/apt-cache" rpm
sudo chmod -R a+rw ~/apt-cache
- name: Setup git committer
id: committer
uses: ./.github/actions/setup-git-committer
with:
opencode-app-id: ${{ vars.OPENCODE_APP_ID }}
opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }}
# Beta trades larger installers for faster packaging. These variables must stay unset elsewhere:
# electron-builder rejects an empty ELECTRON_BUILDER_COMPRESSION_LEVEL.
- name: Beta packaging settings
if: github.ref_name == 'beta'
shell: bash
run: |
# fpm sets XZ_OPT for the deb and rpm level, but xz still reads XZ_DEFAULTS, so it uses every CPU.
if [ "$RUNNER_OS" = "Linux" ]; then echo "XZ_DEFAULTS=-T0" >> "$GITHUB_ENV"; fi
# The macOS zip (7z deflate, default -mx=7) and DMG (UDZO zlib, default level 9) at level 1.
if [ "$RUNNER_OS" = "macOS" ]; then echo "ELECTRON_BUILDER_COMPRESSION_LEVEL=1" >> "$GITHUB_ENV"; fi
# The beta build embeds the subjects of its newest commits for "What's new in beta"
# (packages/desktop/scripts/beta-notes.ts), with their pull requests' authors and descriptions from GitHub.
# Commits without file contents are enough.
- name: Fetch beta history (beta)
if: github.ref_name == 'beta'
shell: bash
run: git fetch --no-tags --filter=blob:none --depth=300 origin "$GITHUB_SHA"
# Beta builds the app before its CLI exists. `bun run build` would run the prebuild hook, which copies the CLI;
# Prepare runs it once the CLI is here.
- name: Build (beta)
if: github.ref_name == 'beta'
run: bun run electron-vite build
working-directory: packages/desktop
env:
NODE_OPTIONS: --max-old-space-size=4096
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_CHANNEL: beta
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.WEB_SENTRY_PROJECT }}
SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }}
VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: beta
VITE_SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }}
OPENCODE_CLI_TARGET: ${{ matrix.settings.target }}
GITHUB_TOKEN: ${{ github.token }}
- name: Wait for the CLI (beta)
if: github.ref_name == 'beta'
run: bun ./script/wait-for-artifact.ts opencode-cli-unsigned-cli-${{ matrix.settings.cli }} "build-cli-beta (${{ matrix.settings.cli }})"
env:
GITHUB_TOKEN: ${{ github.token }}
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name == 'beta'
with:
name: opencode-cli-unsigned-cli-${{ matrix.settings.cli }}
path: packages/cli/dist/cli-${{ matrix.settings.cli }}
- name: Prepare
run: bun ./scripts/prepare.ts
working-directory: packages/desktop
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
OPENCODE_CLI_TARGET: ${{ matrix.settings.target }}
OPENCODE_CLI_DIST: ${{ github.workspace }}/packages/cli/dist
- name: Build
if: github.ref_name != 'beta'
run: bun run build
working-directory: packages/desktop
env:
NODE_OPTIONS: --max-old-space-size=4096
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.WEB_SENTRY_PROJECT }}
SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }}
VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ (github.ref_name == 'beta' && 'beta') || 'production' }}
VITE_SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }}
OPENCODE_CLI_TARGET: ${{ matrix.settings.target }}
OPENCODE_CLI_DIST: ${{ github.workspace }}/packages/cli/dist
- name: Package
if: needs.version.outputs.release
run: npx electron-builder ${{ matrix.settings.platform_flag }} --publish never --config electron-builder.config.ts
working-directory: packages/desktop
timeout-minutes: 60
env:
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
OPENCODE_CLI_TARGET: ${{ matrix.settings.target }}
GH_TOKEN: ${{ steps.committer.outputs.token }}
CSC_KEYCHAIN: build.keychain
APPLE_API_KEY: ${{ runner.temp }}/apple-api-key.p8
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
- name: Package (no publish)
if: ${{ !needs.version.outputs.release }}
run: npx electron-builder ${{ matrix.settings.platform_flag }} --publish never --config electron-builder.config.ts
working-directory: packages/desktop
timeout-minutes: 60
env:
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
OPENCODE_CLI_TARGET: ${{ matrix.settings.target }}
- name: Create macOS .app.tar.gz
# Only the retired Tauri updater feed read these archives.
if: runner.os == 'macOS' && needs.version.outputs.release && github.ref_name != 'beta'
working-directory: packages/desktop/dist
run: |
if [[ "${{ matrix.settings.target }}" == "x86_64-apple-darwin" ]]; then
APP_DIR="mac"
OUT_NAME="opencode-desktop-mac-x64.app.tar.gz"
elif [[ "${{ matrix.settings.target }}" == "aarch64-apple-darwin" ]]; then
APP_DIR="mac-arm64"
OUT_NAME="opencode-desktop-mac-arm64.app.tar.gz"
else
echo "Unknown macOS target: ${{ matrix.settings.target }}"
exit 1
fi
APP_PATH=$(find "$APP_DIR" -maxdepth 1 -name "*.app" -type d | head -1)
if [ -z "$APP_PATH" ]; then
echo "No .app bundle found in $APP_DIR"
exit 1
fi
tar -czf "$OUT_NAME" -C "$(dirname "$APP_PATH")" "$(basename "$APP_PATH")"
- name: Verify signed Windows Electron artifacts
if: runner.os == 'Windows'
shell: pwsh
run: |
$files = @()
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*.exe" | Select-Object -ExpandProperty FullName
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\*.exe" | Select-Object -ExpandProperty FullName
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\resources\opencode-cli.exe" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName
foreach ($file in $files | Select-Object -Unique) {
$sig = Get-AuthenticodeSignature $file
if ($sig.Status -ne "Valid") {
throw "Invalid signature for ${file}: $($sig.Status)"
}
}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: github.ref_name != 'beta'
with:
name: opencode-desktop-${{ matrix.settings.target }}
path: packages/desktop/dist/*
# Beta uploads its installers to R2 here instead of passing them through an artifact to publish, which only
# records the release from the returned file list.
- name: Upload to R2 (beta)
if: github.ref_name == 'beta'
run: bun ./scripts/upload.ts dist dist/uploaded-${{ matrix.settings.target }}.json
working-directory: packages/desktop
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: github.ref_name == 'beta'
with:
name: desktop-uploaded-${{ matrix.settings.target }}
path: packages/desktop/dist/uploaded-${{ matrix.settings.target }}.json
if-no-files-found: error
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: needs.version.outputs.release
with:
name: latest-yml-${{ matrix.settings.target }}
path: packages/desktop/dist/latest*.yml
publish:
needs:
- version
- build-cli
- build-cli-beta
- sign-cli-macos
- build-node-app-archive
- build-node-cli
- sign-cli-windows
- build-electron
if: always() && !failure() && !cancelled()
runs-on: blacksmith-4vcpu-ubuntu-2404
# Versioned and beta releases wait for approval in the release environment; dev previews do not.
environment: ${{ needs.version.outputs.release && 'release' || '' }}
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: ./.github/actions/setup-bun
# Beta only records the desktop release, so it skips the Docker, git and AUR setup.
- name: Login to GitHub Container Registry
if: github.ref_name != 'beta'
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up QEMU
if: github.ref_name != 'beta'
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
- name: Set up Docker Buildx
if: github.ref_name != 'beta'
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'dev' && github.ref_name != 'beta'
with:
name: opencode-cli
path: packages/opencode/dist
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'dev' && github.ref_name != 'beta'
with:
name: opencode-cli-windows
path: packages/opencode/dist
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'dev' && github.ref_name != 'beta'
with:
name: opencode-cli-signed-windows
path: packages/opencode/dist
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'beta'
with:
name: opencode-preview-cli
path: packages/cli/dist
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: needs.build-node-cli.result == 'success'
with:
pattern: opencode-node-cli-*
path: packages/cli/dist/node
merge-multiple: true
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: needs.version.outputs.release
with:
pattern: latest-yml-*
path: /tmp/latest-yml
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: needs.version.outputs.release && github.ref_name != 'beta'
with:
pattern: opencode-desktop-*
path: /tmp/desktop
merge-multiple: true
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name == 'beta'
with:
pattern: desktop-uploaded-*
path: /tmp/desktop-uploaded
merge-multiple: true
- name: Setup git committer
id: committer
if: github.ref_name != 'beta'
uses: ./.github/actions/setup-git-committer
with:
opencode-app-id: ${{ vars.OPENCODE_APP_ID }}
opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }}
- name: Cache apt packages (AUR)
if: github.ref_name != 'beta'
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: /var/cache/apt/archives
key: ${{ runner.os }}-apt-aur-${{ hashFiles('.github/workflows/publish.yml') }}
restore-keys: |
${{ runner.os }}-apt-aur-
- name: Setup SSH for AUR
if: github.ref_name != 'beta'
run: |
sudo apt-get update
sudo apt-get install -y pacman-package-manager
mkdir -p ~/.ssh
echo "${{ secrets.AUR_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
git config --global user.email "opencode@sst.dev"
git config --global user.name "opencode"
ssh-keyscan -H aur.archlinux.org >> ~/.ssh/known_hosts || true
- run: ./script/publish.ts
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
AUR_KEY: ${{ secrets.AUR_KEY }}
GITHUB_TOKEN: ${{ steps.committer.outputs.token }}
GH_REPO: ${{ github.repository }}
NPM_CONFIG_PROVENANCE: false
LATEST_YML_DIR: /tmp/latest-yml
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
OPENCODE_DESKTOP_UPLOADED: ${{ (github.ref_name == 'beta' && '/tmp/desktop-uploaded') || '' }}
WINGET_GITHUB_TOKEN: ${{ secrets.WINGET_GITHUB_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
notify-discord-v2:
needs:
- version
- publish
if: ${{ !cancelled() && github.repository == 'anomalyco/opencode' && github.ref_name == 'dev' && needs.version.outputs.release && needs.publish.result == 'success' }}
runs-on: blacksmith-4vcpu-ubuntu-2404
environment: release
steps:
# Unlike dev, V2 publishes a tag rather than a GitHub Release event.
- name: Announce V2 release in Discord
uses: SethCohen/github-releases-to-discord@24d166886aee4646d448c8a389ff9e1ebcab3682 # v1.20.0
with:
webhook_url: ${{ secrets.DISCORD_WEBHOOK }}
release_name: OpenCode V2 ${{ needs.version.outputs.tag }}
release_body: ${{ inputs.release_notes }}
release_html_url: https://github.com/${{ github.repository }}/tree/${{ needs.version.outputs.tag }}

727
.github/workflows/release-dry-run.yml vendored Normal file
View file

@ -0,0 +1,727 @@
name: release-dry-run
run-name: "${{ format('release {0}{1}', inputs.bump, inputs.version) }}"
# Builds are separated from signing and publishing.
# - build-* jobs run repository code (`bun run build`, `bun run pack`) with no environment, secrets or id-token.
# - sign-* and publish-* jobs run in the release environment, check out only .github/release/, and run those
# scripts on verified artifacts, which they treat as data. They never execute repository code.
# - plan decides version, channel and npm dist-tag from the event, inputs and ref; only a dispatch with a bump or
# version on dev reaches latest.
# .github/release/ and this file are the security boundary for releases.
# TEMPORARY copy of release.yml for this PR's dry run: GitHub does not start runs for the release.yml path on
# pull requests (it is the old name of publish.yml). Delete before merging.
on:
pull_request:
paths: [.github/workflows/release.yml, .github/workflows/release-dry-run.yml, .github/release/**]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ (inputs.bump || inputs.version) && 'release' || 'build' }}
# Beta ships only the newest commit to the team. A cancelled beta run can leave unreferenced files in R2, but only
# publish-desktop records a release, in one request.
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.ref_name == 'beta' }}
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
plan:
if: github.repository == 'anomalyco/opencode'
runs-on: ubuntu-24.04
permissions: {}
outputs:
version: ${{ steps.plan.outputs.version }}
channel: ${{ steps.plan.outputs.channel }}
npm_tag: ${{ steps.plan.outputs.npm_tag }}
dry_run: ${{ steps.plan.outputs.dry_run }}
cli: ${{ steps.plan.outputs.cli }}
desktop: ${{ steps.plan.outputs.desktop }}
node: ${{ steps.plan.outputs.node }}
release: ${{ steps.plan.outputs.release }}
steps:
- &checkout-release
name: Check out release scripts
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
ref: ${{ github.sha }}
sparse-checkout: /.github/release/
sparse-checkout-cone-mode: false
persist-credentials: false
- id: plan
name: Plan
run: bash .github/release/plan-release.sh
env:
INPUT_BUMP: ${{ inputs.bump }}
INPUT_VERSION: ${{ inputs.version }}
# A versioned release builds from a commit with its versions and changelog on the dispatched dev commit,
# tagged v<version>. Runs git only.
tag:
needs: plan
runs-on: ubuntu-24.04
permissions:
contents: write
env: &env
OPENCODE_VERSION: ${{ needs.plan.outputs.version }}
OPENCODE_CHANNEL: ${{ needs.plan.outputs.channel }}
OPENCODE_NPM_TAG: ${{ needs.plan.outputs.npm_tag }}
OPENCODE_DRY_RUN: ${{ needs.plan.outputs.dry_run }}
outputs:
sha: ${{ steps.tag.outputs.sha || github.sha }}
steps:
- name: Check out
if: needs.plan.outputs.channel == 'latest'
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- id: tag
name: Tag
if: needs.plan.outputs.channel == 'latest'
run: bash .github/release/tag-release.sh
env:
OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }}
# ---- Build: repository code; no environment, secrets or id-token --------------------------------------------
# Fetches the models.dev catalog once per run, so every CLI bundles the same copy.
models-catalog:
needs: [plan, tag]
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 10
env: *env
steps:
- &checkout
name: Check out
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
ref: ${{ needs.tag.outputs.sha }}
persist-credentials: false
- name: Set up Bun
uses: ./.github/actions/setup-bun
- name: Fetch
run: bun packages/core/script/update-models-snapshot.ts .cache/models-catalog/api.json
- name: Upload
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: models-catalog
path: .cache/models-catalog/api.json
if-no-files-found: error
build-cli:
needs: [plan, tag, models-catalog]
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
with:
bun-version: 1.4.4
- &download-models-catalog
name: Download models catalog
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: models-catalog
path: .cache/models-catalog
- name: Build
working-directory: packages/cli
run: bun run build && rm -rf dist/.bun
env:
BUN_COMPILE_RELEASE: bun-v1.4.4
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
OPENCODE_RELEASE_NOTES: ${{ needs.plan.outputs.channel == 'latest' && inputs.release_notes || '' }}
GH_TOKEN: ${{ github.token }} # read-only; raises the rate limit for Bun release downloads
- name: Verify bundled models catalog
run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/cli-linux-x64/bin/opencode
env:
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
- name: Upload
uses: ./.github/release/upload
with:
name: build-cli
path: packages/cli/dist
build-node:
needs: [plan, tag, models-catalog]
if: needs.plan.outputs.node == 'true'
strategy:
fail-fast: false
matrix:
include:
- { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm }
- { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 }
- { target: darwin-arm64, host: macos-26 }
- { target: windows-arm64, host: blacksmith-4vcpu-windows-2025 }
- { target: windows-x64, host: blacksmith-4vcpu-windows-2025 }
runs-on: ${{ matrix.host }}
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
- name: Set up Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- *download-models-catalog
- name: Build
working-directory: packages/cli
run: bun run build:node
env:
OPENCODE_TARGET: ${{ matrix.target }}
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
- name: Test
if: matrix.target != 'windows-arm64'
working-directory: packages/cli
run: bun run script/service-smoke.ts --node
- name: Verify bundled models catalog
if: matrix.target != 'windows-arm64'
run: bun packages/cli/script/catalog-smoke.ts "packages/cli/dist/node/cli-node-$OPENCODE_TARGET/bin/opencode2-node$EXE"
env:
OPENCODE_TARGET: ${{ matrix.target }}
EXE: ${{ startsWith(matrix.target, 'windows') && '.exe' || '' }}
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
- name: Upload
uses: ./.github/release/upload
with:
name: build-node-${{ matrix.target }}
path: packages/cli/dist/node
# `bun run pack` packs every npm package into dist/npm and the Linux and Node CLI archives into dist/archives.
# The macOS and Windows CLI packages and archives are re-packed after signing.
build-npm:
needs: [plan, tag, build-cli, build-node]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }}
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
- &download-cli
name: Download
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: build-cli
path: packages/cli/dist
- name: Download Node CLI
if: needs.plan.outputs.node == 'true'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
pattern: build-node-*
path: packages/cli/dist/node
merge-multiple: true
- name: Pack
run: rm packages/cli/dist/SHA256SUMS && bun run pack
- name: Upload
uses: ./.github/release/upload
with:
name: build-npm
path: dist/npm
- name: Upload archives
uses: ./.github/release/upload
with:
name: build-archives
path: dist/archives
build-docker:
needs: [plan, tag, build-cli]
if: needs.plan.outputs.release == 'true'
runs-on: blacksmith-4vcpu-ubuntu-2404
env: *env
steps:
- *checkout
- *download-cli
- name: Set up QEMU
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
- name: Set up Buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- name: Set up Bun
uses: ./.github/actions/setup-bun
- name: Pack
working-directory: packages/cli
run: bun run pack:docker
- name: Upload
uses: ./.github/release/upload
with:
name: build-docker
path: dist/docker
# macOS and Windows pack an unsigned app; Linux packs the final AppImage, deb and rpm.
# Beta packages macOS x64 on Apple Silicon and Windows arm64 on Blacksmith for speed. electron-builder's afterPack
# rejects a bundle whose CLI or node-pty does not match the target CPU.
build-desktop:
needs: [plan, tag, build-cli]
if: needs.plan.outputs.desktop == 'true'
permissions:
contents: read
pull-requests: read # beta builds read who made each change and what it does for "What's new in beta"
strategy:
fail-fast: false
matrix:
include:
- target: darwin-x64
host: ${{ github.ref_name == 'beta' && 'macos-26' || 'macos-26-intel' }}
install: ${{ github.ref_name == 'beta' && '--os=darwin --cpu=*' || '--os=darwin --cpu=x64' }}
- { target: darwin-arm64, host: macos-26, install: --os=darwin --cpu=arm64 }
# github-hosted: blacksmith lacks the ARM64 MSVC cross-compilation toolchain
- target: windows-arm64
host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }}
install: --cpu=*
- { target: windows-x64, host: blacksmith-4vcpu-windows-2025 }
- { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 }
- { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm }
runs-on: ${{ matrix.host }}
env: *env
steps:
- *checkout
- *download-cli
- name: Set up Bun
uses: ./.github/actions/setup-bun
with:
install-flags: ${{ matrix.install }}
- name: Set up rpm
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends rpm
# The beta build embeds the subjects of its newest commits for "What's new in beta"
# (packages/desktop/script/beta-notes.ts). Commits without file contents are enough.
- name: Fetch beta history
if: needs.plan.outputs.channel == 'beta'
run: git fetch --no-tags --filter=blob:none --depth=300 origin "$SHA"
env:
SHA: ${{ needs.tag.outputs.sha }}
# Beta trades larger packages for faster packaging. fpm sets XZ_OPT for the deb and rpm level, but xz still
# reads XZ_DEFAULTS, so it uses every CPU.
- name: Beta packaging settings
if: needs.plan.outputs.channel == 'beta' && runner.os == 'Linux'
run: echo "XZ_DEFAULTS=-T0" >> "$GITHUB_ENV"
- name: Build
working-directory: packages/desktop
run: bun run build
env:
OPENCODE_TARGET: ${{ matrix.target }}
NODE_OPTIONS: --max-old-space-size=4096
VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ needs.plan.outputs.channel == 'beta' && 'beta' || 'production' }}
VITE_SENTRY_RELEASE: desktop@${{ needs.plan.outputs.version }}
GITHUB_TOKEN: ${{ github.token }} # read-only; beta notes read pull request authors and descriptions
- name: Pack
working-directory: packages/desktop
timeout-minutes: 60
run: bun run pack
env:
OPENCODE_TARGET: ${{ matrix.target }}
- name: Upload
uses: ./.github/release/upload
with:
name: build-desktop-${{ matrix.target }}
path: dist/desktop
# Packs the NSIS installer around the signed app. This runs repository config, so it is a build job; the
# installer is signed next.
build-desktop-windows-installer:
needs: [plan, tag, sign-windows]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }}
strategy:
fail-fast: false
matrix:
include:
- target: windows-arm64
host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }}
install: --cpu=*
- { target: windows-x64, host: blacksmith-4vcpu-windows-2025 }
runs-on: ${{ matrix.host }}
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
with:
install-flags: ${{ matrix.install }}
- name: Download
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: sign-desktop-${{ matrix.target }}
path: ${{ runner.temp }}/app
- name: Pack
working-directory: packages/desktop
timeout-minutes: 30
run: bun run pack
env:
OPENCODE_TARGET: ${{ matrix.target }}
OPENCODE_DESKTOP_APP: ${{ runner.temp }}/app/app
- name: Upload
uses: ./.github/release/upload
with:
name: build-desktop-windows-installer-${{ matrix.target }}
path: dist/desktop
# ---- Sign: release environment; only .github/release/ is checked out ----------------------------------------
# Pull requests run sign and publish jobs without an environment, so steps that need a secret skip or dry-run.
# Signs the macOS CLI; signs the desktop apps inside-out, notarizes them in one submission, staples them, and
# only then builds the zip, dmg and .app.tar.gz from the stapled apps.
sign-macos:
needs: [plan, build-npm, build-desktop]
if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }}
runs-on: macos-26
timeout-minutes: 90
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
env: *env
outputs:
digest: ${{ steps.upload.outputs.digest }}
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-desktop-darwin-*}"
- name: Import certificate
if: needs.plan.outputs.dry_run != 'true'
uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0
with:
keychain: build
p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- name: Sign CLI
if: needs.plan.outputs.cli == 'true'
run: bash .github/release/sign-cli-macos.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/out"
- name: Sign desktop
if: needs.plan.outputs.desktop == 'true'
run: |
bash .github/release/sign-desktop-macos.sh "$RUNNER_TEMP/out" \
"$RUNNER_TEMP"/in/build-desktop-darwin-*/opencode-desktop-mac-*.app.tar
env:
APPLE_API_KEY_CONTENT: ${{ secrets.APPLE_API_KEY_PATH }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
- id: upload
name: Upload
uses: ./.github/release/upload
with:
name: sign-macos
path: ${{ runner.temp }}/out
# Signs the Windows CLI and every executable and native module of the unpacked desktop apps.
sign-windows:
needs: [plan, build-npm, build-desktop]
if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }}
runs-on: windows-2025
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
outputs:
digest: ${{ steps.upload.outputs.digest }}
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-desktop-windows-*}"
- name: Unpack
run: bash .github/release/unpack-windows.sh "$RUNNER_TEMP/in" "$RUNNER_TEMP/work"
- &azure-login
name: Log in to Azure
if: needs.plan.outputs.dry_run != 'true'
uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- &azure-sign
name: Sign
if: needs.plan.outputs.dry_run != 'true'
uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0
with:
endpoint: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
signing-account-name: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
certificate-profile-name: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
files-folder: ${{ runner.temp }}\work
files-folder-filter: exe,node
files-folder-recurse: true
exclude-environment-credential: true
exclude-workload-identity-credential: true
exclude-managed-identity-credential: true
exclude-shared-token-cache-credential: true
exclude-visual-studio-credential: true
exclude-visual-studio-code-credential: true
exclude-azure-cli-credential: false
exclude-azure-powershell-credential: true
exclude-azure-developer-cli-credential: true
exclude-interactive-browser-credential: true
- name: Repack
run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out"
- id: upload
name: Upload
if: needs.plan.outputs.cli == 'true'
uses: ./.github/release/upload
with:
name: sign-windows
path: ${{ runner.temp }}/out
- name: Upload arm64 app
if: needs.plan.outputs.desktop == 'true'
uses: ./.github/release/upload
with:
name: sign-desktop-windows-arm64
path: ${{ runner.temp }}/work/desktop-windows-arm64
- name: Upload x64 app
if: needs.plan.outputs.desktop == 'true'
uses: ./.github/release/upload
with:
name: sign-desktop-windows-x64
path: ${{ runner.temp }}/work/desktop-windows-x64
sign-desktop-windows-installer:
needs: [plan, build-desktop-windows-installer]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }}
runs-on: windows-2025
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
outputs:
digest: ${{ steps.upload.outputs.digest }}
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: build-desktop-windows-installer-*
- name: Unpack
run: mkdir -p "$RUNNER_TEMP/work" && cp "$RUNNER_TEMP"/in/build-desktop-windows-installer-*/*.exe "$RUNNER_TEMP/work/"
- *azure-login
- *azure-sign
- name: Repack
run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out"
- id: upload
name: Upload
uses: ./.github/release/upload
with:
name: sign-desktop-windows-installer
path: ${{ runner.temp }}/work
# ---- Publish: release environment; only .github/release/ is checked out -------------------------------------
# Destinations, names and channels come from plan and the scripts, never from artifacts.
# Build provenance for the npm tarballs and Linux archives. No secrets; id-token only for Sigstore.
publish-attestations:
needs: [plan, build-npm]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' && needs.plan.outputs.dry_run != 'true' }}
runs-on: ubuntu-24.04
permissions:
contents: read
id-token: write
attestations: write
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-archives}"
- name: Sign
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: |
${{ runner.temp }}/in/build-npm/*.tgz
${{ runner.temp }}/in/build-archives/opencode*
publish-npm:
needs: [plan, sign-macos, sign-windows, publish-attestations]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
attestations: read
env: *env
steps:
- *checkout-release
- name: Set up Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "24.11.0"
- &download-signed-cli
name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-archives,sign-macos,sign-windows}"
digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }}
- name: Publish
run: bash .github/release/publish-npm.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows"
env:
GH_TOKEN: ${{ github.token }}
publish-cli:
needs: [plan, sign-macos, sign-windows, publish-npm]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- *download-signed-cli
- name: Publish
run: bash .github/release/publish-cli.sh "$RUNNER_TEMP/in/build-archives" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows"
env: &cloudflare
CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
publish-desktop:
needs: [plan, sign-macos, sign-desktop-windows-installer]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{sign-macos,sign-desktop-windows-installer,build-desktop-linux-*}"
digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }}
- name: Publish
run: |
bash .github/release/publish-desktop.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-desktop-windows-installer" \
"$RUNNER_TEMP/in/build-desktop-linux-x64" "$RUNNER_TEMP/in/build-desktop-linux-arm64"
env: *cloudflare
publish-docker:
needs: [plan, build-docker]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
packages: write
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: build-docker
- name: Publish
run: bash .github/release/publish-docker.sh "$RUNNER_TEMP/in/build-docker"
env:
GH_TOKEN: ${{ github.token }}
publish-homebrew:
needs: [plan, sign-macos, sign-windows, publish-cli]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- *download-signed-cli
- id: token
name: Create token
if: needs.plan.outputs.dry_run != 'true'
uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2
with:
app-id: ${{ vars.OPENCODE_APP_ID }}
private-key: ${{ secrets.OPENCODE_APP_SECRET }}
owner: anomalyco
repositories: homebrew-tap
- name: Publish
run: bash .github/release/publish-homebrew.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/build-archives"
env:
HOMEBREW_TOKEN: ${{ steps.token.outputs.token }}
# The AUR package installs the published npm tarballs, so it follows the npm publish.
publish-aur:
needs: [plan, sign-macos, sign-windows, publish-npm]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- *download-signed-cli
- name: Publish
run: bash .github/release/publish-aur.sh "$RUNNER_TEMP/in/build-npm"
env:
AUR_KEY: ${{ secrets.AUR_KEY }}
# WinGet manifests as data. Submission to microsoft/winget-pkgs stays paused until the packages are accepted.
publish-winget:
needs: [plan, sign-windows, sign-desktop-windows-installer]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{sign-windows,sign-desktop-windows-installer}"
digests: sign-windows=${{ needs.sign-windows.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }}
- name: Render
run: bash .github/release/render-winget.sh "$RUNNER_TEMP/in/sign-windows" "$RUNNER_TEMP/in/sign-desktop-windows-installer" "$RUNNER_TEMP/out"
- name: Upload
uses: ./.github/release/upload
with:
name: publish-winget
path: ${{ runner.temp }}/out
publish-github-release:
needs: [plan, sign-macos, sign-windows, sign-desktop-windows-installer, publish-cli, publish-desktop]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: write
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-archives,build-desktop-linux-*,sign-macos,sign-windows,sign-desktop-windows-installer}"
digests: >-
sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }}
sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }}
- name: Publish
run: bash .github/release/publish-github-release.sh "$RUNNER_TEMP"/in/*
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }}
# Brings the release commit back to dev. Pushing to dev is blocked by rulesets, so it opens a PR.
publish-version-pr:
needs: [plan, tag, publish-npm, publish-cli, publish-desktop, publish-github-release]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.channel == 'latest' }}
runs-on: ubuntu-24.04
permissions:
contents: write
pull-requests: write
env: *env
steps:
- *checkout-release
- name: Publish
run: bash .github/release/publish-version-pr.sh "$SHA"
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
SHA: ${{ needs.tag.outputs.sha }}

740
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,740 @@
name: release
run-name: "${{ format('release {0}{1}', inputs.bump, inputs.version) }}"
# Builds are separated from signing and publishing.
# - build-* jobs run repository code (`bun run build`, `bun run pack`) with no environment, secrets or id-token.
# - sign-* and publish-* jobs run in the release environment, check out only .github/release/, and run those
# scripts on verified artifacts, which they treat as data. They never execute repository code.
# - plan decides version, channel and npm dist-tag from the event, inputs and ref; only a dispatch with a bump or
# version on dev reaches latest.
# .github/release/ and this file are the security boundary for releases.
on:
push:
branches: [dev, beta]
workflow_dispatch:
inputs:
bump:
description: "Bump major, minor, or patch"
required: false
type: choice
options: [major, minor, patch]
version:
description: "Override version (optional)"
required: false
type: string
release_notes:
description: "Reviewed V2 release notes for CHANGELOG.md and the GitHub release (optional)"
required: false
type: string
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ (inputs.bump || inputs.version) && 'release' || 'build' }}
# Beta ships only the newest commit to the team. A cancelled beta run can leave unreferenced files in R2, but only
# publish-desktop records a release, in one request.
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.ref_name == 'beta' }}
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
plan:
if: github.repository == 'anomalyco/opencode'
runs-on: ubuntu-24.04
permissions: {}
outputs:
version: ${{ steps.plan.outputs.version }}
channel: ${{ steps.plan.outputs.channel }}
npm_tag: ${{ steps.plan.outputs.npm_tag }}
dry_run: ${{ steps.plan.outputs.dry_run }}
cli: ${{ steps.plan.outputs.cli }}
desktop: ${{ steps.plan.outputs.desktop }}
node: ${{ steps.plan.outputs.node }}
release: ${{ steps.plan.outputs.release }}
steps:
- &checkout-release
name: Check out release scripts
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
ref: ${{ github.sha }}
sparse-checkout: /.github/release/
sparse-checkout-cone-mode: false
persist-credentials: false
- id: plan
name: Plan
run: bash .github/release/plan-release.sh
env:
INPUT_BUMP: ${{ inputs.bump }}
INPUT_VERSION: ${{ inputs.version }}
# A versioned release builds from a commit with its versions and changelog on the dispatched dev commit,
# tagged v<version>. Runs git only.
tag:
needs: plan
runs-on: ubuntu-24.04
permissions:
contents: write
env: &env
OPENCODE_VERSION: ${{ needs.plan.outputs.version }}
OPENCODE_CHANNEL: ${{ needs.plan.outputs.channel }}
OPENCODE_NPM_TAG: ${{ needs.plan.outputs.npm_tag }}
OPENCODE_DRY_RUN: ${{ needs.plan.outputs.dry_run }}
outputs:
sha: ${{ steps.tag.outputs.sha || github.sha }}
steps:
- name: Check out
if: needs.plan.outputs.channel == 'latest'
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- id: tag
name: Tag
if: needs.plan.outputs.channel == 'latest'
run: bash .github/release/tag-release.sh
env:
OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }}
# ---- Build: repository code; no environment, secrets or id-token --------------------------------------------
# Fetches the models.dev catalog once per run, so every CLI bundles the same copy.
models-catalog:
needs: [plan, tag]
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 10
env: *env
steps:
- &checkout
name: Check out
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
ref: ${{ needs.tag.outputs.sha }}
persist-credentials: false
- name: Set up Bun
uses: ./.github/actions/setup-bun
- name: Fetch
run: bun packages/core/script/update-models-snapshot.ts .cache/models-catalog/api.json
- name: Upload
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: models-catalog
path: .cache/models-catalog/api.json
if-no-files-found: error
build-cli:
needs: [plan, tag, models-catalog]
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
with:
bun-version: 1.4.4
- &download-models-catalog
name: Download models catalog
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: models-catalog
path: .cache/models-catalog
- name: Build
working-directory: packages/cli
run: bun run build && rm -rf dist/.bun
env:
BUN_COMPILE_RELEASE: bun-v1.4.4
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
OPENCODE_RELEASE_NOTES: ${{ needs.plan.outputs.channel == 'latest' && inputs.release_notes || '' }}
GH_TOKEN: ${{ github.token }} # read-only; raises the rate limit for Bun release downloads
- name: Verify bundled models catalog
run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/cli-linux-x64/bin/opencode
env:
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
- name: Upload
uses: ./.github/release/upload
with:
name: build-cli
path: packages/cli/dist
build-node:
needs: [plan, tag, models-catalog]
if: needs.plan.outputs.node == 'true'
strategy:
fail-fast: false
matrix:
include:
- { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm }
- { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 }
- { target: darwin-arm64, host: macos-26 }
- { target: windows-arm64, host: blacksmith-4vcpu-windows-2025 }
- { target: windows-x64, host: blacksmith-4vcpu-windows-2025 }
runs-on: ${{ matrix.host }}
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
- name: Set up Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- *download-models-catalog
- name: Build
working-directory: packages/cli
run: bun run build:node
env:
OPENCODE_TARGET: ${{ matrix.target }}
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
- name: Test
if: matrix.target != 'windows-arm64'
working-directory: packages/cli
run: bun run script/service-smoke.ts --node
- name: Verify bundled models catalog
if: matrix.target != 'windows-arm64'
run: bun packages/cli/script/catalog-smoke.ts "packages/cli/dist/node/cli-node-$OPENCODE_TARGET/bin/opencode2-node$EXE"
env:
OPENCODE_TARGET: ${{ matrix.target }}
EXE: ${{ startsWith(matrix.target, 'windows') && '.exe' || '' }}
OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json
- name: Upload
uses: ./.github/release/upload
with:
name: build-node-${{ matrix.target }}
path: packages/cli/dist/node
# `bun run pack` packs every npm package into dist/npm and the Linux and Node CLI archives into dist/archives.
# The macOS and Windows CLI packages and archives are re-packed after signing.
build-npm:
needs: [plan, tag, build-cli, build-node]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }}
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
- &download-cli
name: Download
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: build-cli
path: packages/cli/dist
- name: Download Node CLI
if: needs.plan.outputs.node == 'true'
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
pattern: build-node-*
path: packages/cli/dist/node
merge-multiple: true
- name: Pack
run: rm packages/cli/dist/SHA256SUMS && bun run pack
- name: Upload
uses: ./.github/release/upload
with:
name: build-npm
path: dist/npm
- name: Upload archives
uses: ./.github/release/upload
with:
name: build-archives
path: dist/archives
build-docker:
needs: [plan, tag, build-cli]
if: needs.plan.outputs.release == 'true'
runs-on: blacksmith-4vcpu-ubuntu-2404
env: *env
steps:
- *checkout
- *download-cli
- name: Set up QEMU
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
- name: Set up Buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- name: Set up Bun
uses: ./.github/actions/setup-bun
- name: Pack
working-directory: packages/cli
run: bun run pack:docker
- name: Upload
uses: ./.github/release/upload
with:
name: build-docker
path: dist/docker
# macOS and Windows pack an unsigned app; Linux packs the final AppImage, deb and rpm.
# Beta packages macOS x64 on Apple Silicon and Windows arm64 on Blacksmith for speed. electron-builder's afterPack
# rejects a bundle whose CLI or node-pty does not match the target CPU.
build-desktop:
needs: [plan, tag, build-cli]
if: needs.plan.outputs.desktop == 'true'
permissions:
contents: read
pull-requests: read # beta builds read who made each change and what it does for "What's new in beta"
strategy:
fail-fast: false
matrix:
include:
- target: darwin-x64
host: ${{ github.ref_name == 'beta' && 'macos-26' || 'macos-26-intel' }}
install: ${{ github.ref_name == 'beta' && '--os=darwin --cpu=*' || '--os=darwin --cpu=x64' }}
- { target: darwin-arm64, host: macos-26, install: --os=darwin --cpu=arm64 }
# github-hosted: blacksmith lacks the ARM64 MSVC cross-compilation toolchain
- target: windows-arm64
host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }}
install: --cpu=*
- { target: windows-x64, host: blacksmith-4vcpu-windows-2025 }
- { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 }
- { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm }
runs-on: ${{ matrix.host }}
env: *env
steps:
- *checkout
- *download-cli
- name: Set up Bun
uses: ./.github/actions/setup-bun
with:
install-flags: ${{ matrix.install }}
- name: Set up rpm
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends rpm
# The beta build embeds the subjects of its newest commits for "What's new in beta"
# (packages/desktop/script/beta-notes.ts). Commits without file contents are enough.
- name: Fetch beta history
if: needs.plan.outputs.channel == 'beta'
run: git fetch --no-tags --filter=blob:none --depth=300 origin "$SHA"
env:
SHA: ${{ needs.tag.outputs.sha }}
# Beta trades larger packages for faster packaging. fpm sets XZ_OPT for the deb and rpm level, but xz still
# reads XZ_DEFAULTS, so it uses every CPU.
- name: Beta packaging settings
if: needs.plan.outputs.channel == 'beta' && runner.os == 'Linux'
run: echo "XZ_DEFAULTS=-T0" >> "$GITHUB_ENV"
- name: Build
working-directory: packages/desktop
run: bun run build
env:
OPENCODE_TARGET: ${{ matrix.target }}
NODE_OPTIONS: --max-old-space-size=4096
VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ needs.plan.outputs.channel == 'beta' && 'beta' || 'production' }}
VITE_SENTRY_RELEASE: desktop@${{ needs.plan.outputs.version }}
GITHUB_TOKEN: ${{ github.token }} # read-only; beta notes read pull request authors and descriptions
- name: Pack
working-directory: packages/desktop
timeout-minutes: 60
run: bun run pack
env:
OPENCODE_TARGET: ${{ matrix.target }}
- name: Upload
uses: ./.github/release/upload
with:
name: build-desktop-${{ matrix.target }}
path: dist/desktop
# Packs the NSIS installer around the signed app. This runs repository config, so it is a build job; the
# installer is signed next.
build-desktop-windows-installer:
needs: [plan, tag, sign-windows]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }}
strategy:
fail-fast: false
matrix:
include:
- target: windows-arm64
host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }}
install: --cpu=*
- { target: windows-x64, host: blacksmith-4vcpu-windows-2025 }
runs-on: ${{ matrix.host }}
env: *env
steps:
- *checkout
- name: Set up Bun
uses: ./.github/actions/setup-bun
with:
install-flags: ${{ matrix.install }}
- name: Download
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: sign-desktop-${{ matrix.target }}
path: ${{ runner.temp }}/app
- name: Pack
working-directory: packages/desktop
timeout-minutes: 30
run: bun run pack
env:
OPENCODE_TARGET: ${{ matrix.target }}
OPENCODE_DESKTOP_APP: ${{ runner.temp }}/app/app
- name: Upload
uses: ./.github/release/upload
with:
name: build-desktop-windows-installer-${{ matrix.target }}
path: dist/desktop
# ---- Sign: release environment; only .github/release/ is checked out ----------------------------------------
# Pull requests run sign and publish jobs without an environment, so steps that need a secret skip or dry-run.
# Signs the macOS CLI; signs the desktop apps inside-out, notarizes them in one submission, staples them, and
# only then builds the zip, dmg and .app.tar.gz from the stapled apps.
sign-macos:
needs: [plan, build-npm, build-desktop]
if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }}
runs-on: macos-26
timeout-minutes: 90
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
env: *env
outputs:
digest: ${{ steps.upload.outputs.digest }}
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-desktop-darwin-*}"
- name: Import certificate
if: needs.plan.outputs.dry_run != 'true'
uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0
with:
keychain: build
p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- name: Sign CLI
if: needs.plan.outputs.cli == 'true'
run: bash .github/release/sign-cli-macos.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/out"
- name: Sign desktop
if: needs.plan.outputs.desktop == 'true'
run: |
bash .github/release/sign-desktop-macos.sh "$RUNNER_TEMP/out" \
"$RUNNER_TEMP"/in/build-desktop-darwin-*/opencode-desktop-mac-*.app.tar
env:
APPLE_API_KEY_CONTENT: ${{ secrets.APPLE_API_KEY_PATH }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
- id: upload
name: Upload
uses: ./.github/release/upload
with:
name: sign-macos
path: ${{ runner.temp }}/out
# Signs the Windows CLI and every executable and native module of the unpacked desktop apps.
sign-windows:
needs: [plan, build-npm, build-desktop]
if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }}
runs-on: windows-2025
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
outputs:
digest: ${{ steps.upload.outputs.digest }}
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-desktop-windows-*}"
- name: Unpack
run: bash .github/release/unpack-windows.sh "$RUNNER_TEMP/in" "$RUNNER_TEMP/work"
- &azure-login
name: Log in to Azure
if: needs.plan.outputs.dry_run != 'true'
uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- &azure-sign
name: Sign
if: needs.plan.outputs.dry_run != 'true'
uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0
with:
endpoint: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
signing-account-name: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
certificate-profile-name: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
files-folder: ${{ runner.temp }}\work
files-folder-filter: exe,node
files-folder-recurse: true
exclude-environment-credential: true
exclude-workload-identity-credential: true
exclude-managed-identity-credential: true
exclude-shared-token-cache-credential: true
exclude-visual-studio-credential: true
exclude-visual-studio-code-credential: true
exclude-azure-cli-credential: false
exclude-azure-powershell-credential: true
exclude-azure-developer-cli-credential: true
exclude-interactive-browser-credential: true
- name: Repack
run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out"
- id: upload
name: Upload
if: needs.plan.outputs.cli == 'true'
uses: ./.github/release/upload
with:
name: sign-windows
path: ${{ runner.temp }}/out
- name: Upload arm64 app
if: needs.plan.outputs.desktop == 'true'
uses: ./.github/release/upload
with:
name: sign-desktop-windows-arm64
path: ${{ runner.temp }}/work/desktop-windows-arm64
- name: Upload x64 app
if: needs.plan.outputs.desktop == 'true'
uses: ./.github/release/upload
with:
name: sign-desktop-windows-x64
path: ${{ runner.temp }}/work/desktop-windows-x64
sign-desktop-windows-installer:
needs: [plan, build-desktop-windows-installer]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }}
runs-on: windows-2025
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
outputs:
digest: ${{ steps.upload.outputs.digest }}
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: build-desktop-windows-installer-*
- name: Unpack
run: mkdir -p "$RUNNER_TEMP/work" && cp "$RUNNER_TEMP"/in/build-desktop-windows-installer-*/*.exe "$RUNNER_TEMP/work/"
- *azure-login
- *azure-sign
- name: Repack
run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out"
- id: upload
name: Upload
uses: ./.github/release/upload
with:
name: sign-desktop-windows-installer
path: ${{ runner.temp }}/work
# ---- Publish: release environment; only .github/release/ is checked out -------------------------------------
# Destinations, names and channels come from plan and the scripts, never from artifacts.
# Build provenance for the npm tarballs and Linux archives. No secrets; id-token only for Sigstore.
publish-attestations:
needs: [plan, build-npm]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' && needs.plan.outputs.dry_run != 'true' }}
runs-on: ubuntu-24.04
permissions:
contents: read
id-token: write
attestations: write
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-archives}"
- name: Sign
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: |
${{ runner.temp }}/in/build-npm/*.tgz
${{ runner.temp }}/in/build-archives/opencode*
publish-npm:
needs: [plan, sign-macos, sign-windows, publish-attestations]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
attestations: read
env: *env
steps:
- *checkout-release
- name: Set up Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "24.11.0"
- &download-signed-cli
name: Download
uses: ./.github/release/download
with:
pattern: "{build-npm,build-archives,sign-macos,sign-windows}"
digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }}
- name: Publish
run: bash .github/release/publish-npm.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows"
env:
GH_TOKEN: ${{ github.token }}
publish-cli:
needs: [plan, sign-macos, sign-windows, publish-npm]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- *download-signed-cli
- name: Publish
run: bash .github/release/publish-cli.sh "$RUNNER_TEMP/in/build-archives" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows"
env: &cloudflare
CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
publish-desktop:
needs: [plan, sign-macos, sign-desktop-windows-installer]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{sign-macos,sign-desktop-windows-installer,build-desktop-linux-*}"
digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }}
- name: Publish
run: |
bash .github/release/publish-desktop.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-desktop-windows-installer" \
"$RUNNER_TEMP/in/build-desktop-linux-x64" "$RUNNER_TEMP/in/build-desktop-linux-arm64"
env: *cloudflare
publish-docker:
needs: [plan, build-docker]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
packages: write
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: build-docker
- name: Publish
run: bash .github/release/publish-docker.sh "$RUNNER_TEMP/in/build-docker"
env:
GH_TOKEN: ${{ github.token }}
publish-homebrew:
needs: [plan, sign-macos, sign-windows, publish-cli]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- *download-signed-cli
- id: token
name: Create token
if: needs.plan.outputs.dry_run != 'true'
uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2
with:
app-id: ${{ vars.OPENCODE_APP_ID }}
private-key: ${{ secrets.OPENCODE_APP_SECRET }}
owner: anomalyco
repositories: homebrew-tap
- name: Publish
run: bash .github/release/publish-homebrew.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/build-archives"
env:
HOMEBREW_TOKEN: ${{ steps.token.outputs.token }}
# The AUR package installs the published npm tarballs, so it follows the npm publish.
publish-aur:
needs: [plan, sign-macos, sign-windows, publish-npm]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: read
id-token: write
env: *env
steps:
- *checkout-release
- *download-signed-cli
- name: Publish
run: bash .github/release/publish-aur.sh "$RUNNER_TEMP/in/build-npm"
env:
AUR_KEY: ${{ secrets.AUR_KEY }}
# WinGet manifests as data. Submission to microsoft/winget-pkgs stays paused until the packages are accepted.
publish-winget:
needs: [plan, sign-windows, sign-desktop-windows-installer]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{sign-windows,sign-desktop-windows-installer}"
digests: sign-windows=${{ needs.sign-windows.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }}
- name: Render
run: bash .github/release/render-winget.sh "$RUNNER_TEMP/in/sign-windows" "$RUNNER_TEMP/in/sign-desktop-windows-installer" "$RUNNER_TEMP/out"
- name: Upload
uses: ./.github/release/upload
with:
name: publish-winget
path: ${{ runner.temp }}/out
publish-github-release:
needs: [plan, sign-macos, sign-windows, sign-desktop-windows-installer, publish-cli, publish-desktop]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }}
runs-on: ubuntu-24.04
environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }}
permissions:
contents: write
env: *env
steps:
- *checkout-release
- name: Download
uses: ./.github/release/download
with:
pattern: "{build-archives,build-desktop-linux-*,sign-macos,sign-windows,sign-desktop-windows-installer}"
digests: >-
sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }}
sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }}
- name: Publish
run: bash .github/release/publish-github-release.sh "$RUNNER_TEMP"/in/*
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }}
# Brings the release commit back to dev. Pushing to dev is blocked by rulesets, so it opens a PR.
publish-version-pr:
needs: [plan, tag, publish-npm, publish-cli, publish-desktop, publish-github-release]
if: ${{ !cancelled() && !failure() && needs.plan.outputs.channel == 'latest' }}
runs-on: ubuntu-24.04
permissions:
contents: write
pull-requests: write
env: *env
steps:
- *checkout-release
- name: Publish
run: bash .github/release/publish-version-pr.sh "$SHA"
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
SHA: ${{ needs.tag.outputs.sha }}

View file

@ -5,13 +5,13 @@ description: Use when writing, changing, reviewing, or debugging Playwright e2e
# App e2e tests
Read `packages/app/e2e/AGENTS.md` and the Tests section of `packages/app/AGENTS.md` first. They define what to test, which locators to use, and how to assert. `packages/app/README.md` (E2E Testing) documents run modes and env vars. This skill covers what makes these tests slow or flaky in CI, which runs the suite as two shards per OS on 4-vCPU runners (`.github/workflows/test.yml:207-229`). Most races below were found on Windows.
Read `packages/app/e2e/AGENTS.md` and the Tests section of `packages/app/AGENTS.md` first. They define what to test, which locators to use, and how to assert. `packages/app/README.md` (E2E Testing) documents run modes and env vars. This skill covers what makes these tests slow or flaky in CI, which runs the suite as two shards per OS on 4-vCPU runners (`.github/workflows/check-test.yml:217-240`). Most races below were found on Windows.
All paths below are relative to `packages/app` unless they start with `packages/`, `services/` or `.github/`.
## What a test runs against
- **No opencode backend.** Each shard leg runs `bun --cwd packages/app test:e2e:built --shard=<n>/2` (`test.yml:274-279`). It builds once and starts one Bun static server, `e2e/utils/serve.ts`, on `127.0.0.1:${PLAYWRIGHT_PORT ?? 3000}`. All 5 workers share it (`playwright.config.ts:23-27`).
- **No opencode backend.** Each shard leg runs `bun --cwd packages/app test:e2e:built --shard=<n>/2` (`check-test.yml:287-292`). It builds once and starts one Bun static server, `e2e/utils/serve.ts`, on `127.0.0.1:${PLAYWRIGHT_PORT ?? 3000}`. All 5 workers share it (`playwright.config.ts:23-27`).
- `serve.ts` keeps vite preview's SPA fallback rules. Do not move built e2e back to vite preview. On case-insensitive file systems it synchronously reads the whole `dist/_assets` directory (about 3,100 files) for every asset request, so every worker's page loads wait in line. The `e2e/performance` configs still use it to keep their baselines comparable.
- **The API is an in-memory mock per page,** running in the test worker. `mockOpenCodeServer` (`e2e/utils/mock-server.ts:202`):
- answers `page.route("**/api/**")` with an Effect HttpApi handler;
@ -39,7 +39,7 @@ All paths below are relative to `packages/app` unless they start with `packages/
- **Navigate once.** Every `goto` or `reload` is a cold load of the production bundle: about 150 requests per session open, about 125 of them static files. Each test has a new context, and any `page.route` disables the HTTP cache. Reach later states through the UI or through pushed events. Reload only when surviving a reload is the contract.
- **Service workers are already blocked suite-wide** (`serviceWorkers: "block"`, `playwright.config.ts:66-67`). Do not add a per-file block; the 11 in `e2e/regression` are redundant.
- Production registers `/sw.js` on load (`src/entry.tsx:54-55`) and precaches about 1,600 files (`globPatterns: ["**/*"]`, `vite.pwa.ts:34`). `e2e/service-worker/` covers it under its own config. The main config ignores that directory (`playwright.config.ts:33-36`), and CI runs it after shard 2 (`test.yml:281-285`).
- Production registers `/sw.js` on load (`src/entry.tsx:54-55`) and precaches about 1,600 files (`globPatterns: ["**/*"]`, `vite.pwa.ts:34`). `e2e/service-worker/` covers it under its own config. The main config ignores that directory (`playwright.config.ts:33-36`), and CI runs it after shard 2 (`check-test.yml:294-298`).
- Opt back in with `test.use({ serviceWorkers: "allow" })` only when the worker is the contract. It never controls the first load (`clientsClaim: false`, `vite.pwa.ts:26-28`). After a reload it can control the page, and page routes may then miss its requests.
- Every built-mode page load logs Playwright's block warning. Console collectors must ignore it, as `captureConsoleWarnings` does (`e2e/utils/command-palette.ts:15-26`).
- **Match new routes with a RegExp or a query-aware glob, not a function.**
@ -89,12 +89,12 @@ Most of these rarely reproduce on an idle local machine.
- A rename that the regex misses quietly puts the file back in `chromium` as that serial group.
- `--project chromium`, UI mode and the VS Code extension's default project skip the file.
- **In `chromium`, files are the scheduling unit.** `fullyParallel` is off unless `PLAYWRIGHT_FULLY_PARALLEL=1` (`:42`), so a file's tests run in order on one worker. A long file sets a floor and leaves an idle tail. New regressions go into the area's keeper file (`e2e/AGENTS.md`), so keep each case cheap.
- **Shards split whole files by test count, not duration** (`test.yml:219-222`). The touch project queues last, so its tests always fall in shard 2. To reproduce a leg's schedule, pass the same `--shard`.
- **Shards split whole files by test count, not duration** (`check-test.yml:229-232`). The touch project queues last, so its tests always fall in shard 2. To reproduce a leg's schedule, pass the same `--shard`.
- **Worker-scoped options fork a worker.** `launchOptions`, `channel`, `headless`, `video`, `trace`, `screenshot` and `defaultBrowserType` give a file its own worker hash.
- Playwright groups a project's files by worker hash in order of first appearance, so such a file runs after every default file in its project.
- Use test-scoped options instead: `viewport`, `deviceScaleFactor`, `hasTouch`, `isMobile`, `userAgent`, `colorScheme`, `serviceWorkers`, `locale`.
- Use `launchOptions` only when a Chromium flag is the contract, with a comment (`patch-border.spec.ts:5-9`).
- **Never spread `devices[...]` into `test.use`.** iPhone entries set `defaultBrowserType: "webkit"`, which forks a worker and needs a browser that CI never installs (`test.yml:269-272`). Copy the fields you need, as `mobile-timeline-scroll.spec.ts:23-28` does.
- **Never spread `devices[...]` into `test.use`.** iPhone entries set `defaultBrowserType: "webkit"`, which forks a worker and needs a browser that CI never installs (`check-test.yml:282-285`). Copy the fields you need, as `mobile-timeline-scroll.spec.ts:23-28` does.
- **Retries are not free.** CI retries twice (`playwright.config.ts:44`). Each failure restarts the worker's browser and costs 10-30 s of cleanup on Windows. The first retry then reruns with a trace and a video (`:62-65`).
- **Timeouts are not a fix.** The limits are 60 s per test and 10 s per assertion (`playwright.config.ts:38-41`). `APP_READY_TIMEOUT` (30 s, `e2e/utils/waits.ts:4`) covers only first readiness.
- When one wait is genuinely long, scope the timeout to that assertion and say what takes the time. `settings-wsl.spec.ts:268-276` does this with `{ timeout: 20_000 }` for a 10 s health check.
@ -122,11 +122,11 @@ Run from `packages/app`:
## When CI flakes
- **Find it.** e2e runs on pull requests that affect `@opencode/app` or `@opencode/stories`, including their workspace dependencies, and on every manual dispatch (`.github/workflows/test.yml:43-55`). It never runs on dev (`:28`).
- **Find it.** e2e runs on pull requests that affect `@opencode/app` or `@opencode/stories`, including their workspace dependencies, and on every manual dispatch (`.github/workflows/check-test.yml:50-62`). It never runs on dev (`:28`).
- Each OS has the legs `app-1` and `app-2` (the shards), `session-ui-components` and `app-components`.
- The required `e2e (linux)` and `e2e (windows)` checks only aggregate those legs (`:319-334`).
- The required `e2e (linux)` and `e2e (windows)` checks only aggregate those legs (`:329-352`).
- A pass on retry leaves a leg green. Check each Windows shard report's Flaky list, and make sure your new tests are not on it.
- **Download:** `gh run download <run-id> -n playwright-windows-app-2-1 -D <dir>`. Artifacts are named `playwright-<os>-<leg>-<run attempt>` (`test.yml:301-314`). App e2e results are in `<dir>/app/e2e/`.
- **Download:** `gh run download <run-id> -n playwright-windows-app-2-1 -D <dir>`. Artifacts are named `playwright-<os>-<leg>-<run attempt>` (`check-test.yml:314-327`). App e2e results are in `<dir>/app/e2e/`.
- **In CI, the failing first attempt has no trace and no video** (`playwright.config.ts:62-65`).
- `test-results/<test>-<project>/` holds `error-context.md` (the aria snapshot at the failure) and `test-failed-1.png`.
- `<test>-<project>-retry1/` holds `trace.zip` and `video.webm` whether the retry passed or failed, plus failure files only if it failed. A second retry records neither.

View file

@ -56,7 +56,7 @@ Use these when the contract is not visible in a story, such as construction coun
## Cold vs warm, and what a mount costs
- **CI is always cold.** Each suite runs in its own leg on a fresh runner (`test.yml:228-229`), so every leg starts the story server with no cache and runs the full scan.
- **CI is always cold.** Each suite runs in its own leg on a fresh runner (`check-test.yml:239-240`), so every leg starts the story server with no cache and runs the full scan.
- **Do not count the first test.** In one CI run of this harness, the first test per worker took 5.7-7.0 s on Linux and 14-15 s on Windows. Warm tests had a median of 1.5 s (app) and 2.0 s (session-ui) on Linux and 2.4-2.6 s on Windows. A warm `mount` (navigation plus root wait) had a median of 1.0 s (app) and 1.5 s (session-ui) on Linux and 1.7-1.9 s on Windows, which is most of a typical test. Judge cost by warm attempts.
- **Local reuse.** Playwright reuses whatever answers on the port (`config.ts:20`; default 6006, `config.ts:3`). That hides cold cost and reloads, and with several worktrees another checkout's story server can serve your tests its own code. Set `PLAYWRIGHT_STORIES_PORT` or `PLAYWRIGHT_STORIES_URL` (`config.ts:3-4`). On Windows pick a port below 49152: the dynamic range starts there, and Hyper-V and WSL reserve blocks inside it (`netsh int ipv4 show excludedportrange protocol=tcp`). Two story servers in one checkout share, and race on, `packages/stories/node_modules/.vite`, so a separate port is not enough: use a separate worktree.
- **Keep mounts few.** Put one scenario in each test, and resize in place with `page.setViewportSize` (`composer.spec.ts:28-29`) instead of mounting again.
@ -101,15 +101,15 @@ From the owning package (`packages/session-ui` or `packages/app`):
5. **Windows.** Check platform keys and labels and font-dependent geometry. The Windows component legs are the authoritative check.
- Do not skip on Windows, and do not raise `config.ts` timeouts, retries or the `mount` wait.
- If one test does genuinely expensive work, call `story.setTimeout(...)` in that test, with a comment that names the work.
6. **Confirm CI ran the component legs.** E2E never runs on pushes to dev (`test.yml:28`), so no post-merge run catches a regression.
- The `affected` gate filters on `@opencode/app` and `@opencode/stories` (`test.yml:53-54`). `ui`, `session-ui` and `gui-extensions` count through app's dependencies. `workflow_dispatch` forces the legs on (`test.yml:48-51`).
- `test.yml` is listed in `globalDependencies` (`turbo.json:8`), so editing it marks every package affected.
- The required `e2e (linux)` and `e2e (windows)` checks also pass when no leg was needed (`test.yml:316-335`). Look for `e2e (<os>, session-ui-components)` and `e2e (<os>, app-components)`.
6. **Confirm CI ran the component legs.** E2E never runs on pushes to dev (`check-test.yml:28`), so no post-merge run catches a regression.
- The `affected` gate filters on `@opencode/app` and `@opencode/stories` (`check-test.yml:60-61`). `ui`, `session-ui` and `gui-extensions` count through app's dependencies. `workflow_dispatch` forces the legs on (`check-test.yml:56-59`).
- `check-test.yml` is listed in `globalDependencies` (`turbo.json:8`), so editing it marks every package affected.
- The required `e2e (linux)` and `e2e (windows)` checks also pass when no leg was needed (`check-test.yml:329-352`). Look for `e2e (<os>, session-ui-components)` and `e2e (<os>, app-components)`.
- If CI skipped them, report your local cold run in the PR.
## When CI flakes
- **Download the artifact.** Run `gh run download <run-id> -n playwright-<linux|windows>-<session-ui|app>-components-<attempt> -D <dir>` (`test.yml:301-314`). Results are in `<dir>/session-ui/component-tests/` or `<dir>/app/component-tests/`. Only the first retry has a trace and, in CI, a video: `test-results/<test>-components-retry1/`.
- **Download the artifact.** Run `gh run download <run-id> -n playwright-<linux|windows>-<session-ui|app>-components-<attempt> -D <dir>` (`check-test.yml:314-327`). Results are in `<dir>/session-ui/component-tests/` or `<dir>/app/component-tests/`. Only the first retry has a trace and, in CI, a video: `test-results/<test>-components-retry1/`.
- **Find reloads.** The story server's output reaches the job log with a `[WebServer]` prefix, so grep the log for `optimized dependencies changed`. In the retry trace, a reload shows up as any of:
- a second frame (`/?id=…`) load and a second `[vite] connecting...`;
- the deps `?v=` hash changing between requests;

View file

@ -5,7 +5,7 @@ description: Use when writing, fixing, or reviewing tests that render OpenTUI (t
# TUI tests
packages/tui runs about 170 test files in one `bun test` process. CI runs it next to up to two other suites on 4-vCPU runners (`bun turbo test --affected --concurrency=3` in `.github/workflows/test.yml`), where it has taken 136-146s on Linux and 147-171s on Windows, most of it idle on frame pacing, production timers and sleeps. Most flakes come from waiting on the wrong signal and then running out of frames on a busy runner.
packages/tui runs about 170 test files in one `bun test` process. CI runs it next to up to two other suites on 4-vCPU runners (`bun turbo test --affected --concurrency=3` in `.github/workflows/check-test.yml`), where it has taken 136-146s on Linux and 147-171s on Windows, most of it idle on frame pacing, production timers and sleeps. Most flakes come from waiting on the wrong signal and then running out of frames on a busy runner.
Read the root `AGENTS.md` Testing section (no `globalThis` mocks, run from the package directory) and its TUI Stories section. To drive the real TUI, use the `opencode-dev` skill. For CLI subprocesses, service deadlines, Effect `TestClock` and turbo test tasks, use the `unit-tests` skill.

View file

@ -5,7 +5,7 @@ description: Use when writing, reviewing, speeding up, or fixing a flaky `bun te
# Fast, Reliable Unit Tests
CI runs `bun turbo test --affected --concurrency=3` on 4-vCPU Linux and Windows runners (unit job in `.github/workflows/test.yml`), so each suite shares the CPU with two others, and Windows is the slower leg. Most slow or flaky unit tests here wait on real time, spawn too many processes, or assert wall-clock speed.
CI runs `bun turbo test --affected --concurrency=3` on 4-vCPU Linux and Windows runners (unit job in `.github/workflows/check-test.yml`), so each suite shares the CPU with two others, and Windows is the slower leg. Most slow or flaky unit tests here wait on real time, spawn too many processes, or assert wall-clock speed.
Read these first; this skill does not repeat them:
@ -81,7 +81,7 @@ To avoid adding more:
- Do not write per-file `git init` plus `git config` copies. server still has two (`packages/server/test/vcs.test.ts:215-218`, `packages/server/test/worktree.test.ts:131-133`); server already imports core fixtures such as `tmpdir`.
- Use `-c user.name=… -c user.email=…` only for commits the test makes itself (`npm.test.ts:53`). Repos where production code commits later (snapshot, worktree, vcs) need repo-local identity.
- Keep identity repo-local. The unit job's "Configure git identity" step sets a global identity, but core's `script/test.ts` and cli's `isolatedEnv` replace HOME, so it is invisible there and visible to server and tui. That HOME isolation keeps core's missing-identity coverage: do not depend on CI's identity, and do not add a global gitconfig in core.
- **Independent children** start together (`Promise.all`, `packages/ai/test/exports.test.ts:63`). `packages/app/test-browser/playwright-config.test.ts` runs sequential `Bun.spawnSync` (3.5s on Windows, 1.4s on Linux); `packages/desktop/scripts/windows-installer.test.ts` makes 6 sequential cold `pwsh` starts for ACL reads, which one `pwsh` call could batch.
- **Independent children** start together (`Promise.all`, `packages/ai/test/exports.test.ts:63`). `packages/app/test-browser/playwright-config.test.ts` runs sequential `Bun.spawnSync` (3.5s on Windows, 1.4s on Linux); `packages/desktop/script/windows-installer.test.ts` makes 6 sequential cold `pwsh` starts for ACL reads, which one `pwsh` call could batch.
- **Size contention and thresholds to the claim.** `flock.test.ts:46` starts 16 bun workers; use only as many as still exceed the 4 CI vCPUs. A hard-coded threshold forces huge fixtures: `packages/core/test/git.test.ts:354` writes 2,100 files to cross `looseObjectLimit = 2048` (`packages/core/src/git.ts:50`), 2.7s locally and slower on Windows. Make the threshold an option with the production default, cross a small value in the test, and assert the default once.
## Windows-only failures
@ -114,7 +114,7 @@ To avoid adding more:
## Turbo test tasks
- `bun turbo test` runs every workspace package that has a `test` script, through the generic `test` task in `turbo.json` (`"dependsOn": ["transit"], "outputs": []`). A package with test files but no `test` script never runs in CI: give a new suite a script, and check with `bun turbo test --dry=json`. Add an `@opencode/<pkg>#test` entry only to override the generic task (desktop disables caching). Suites CI skipped rotted: client, util, sdk, http-recorder and merman needed fixes before CI could run them.
- `transit` runs nothing and depends on `^transit`, so a test hash covers the package's whole workspace closure. The global dependencies add root `package.json` (whose `packageManager` pins Bun), `bunfig.toml`, `patches/**`, `.npmrc`, `.github/actions/setup-bun/**` and `test.yml`.
- `transit` runs nothing and depends on `^transit`, so a test hash covers the package's whole workspace closure. The global dependencies add root `package.json` (whose `packageManager` pins Bun), `bunfig.toml`, `patches/**`, `.npmrc`, `.github/actions/setup-bun/**` and `check-test.yml`.
- Tests do not wait for builds: workspace packages export their sources (`"./*": "./src/*.ts"` in `packages/core/package.json`), so a test must not read a dependency's `dist`. The build job's "Build workspace libraries" step checks the library builds on Linux.
- A package that compiles `src` with tsc keeps colocated tests out of the build (`"exclude": ["src/**/*.test.ts"]` in `packages/util/tsconfig.build.json`). Otherwise `bun test` also runs the compiled copies, as Windows CI did with `packages/util/dist/retry.test.js`.
@ -123,7 +123,7 @@ To avoid adding more:
- Most suites print only failures (`--only-failures`): `(fail) <name> [5000ms]` and `^ this test timed out after 5000ms`.
- When `killed 1 dangling process` and `# Unhandled error between tests` follow (for example `NpmInstallFailedError` with `SIGTERM` from a `git clone`), the test was still doing real work, not hanging.
- The unhandled error is the abandoned Effect failing after Bun killed its child, not a second bug. Count the work (see Before you push) before choosing a fix.
- Check whether the test also fails on dev pushes: `gh run list --workflow test.yml --branch dev --event push --status failure`. In one census before core's 30s default, 4 of 25 dev pushes went red, all on Windows unit tests (3 of them Npm.add 5s timeouts).
- Check whether the test also fails on dev pushes: `gh run list --workflow check-test.yml --branch dev --event push --status failure`. In one census before core's 30s default, 4 of 25 dev pushes went red, all on Windows unit tests (3 of them Npm.add 5s timeouts).
- Read whole job logs with `gh run view --log --job <id>`; `--log-failed` omits green jobs, whose `Ran N tests across M files. [Xs]` lines you need for comparison.
- Assert a child's stderr before its exit codes. `packages/core/test/util/effect-flock.test.ts:327-328` checks codes first, so its one CI failure never showed the cause.

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="สถานะการสร้าง" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="สถานะการสร้าง" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -11,7 +11,7 @@
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/release.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/release.yml?style=flat-square&branch=dev" /></a>
</p>
<p align="center">

View file

@ -1,279 +0,0 @@
# V2 HTTP API audit checklist
**Source:** `packages/protocol/openapi.json`
**Current endpoint count:** 139
**Last regenerated:** 2026-09-13
## How to use this checklist
Review endpoints in document order. For each endpoint, select one disposition and capture rationale or follow-up work in Notes. Mark **Reviewed** only after the disposition is agreed.
### Review criteria
- Resource and operation naming
- HTTP method and idempotency
- Request parameters and location scope
- Response shape and error taxonomy
- Authentication and authorization
- Current production consumers
- Stability level: public, experimental, or internal
- Whether the generated client API is intuitive
### Disposition legend
- **Keep:** ship unchanged as a supported V2 API
- **Change:** retain after a defined contract change
- **Remove:** exclude from the official V2 API
- **Experimental-only:** retain outside the stable API commitment
## Progress
- [x] Group 1: Foundation and placement (4)
- [x] Group 2: Configuration and capability catalogs (16)
- [x] Group 3: Credentials, integrations, MCP, and web search (22)
- [x] Group 4: Session lifecycle (12)
- [x] Group 5: Session execution and inputs (11)
- [x] Group 6: Session history and recovery (13)
- [x] Group 7: Inbox, permissions, and forms (19)
- [x] Group 8: Filesystem, worktrees, and VCS (12)
- [x] Group 9: PTYs, persistent terminals, and shells (24)
- [x] Group 10: Events, RPC, and experimental operations (6)
## Resolved during audit
### [x] `POST /api/plugin/await-activation`
- **Decision:** Remove
- **Notes:** Activation timing is an internal server concern. Catalog reads remain non-blocking.
### [x] Location response wrappers
- **Decision:** Reduce generic endpoint response locations to `{ directory }`.
- **Notes:** Full project metadata remains available from `GET /api/location`; no consumers used it from wrapped responses.
### [x] `GET /api/health` and `GET /api/server`
- **Decision:** Merge and rename
- **Replacement:** `GET /api/info` with operation ID `server.info`.
- **Notes:** Returns `version`, `pid`, and connection `urls`; readiness is conveyed by HTTP status.
### [x] `GET /api/project/current`
- **Decision:** Remove
- **Replacement:** `GET /api/location`, using `project` from the response.
- **Notes:** The endpoint duplicated `Location.Info.project`; production callers were migrated.
### [x] `POST /api/workspace` and `DELETE /api/workspace/{workspaceID}`
- **Decision:** Remove
- **Notes:** Provider-backed workspaces are not part of the V2 HTTP contract and can be introduced later. Core and the embedded SDK retain internal workspace support.
## Group 1: Foundation and placement
**Endpoints:** 4
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 001–002 | `GET` | `/api/info` | `server.info` | Keep | Replaces the former health and server endpoints. |
| [x] 003 | `GET` | `/api/location` | `location.get` | Keep | Workspace selectors and response fields removed until workspace support ships. |
| [x] 004 | `GET` | `/api/project` | `project.list` | Keep | Removed unused `time.initialized`; the database column remains for migration data. |
| [x] 005 | `PATCH` | `/api/project/{projectID}` | `project.update` | Keep | Request and response accepted as-is. |
## Group 2: Configuration and capability catalogs
**Endpoints:** 16
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 008 | `GET` | `/api/agent` | `agent.list` | Keep | Request and response accepted as-is. |
| [x] 009 | `GET` | `/api/agent/{agentID}` | `agent.get` | Keep | Request, response, and not-found error accepted as-is. |
| [x] 010 | `GET` | `/api/plugin` | `plugin.list` | Keep | Request and response accepted as-is. |
| [x] 012 | `POST` | `/api/plugin/check` | `plugin.check` | Keep | Request and response accepted as-is. |
| [x] 013 | `POST` | `/api/plugin/update` | `plugin.update` | Keep | Request and errors accepted as-is. |
| [x] 014 | `GET` | `/api/model` | `model.list` | Keep | Request and response accepted as-is. |
| [x] 015 | `GET` | `/api/model/default` | `model.default` | Keep | Request and nullable response accepted as-is. |
| [x] 016 | `GET` | `/api/provider` | `provider.list` | Keep | Request and response accepted as-is. |
| [x] 017 | `GET` | `/api/provider/{providerID}` | `provider.get` | Keep | Request, response, and not-found error accepted as-is. |
| [x] 018 | `GET` | `/api/command` | `command.list` | Keep | Request and response accepted as-is. |
| [x] 019 | `GET` | `/api/skill` | `skill.list` | Keep | Renamed `location` to `path`; removed the skill-specific `slash` flag and slash-command behavior. |
| [x] 020 | `GET` | `/api/reference` | `reference.list` | Keep | Removed duplicate `description` and `hidden` fields from nested `source`. |
| [x] 021 | `GET` | `/api/config` | `config.get` | Keep | Compatibility entries removed; response now contains only documents and OpenCode directories. |
| [x] 022 | `GET` | `/api/config/preferences` | `config.preferences` | Remove | Redundant special projection of global config. |
| [x] 023 | `PATCH` | `/api/config/preferences` | `config.updatePreferences` | Remove | Redundant field-specific config mutation API. |
| [x] 024 | `GET` | `/api/config/shell` | `config.shells` | Keep | Required by the server Terminal shell setting. |
| [x] 024a | `PATCH` | `/api/experimental/config` | `experimental.config.update` | Change | Experimental global config mutation; initially accepts only `shell`. |
## Group 3: Credentials, integrations, MCP, and web search
**Endpoints:** 22
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 025 | `GET` | `/api/integration` | `integration.list` | Keep | Full integration inventory is consumed by authentication and integration-selection clients. |
| [x] 026 | `GET` | `/api/integration/{integrationID}` | `integration.get` | Change | Missing integration now returns typed `404` instead of optional data. |
| [x] 027 | `POST` | `/api/experimental/integration/wellknown` | `experimental.integration.wellknown.add` | Experimental-only | Retained outside the stable API commitment. |
| [x] 028 | `POST` | `/api/integration/{integrationID}/connect/key` | `integration.connect.key` | Change | Missing integration returns typed `404`; key form answers retained. |
| [x] 029 | `POST` | `/api/integration/{integrationID}/connect/oauth` | `integration.oauth.connect` | Keep | OAuth connection start contract retained. |
| [x] 030 | `GET` | `/api/integration/{integrationID}/connect/oauth/{attemptID}` | `integration.oauth.status` | Change | Missing integration or OAuth attempt returns typed `404`. |
| [x] 031 | `DELETE` | `/api/integration/{integrationID}/connect/oauth/{attemptID}` | `integration.oauth.cancel` | Keep | Idempotent cancellation remains a no-op for unavailable or terminal attempts. |
| [x] 032 | `POST` | `/api/integration/{integrationID}/connect/oauth/{attemptID}/complete` | `integration.oauth.complete` | Change | Missing integration or OAuth attempt returns typed `404`; code remains mode-dependent. |
| [x] 033 | `POST` | `/api/integration/{integrationID}/connect/command` | `integration.command.connect` | Change | Missing integration or command method returns typed `404`. |
| [x] 034 | `GET` | `/api/integration/{integrationID}/connect/command/{attemptID}` | `integration.command.status` | Change | Missing integration or command attempt returns typed `404`. |
| [x] 035 | `DELETE` | `/api/integration/{integrationID}/connect/command/{attemptID}` | `integration.command.cancel` | Keep | Idempotent cancellation remains a no-op for unavailable or terminal attempts. |
| [x] 036 | `GET` | `/api/mcp` | `mcp.list` | Keep | MCP inventory and connection status retained. |
| [x] 037 | `PUT` | `/api/experimental/mcp/{server}` | `experimental.mcp.add` | Experimental-only | Runtime-only MCP override; does not persist configuration. |
| [x] 038 | `DELETE` | `/api/experimental/mcp/{server}` | `experimental.mcp.remove` | Experimental-only | Runtime removal override; missing server returns `404`. |
| [x] 039 | `POST` | `/api/experimental/mcp/{server}/connect` | `experimental.mcp.connect` | Experimental-only | Runtime connection override retained outside the stable API. |
| [x] 040 | `POST` | `/api/experimental/mcp/{server}/disconnect` | `experimental.mcp.disconnect` | Experimental-only | Runtime disconnection override retained outside the stable API. |
| [x] 041 | `GET` | `/api/mcp/resource` | `mcp.resource.catalog` | Keep | Reviewed separately by coworker. |
| [x] 042 | `PATCH` | `/api/credential/{credentialID}` | `credential.update` | Change | Removed redundant location query; credentials and events are global. |
| [x] 043 | `DELETE` | `/api/credential/{credentialID}` | `credential.remove` | Change | Removed redundant location query; credentials and events are global. |
| [x] 044 | `POST` | `/api/credential/{credentialID}/activate` | `credential.activate` | Change | Removed redundant location query; credentials and events are global. |
| [x] 045 | `GET` | `/api/websearch/provider` | `websearch.providers` | Keep | Provider availability remains location-scoped; singular resource path retained. |
| [x] 046 | `POST` | `/api/websearch` | `websearch.query` | Keep | Unknown provider remains an invalid request; published time documented as Unix epoch milliseconds. |
## Group 4: Session lifecycle
**Endpoints:** 12
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 047 | `GET` | `/api/session` | `session.list` | Keep | Existing filtering, ordering, and cursor contract retained for now. |
| [x] 048 | `POST` | `/api/session` | `session.create` | Keep | Existing creation contract retained; model reference includes optional variant. |
| [x] 049 | `GET` | `/api/experimental/session/stats` | `experimental.session.stats` | Experimental-only | Session analytics retained outside the stable API commitment. |
| [x] 050 | `GET` | `/api/session/active` | `session.active` | Keep | Status record retained for future active-state expansion. |
| [x] 051 | `GET` | `/api/session/{sessionID}` | `session.get` | Keep | Specific session read and typed `404` retained. |
| [x] 052 | `DELETE` | `/api/session/{sessionID}` | `session.remove` | Keep | Session and child deletion with typed `404` retained. |
| [x] 053 | `POST` | `/api/session/{sessionID}/fork` | `session.fork` | Change | Request now accepts optional branded `before` message ID; omission copies full history. |
| [x] 054 | `POST` | `/api/session/{sessionID}/agent` | `session.switchAgent` | Keep | Subsequent-execution agent selection retained. |
| [x] 055 | `POST` | `/api/session/{sessionID}/model` | `session.switchModel` | Keep | Subsequent-execution model and optional variant selection retained. |
| [x] 056 | `PATCH` | `/api/session/{sessionID}` | `session.update` | Change | General session patch updates title and permissions; rules emit `session.permissions`. |
| [x] 057 | `POST` | `/api/session/{sessionID}/move` | `session.move` | Change | Removed inaccurate local-change transfer claim; delivery behavior retained. |
| [x] 058 | `POST` | `/api/session/{sessionID}/background` | `session.background` | Keep | Backgroundable foreground tools transition to background observation; idle requests remain no-ops. |
## Group 5: Session execution and inputs
**Endpoints:** 11
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 059 | `POST` | `/api/session/{sessionID}/prompt` | `session.prompt` | Keep | Durable admission, delivery mode, and admit-only resume control retained. |
| [x] 060 | `POST` | `/api/session/{sessionID}/command` | `session.command` | Change | Renamed request field from `command` to `name`; `204` retained. |
| [x] 061 | `POST` | `/api/experimental/session/{sessionID}/skill` | `experimental.session.skill` | Experimental-only | Skill ID is now the `id` field; standalone activation remains experimental. |
| [x] 062 | `POST` | `/api/session/{sessionID}/synthetic` | `session.synthetic` | Keep | Durable synthetic admission and delivery controls retained. |
| [x] 063 | `POST` | `/api/session/{sessionID}/shell` | `session.shell` | Change | Caller ID is now the optimistic shell message ID; server derives its event ID. |
| [x] 064 | `POST` | `/api/session/{sessionID}/compact` | `session.compact` | Keep | Durable compaction admission and delivery controls retained. |
| [x] 065 | `POST` | `/api/experimental/session/{sessionID}/wait` | `experimental.session.wait` | Experimental-only | Race-free idle barrier retained outside the stable API. |
| [x] 066 | `POST` | `/api/session/{sessionID}/generate` | `session.generate` | Keep | Transient generation from session context retained. |
| [x] 067 | `POST` | `/api/session/{sessionID}/interrupt` | `session.interrupt` | Change | Renamed `continue` to `resume` across public and internal interruption APIs. |
| [x] 068 | `PUT` | `/api/session/{sessionID}/environment` | `session.environment` | Keep | Process-local environment replacement retained in the stable API. |
| [x] 069 | `POST` | `/api/session/{sessionID}/view` | `session.view` | Change | Idle watermark now uses the standard epoch-millisecond timestamp schema. |
## Group 6: Session history and recovery
**Endpoints:** 13
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 070 | `POST` | `/api/experimental/session/import` | `experimental.session.import` | Experimental-only | Existing projected transcript import contract retained outside the stable API. |
| [x] 071 | `GET` | `/api/experimental/session/{sessionID}/export` | `experimental.session.export` | Experimental-only | Existing projected transcript export contract retained outside the stable API. |
| [x] 072 | `POST` | `/api/session/{sessionID}/revert/stage` | `session.revert.stage` | Keep | Existing staged history and optional file restoration behavior retained. |
| [x] 073 | `DELETE` | `/api/session/{sessionID}/revert` | `session.revert.clear` | Change | Clearing staged revert now deletes the session revert resource. |
| [x] 074 | `POST` | `/api/session/{sessionID}/revert/commit` | `session.revert.commit` | Keep | Explicit staged-revert commit action retained. |
| [x] 075 | `GET` | `/api/session/{sessionID}/context` | `session.context` | Keep | Active model-context projection retained. |
| [x] 076 | `GET` | `/api/session/{sessionID}/diff` | `session.diff` | Keep | Turn-range structured diff contract retained. |
| [x] 077 | `GET` | `/api/experimental/session/{sessionID}/instructions/entries` | `experimental.session.instructions.entry.list` | Experimental-only | API-managed durable context entries retained outside the stable API. |
| [x] 078 | `PUT` | `/api/experimental/session/{sessionID}/instructions/entries/{key}` | `experimental.session.instructions.entry.put` | Experimental-only | API-managed durable context entries retained outside the stable API. |
| [x] 079 | `DELETE` | `/api/experimental/session/{sessionID}/instructions/entries/{key}` | `experimental.session.instructions.entry.remove` | Experimental-only | API-managed durable context entries retained outside the stable API. |
| [x] 080 | `GET` | `/api/experimental/session/{sessionID}/log` | `session.log` | Experimental-only | Retained outside the stable API commitment. |
| [x] 081 | `GET` | `/api/session/{sessionID}/message/{messageID}` | `session.message.get` | Change | Normalized specific-message operation ID. |
| [x] 082 | `GET` | `/api/session/{sessionID}/message` | `session.message.list` | Change | Normalized session-scoped message-list operation ID. |
## Group 7: Inbox, permissions, and forms
**Endpoints:** 19
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 083 | `GET` | `/api/session/{sessionID}/inbox` | `session.inbox.list` | Change | Inbox timestamps now use the standard nested `time.created` shape. |
| [x] 084 | `DELETE` | `/api/session/{sessionID}/inbox/{inboxID}` | `session.inbox.cancel` | Change | Cancellation is idempotent and returns `204` when the session exists. |
| [x] 085 | `PATCH` | `/api/session/{sessionID}/inbox/{inboxID}` | `session.inbox.update` | Change | Consolidated delivery mutation with `delivery: "steer" | "queue"`. |
| [x] 086 | — | — | — | Remove | Replaced by `session.inbox.update`. |
| [x] 087 | `GET` | `/api/form` | `form.list` | Change | Removed redundant `request` path and operation namespace. |
| [x] 088 | `GET` | `/api/session/{sessionID}/form` | `session.form.list` | Keep | Pending session form list retained with temporary MCP sentinel compatibility. |
| [x] 089 | `POST` | `/api/session/{sessionID}/form` | `session.form.create` | Keep | External form creation and temporary MCP sentinel ownership retained. |
| [x] 090 | `GET` | `/api/session/{sessionID}/form/{formID}` | `session.form.get` | Change | Form definition and lifecycle state are now returned together. |
| [x] 091 | — | — | — | Remove | State is included by `session.form.get`. |
| [x] 092 | `POST` | `/api/session/{sessionID}/form/{formID}/reply` | `session.form.reply` | Keep | One-shot validated form reply retained. |
| [x] 093 | `DELETE` | `/api/session/{sessionID}/form/{formID}` | `session.form.cancel` | Change | Form cancellation now deletes the pending form resource. |
| [x] 094 | `GET` | `/api/permission/request` | `permission.request.list` | Keep | Pending-request namespace retained alongside saved permissions. |
| [x] 095 | `GET` | `/api/permission/saved` | `permission.saved.list` | Change | Added persisted creation and update timestamps under `time`. |
| [x] 096 | `DELETE` | `/api/permission/saved/{id}` | `permission.saved.remove` | Keep | Idempotent saved-permission deletion retained. |
| [x] 097 | `POST` | `/api/session/{sessionID}/permission` | `session.permission.create` | Keep | Non-blocking permission evaluation and pending-request creation retained. |
| [x] 098 | `GET` | `/api/session/{sessionID}/permission` | `session.permission.list` | Keep | Pending session permission list retained. |
| [x] 099 | `GET` | `/api/session/{sessionID}/permission/{requestID}` | `session.permission.get` | Keep | Specific pending permission read with ownership validation retained. |
| [x] 100 | `POST` | `/api/session/{sessionID}/permission/{requestID}/reply` | `session.permission.reply` | Change | Renamed request field from `reply` to `decision`. |
| [x] 101 | — | — | — | Remove | Permission rules are updated through `session.update`. |
## Group 8: Filesystem, worktrees, and VCS
**Endpoints:** 12
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 102 | `GET` | `/api/fs/read/*` | `fs.read` | Keep | Relative wildcard file reads and raw byte responses retained. |
| [x] 103 | `GET` | `/api/fs/list` | `fs.list` | Keep | Existing path scope and minimal entry metadata retained. |
| [x] 104 | `GET` | `/api/fs/find` | `fs.find` | Keep | Existing ranked filesystem search retained. |
| [x] 105 | `GET` | `/api/worktree` | `worktree.list` | Keep | Reviewed separately by coworker. |
| [x] 106 | `POST` | `/api/worktree` | `worktree.create` | Keep | Reviewed separately by coworker. |
| [x] 107 | `DELETE` | `/api/worktree` | `worktree.remove` | Keep | Reviewed separately by coworker. |
| [x] 108 | `POST` | `/api/worktree/refresh` | `worktree.refresh` | Keep | Reviewed separately by coworker. |
| [x] 109 | `GET` | `/api/vcs` | `vcs.get` | Change | Preserved branch nesting and added selected VCS provider ID. |
| [x] 110 | `GET` | `/api/vcs/base` | `vcs.base` | Keep | Review-base inference and nullable unavailable state retained. |
| [x] 111 | `GET` | `/api/vcs/status` | `vcs.status` | Keep | Existing working-copy status shape retained for now. |
| [x] 112 | `GET` | `/api/vcs/branch` | `vcs.branch.list` | Change | Singular collection path and normalized operation ID. |
| [x] 113 | `GET` | `/api/vcs/diff` | `vcs.diff` | Keep | Existing working, branch, and committed comparison modes retained. |
## Group 9: PTYs, persistent terminals, and shells
**Endpoints:** 24
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 114 | `GET` | `/api/pty` | `pty.list` | Keep | PTY endpoints reviewed together and retained. |
| [x] 115 | `POST` | `/api/pty` | `pty.create` | Keep | PTY endpoints reviewed together and retained. |
| [x] 116 | `GET` | `/api/pty/{ptyID}` | `pty.get` | Keep | PTY endpoints reviewed together and retained. |
| [x] 117 | `PUT` | `/api/pty/{ptyID}` | `pty.update` | Keep | PTY endpoints reviewed together and retained. |
| [x] 118 | `DELETE` | `/api/pty/{ptyID}` | `pty.remove` | Keep | PTY endpoints reviewed together and retained. |
| [x] 119 | `POST` | `/api/pty/{ptyID}/connect-token` | `pty.connect.token` | Keep | PTY endpoints reviewed together and retained. |
| [x] 120 | `GET` | `/api/pty/{ptyID}/connect` | `pty.connect` | Keep | PTY endpoints reviewed together and retained. |
| [x] 121 | `GET` | `/api/experimental/session/{sessionID}/terminal/read` | `server.experimental.persistentPty.read` | Experimental-only | Retained outside the stable API commitment. |
| [x] 122 | `GET` | `/api/experimental/session/{sessionID}/terminal` | `server.experimental.persistentPty.list` | Experimental-only | Retained outside the stable API commitment. |
| [x] 123 | `POST` | `/api/experimental/session/{sessionID}/terminal` | `server.experimental.persistentPty.create` | Experimental-only | Retained outside the stable API commitment. |
| [x] 124 | `POST` | `/api/experimental/persistent-pty/shutdown` | `server.experimental.persistentPty.shutdown` | Experimental-only | Retained outside the stable API commitment. |
| [x] 125 | `POST` | `/api/experimental/persistent-pty/handoff` | `server.experimental.persistentPty.handoff` | Experimental-only | Retained outside the stable API commitment. |
| [x] 126 | `GET` | `/api/experimental/persistent-pty/{ptyID}` | `server.experimental.persistentPty.get` | Experimental-only | Retained outside the stable API commitment. |
| [x] 127 | `PUT` | `/api/experimental/persistent-pty/{ptyID}` | `server.experimental.persistentPty.update` | Experimental-only | Retained outside the stable API commitment. |
| [x] 128 | `DELETE` | `/api/experimental/persistent-pty/{ptyID}` | `server.experimental.persistentPty.remove` | Experimental-only | Retained outside the stable API commitment. |
| [x] 129 | `GET` | `/api/experimental/persistent-pty/{ptyID}/snapshot` | `server.experimental.persistentPty.snapshot` | Experimental-only | Retained outside the stable API commitment. |
| [x] 130 | `POST` | `/api/experimental/persistent-pty/{ptyID}/connect-token` | `server.experimental.persistentPty.connectToken` | Experimental-only | Retained outside the stable API commitment. |
| [x] 131 | `GET` | `/api/experimental/persistent-pty/{ptyID}/connect` | `persistentPty.connect` | Experimental-only | Retained outside the stable API commitment. |
| [x] 132 | `GET` | `/api/shell` | `shell.list` | Change | Stable shell inventory retained; numeric timestamps documented as epoch milliseconds. |
| [x] 133 | `POST` | `/api/shell` | `shell.create` | Change | Timeout is optional and defaults to zero; caller metadata retained. |
| [x] 134 | `GET` | `/api/shell/{id}` | `shell.get` | Keep | Specific running or retained shell read retained. |
| [x] 135 | `DELETE` | `/api/shell/{id}` | `shell.remove` | Change | Shell deletion is idempotent and returns `204` when already absent. |
| [x] 136 | — | — | — | Remove | Timeout mutation remains an internal Core shell operation. |
| [x] 137 | `GET` | `/api/shell/{id}/output` | `shell.output` | Keep | Existing byte-cursor text output paging retained. |
## Group 10: Events, RPC, and experimental operations
**Endpoints:** 6
| Done | Method | Path | Operation ID | Decision | Notes |
|---|---|---|---|---|---|
| [x] 138 | `POST` | `/api/experimental/generate` | `experimental.generate.text` | Experimental-only | Stateless generation retained alongside session generation. |
| [x] 139 | `POST` | `/api/rpc/{rpcID}/{method}` | `rpc.call` | Keep | Generic typed-error plugin RPC transport retained. |
| [x] 140 | `GET` | `/api/event` | `event.subscribe` | Keep | Unified native and dynamic plugin event stream retained. |
| [x] 141 | `GET` | `/api/debug/location` | `debug.location.list` | Keep | Loaded-location debug inventory retained. |
| [x] 142 | `DELETE` | `/api/debug/location` | `debug.location.evict` | Keep | Idempotent loaded-location eviction retained. |
| [x] 143 | `GET` | `/api/experimental/migration/v1` | `experimental.migration.v1.status` | Experimental-only | Retained outside the stable API commitment. |

View file

@ -273,7 +273,6 @@
"@opencode/codemode": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/plugin-browser": "workspace:*",
"@opencode/plugin-genui": "workspace:*",
"@opencode/schema": "workspace:*",
"@opencode/util": "workspace:*",
"@parcel/watcher": "2.5.1",
@ -284,7 +283,7 @@
"drizzle-orm": "catalog:",
"effect": "catalog:",
"fuzzysort": "3.1.0",
"gitlab-ai-provider": "6.19.0",
"gitlab-ai-provider": "6.23.1",
"gray-matter": "4.0.3",
"htmlparser2": "8.0.2",
"http-proxy-agent": "7.0.2",
@ -341,7 +340,6 @@
"@opencode/schema": "workspace:*",
"@opencode/ui": "workspace:*",
"@sentry/solid": "catalog:",
"@sentry/vite-plugin": "catalog:",
"@solidjs/router": "catalog:",
"@types/bun": "catalog:",
"@types/node": "catalog:",
@ -532,8 +530,8 @@
},
"peerDependencies": {
"@opencode/theme": "workspace:*",
"@opentui/core": ">=0.6.8",
"@opentui/solid": ">=0.6.8",
"@opentui/core": "0.7.0",
"@opentui/solid": "0.7.0",
"solid-js": ">=1.9.0",
},
"optionalPeers": [
@ -558,22 +556,6 @@
"typescript": "catalog:",
},
},
"packages/plugin-genui": {
"name": "@opencode/plugin-genui",
"version": "2.0.27",
"dependencies": {
"@opencode/ai": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
"effect": "catalog:",
},
"devDependencies": {
"@tsconfig/bun": "catalog:",
"@types/bun": "catalog:",
"@typescript/native": "catalog:",
"typescript": "catalog:",
},
},
"packages/plugins/figma": {
"name": "@opencode/plugin-figma",
"version": "2.1.4",
@ -695,7 +677,6 @@
"@kobalte/core": "catalog:",
"@opencode/client": "workspace:*",
"@opencode/patchmark": "workspace:*",
"@opencode/plugin-genui": "workspace:*",
"@opencode/ui": "workspace:*",
"@opencode/util": "workspace:*",
"@pierre/diffs": "catalog:",
@ -1051,9 +1032,9 @@
},
"overrides": {
"@effect/platform-node-shared": "catalog:",
"@opentui/core": "catalog:",
"@opentui/keymap": "catalog:",
"@opentui/solid": "catalog:",
"@opentui/core": "0.7.0",
"@opentui/keymap": "0.7.0",
"@opentui/solid": "0.7.0",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"bun-types": "1.4.4",
@ -1074,9 +1055,9 @@
"@lydell/node-pty": "1.2.0-beta.12",
"@npmcli/arborist": "9.4.0",
"@octokit/rest": "22.0.0",
"@opentui/core": "0.6.8",
"@opentui/keymap": "0.6.8",
"@opentui/solid": "0.6.8",
"@opentui/core": "0.7.0",
"@opentui/keymap": "0.7.0",
"@opentui/solid": "0.7.0",
"@pierre/diffs": "1.6.1",
"@pierre/highlights": "0.2.0",
"@playwright/test": "1.60.0",
@ -2037,8 +2018,6 @@
"@opencode/plugin-figma": ["@opencode/plugin-figma@workspace:packages/plugins/figma"],
"@opencode/plugin-genui": ["@opencode/plugin-genui@workspace:packages/plugin-genui"],
"@opencode/posts": ["@opencode/posts@workspace:packages/posts"],
"@opencode/protocol": ["@opencode/protocol@workspace:packages/protocol"],
@ -2107,27 +2086,27 @@
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
"@opentui/core": ["@opentui/core@0.6.8", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.6.8", "@opentui/core-darwin-x64": "0.6.8", "@opentui/core-linux-arm64": "0.6.8", "@opentui/core-linux-arm64-musl": "0.6.8", "@opentui/core-linux-x64": "0.6.8", "@opentui/core-linux-x64-musl": "0.6.8", "@opentui/core-win32-arm64": "0.6.8", "@opentui/core-win32-x64": "0.6.8" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-wjqLwLdYGy/6qEBTtZEifuwwVzt06o0BqBF02xJ46whGEUK/gy+h25+1GK4dE9LFnHphgsqeA31f7PHBJPp91w=="],
"@opentui/core": ["@opentui/core@0.7.0", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.7.0", "@opentui/core-darwin-x64": "0.7.0", "@opentui/core-linux-arm64": "0.7.0", "@opentui/core-linux-arm64-musl": "0.7.0", "@opentui/core-linux-x64": "0.7.0", "@opentui/core-linux-x64-musl": "0.7.0", "@opentui/core-win32-arm64": "0.7.0", "@opentui/core-win32-x64": "0.7.0" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-2iWBw9oo+ZJfPbOWeTLXfDV63yTDRfclxltI4IgTa6n7OB90x5xplLMH3y9DXhnWibzTui00GbK3ZCwKfUU1SQ=="],
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.6.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kmu5Rp5qC3StrGAzLvBu6SLEXd2Qq60Yf0YCmL7BmDgYt0QUZ4M2JsSS7BFg7crpk+4Yz17N1ZeOCPumE4s83w=="],
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.7.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-meEyZVUeCIauqHLWo/IsSlKzZPTnGIEjRLigefSZbrSAcOiMryd3OcUWvSByIXpYb9UPOpW0YxKKfVwepb9u2A=="],
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.6.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-eGJcssaONQ32+xYOTRCdGGXnsMJJJLn6mHYt0W79Lck8zlMuel5dWWlCbxdM3qvX/IEHr+f56bGoojTvJjDw6w=="],
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.7.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-hZQ4OfAua5CtUv3hpZ81zhNTTLULbg0leQ/3eupjefityGP6163eS56IzymTWuiM/mVD/7Ad5bicH0I2JXhr1g=="],
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.6.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-ji2LPeEX4RU6RKC0/l70hZWmqD0AvvMvnd3WvpZUNOeaIBFseSzE0QEl3apRPUqAoYiuL7uRgwSV4eewa+xXpg=="],
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.7.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-/u+Kalzkz8NntUW5zjypgt9fnzeKohLG9YMEas7n98KvyaYScrtO4Mdj5iv/STNB3IfocJOChzYAbO6C8TmlPQ=="],
"@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.6.8", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-b+3TI8rtFBQa7T04F7XVt1I8/eL2+GX0X6x9WbDBnNmolgf1DX3ZdVPmKEP8PlxAmDYB+gek+cQAwnkwiYl5YQ=="],
"@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.7.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-BkTn+WLf9OPR4KhBnuOki+R/cgk2qwbL49eQn5fEYPeiJD4HPalGbEZDea59UjwNEJ7rqKq2yuPAXQjkDZ6y3w=="],
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.6.8", "", { "os": "linux", "cpu": "x64" }, "sha512-g8hOxXpff7hOnZNlJRKCqWJr/dwVK/EyEhNsgNK4jLS13BUoaYWXi878xLXJ5acC82qEyGlYWL/kR6ACkiD0YA=="],
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.7.0", "", { "os": "linux", "cpu": "x64" }, "sha512-OD2tGl1r27zcgCsuc+TYU5e+qhrbsRSI0YUBEb0ebQo8P6Ps2FL9LFenH9om4fddCh06G9Zd45ekJMhlDrGD3Q=="],
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.6.8", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-eVQSjO5wXYiqunz/V92WweHvVTCV+LtZOnu0z6kYjwwbAvsnTxISOFAyA9H71Sy3tsibjiu1o+E27twDyM9HlA=="],
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.7.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-HrJbcAIuayzQmWVzv+cjez37fNHL9FDoHmjwxAb4iK5GTjl89FZCxeKopyua14RA6WpP8/zUJQi8U16mm6XptA=="],
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.6.8", "", { "os": "win32", "cpu": "arm64" }, "sha512-P4llQH8kFeiknVp0kfTydKaJC95BSW4mf3fub9HMgFx49eiF3qgcctbebZN+/WaD8Pshu0wiN1KPitqDTyrIDw=="],
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.7.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8yqBoRsDbvKl2kGX0O8t5kpnVEnbzs+2qUZlJ8sbeA3Z+73WFj36G+clUIMVxpspOu78iKXlD84NIwTxjZUPKw=="],
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.6.8", "", { "os": "win32", "cpu": "x64" }, "sha512-6dZuSw883BDetY59G2QwWHJG1kwfPkL+lWhDQ3a6ICxW4/7nito3uPkMRaRDb8DiTHgx0wMt/RdiydjQmZd+lw=="],
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.7.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OfNAX7fNFHhOiiojUkIjhVOZf+IDjpbpT5G7HrxGqhlZ+n4jITrrJzACHctteWbMUYcibieJzIIoKuLdmD5I+w=="],
"@opentui/keymap": ["@opentui/keymap@0.6.8", "", { "dependencies": { "@opentui/core": "0.6.8" }, "peerDependencies": { "@opentui/react": "0.6.8", "@opentui/solid": "0.6.8", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-KGiX2EMoIcJ8jSGJ8Wp2iI1VNW3HNJEqfNayPHwda6ykE//cZmZrtczpCy+OyntZOf+6I8t3H717qo+NJZx7Wg=="],
"@opentui/keymap": ["@opentui/keymap@0.7.0", "", { "dependencies": { "@opentui/core": "0.7.0" }, "peerDependencies": { "@opentui/react": "0.7.0", "@opentui/solid": "0.7.0", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-2IqUnLP+SCZR7+LXRL/7/DGFyaAR6r9y16H5oQVdRTfbACxAjszOaq2iZDEzHp1HVtamQRqEfteuaLEDwmO3kg=="],
"@opentui/solid": ["@opentui/solid@0.6.8", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.6.8", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-GwLhMdGSRBX1Tlh/aUcbpDwIG/FI15y5xL2yMlNIO27q5yRTiZHeg6yvXv3HgM55ykRm9F8YBhiFcuc5M609FA=="],
"@opentui/solid": ["@opentui/solid@0.7.0", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.7.0", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-S6SNZGRykV02UjNbM+f/6lSeAPN3dfEbjcK1jAAdFCfa+EVhJqcJVyaJgtwHLU9fI6c/O1VKXPzbbFYj2RhNVQ=="],
"@opentunnel/client": ["@opentunnel/client@0.6.1", "", { "dependencies": { "@opentunnel/protocol": "0.6.1" }, "peerDependencies": { "effect": "^4.0.0", "undici": ">=7.0.0" }, "optionalPeers": ["undici"] }, "sha512-OuVNlWywQebIXCtkixjVHebOsR3KFRxJ0DSZry6Dzj4hHaHIf3eTVmQ7VwLCjuVmw+ctU2qHIP6RxuAPr07WDw=="],
@ -3603,7 +3582,7 @@
"github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="],
"gitlab-ai-provider": ["gitlab-ai-provider@6.19.0", "", { "dependencies": { "@anthropic-ai/sdk": "^0.71.0", "@anycable/core": "^0.9.2", "graphql-request": "^6.1.0", "isomorphic-ws": "^5.0.0", "openai": "^6.16.0", "socket.io-client": "^4.8.1", "vscode-jsonrpc": "^8.2.1", "zod": "^3.25.76" }, "peerDependencies": { "@ai-sdk/provider": ">=3.0.0", "@ai-sdk/provider-utils": ">=4.0.0" } }, "sha512-ym+p6PxKvCKfBE3VKYTiacJwsmgq/DrOuGctpBnbIBekdnZT31RM6yTTNdzVS83K3+Ym4M+qNY34HEcTVM6EEQ=="],
"gitlab-ai-provider": ["gitlab-ai-provider@6.23.1", "", { "dependencies": { "@anthropic-ai/sdk": "^0.71.0", "@anycable/core": "^0.9.2", "graphql-request": "^6.1.0", "isomorphic-ws": "^5.0.0", "openai": "^6.16.0", "proper-lockfile": "^4.1.2", "socket.io-client": "^4.8.1", "vscode-jsonrpc": "^8.2.1", "zod": "^3.25.76" }, "peerDependencies": { "@ai-sdk/provider": ">=3.0.0", "@ai-sdk/provider-utils": ">=4.0.0" } }, "sha512-qzmsGAcIdlTj8B/eZvqYmwy6CzIXw3Q6zoNEUEG+PErDFFklyFf4I2o7Hbp3lhSm6kOBoQLL9qbZrE96QhnG2Q=="],
"glob": ["glob@13.0.5", "", { "dependencies": { "minimatch": "^10.2.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-BzXxZg24Ibra1pbQ/zE7Kys4Ua1ks7Bn6pKLkVPZ9FZe4JQS6/Q7ef3LG1H+k7lUf5l4T3PLSyYyYJVYUvfgTw=="],

10
install
View file

@ -311,7 +311,15 @@ download_and_install() {
if [[ "$os" == "windows" ]] || ! [ -t 2 ] || ! download_with_progress "$url" "$tmp_dir/$filename"; then
# Fallback to standard curl on Windows, non-TTY environments, or if custom progress fails
curl -f -# -L -o "$tmp_dir/$filename" "$url"
local ret=0
curl -f -# -L -o "$tmp_dir/$filename" "$url" || ret=$?
# curl exits 23 when it cannot write the file, usually because the temporary directory is full.
if [ "$ret" -eq 23 ]; then
print_message error "Could not write the download to $tmp_dir. Make sure it has enough free space, or set TMPDIR to another directory, then try again." >&2
fi
if [ "$ret" -ne 0 ]; then
exit "$ret"
fi
fi
tar -xzf "$tmp_dir/$filename" -C "$tmp_dir"

View file

@ -96,7 +96,7 @@ stdenv.mkDerivation (finalAttrs: {
cd packages/desktop
export OPENCODE_CLI_DIST="$TMPDIR/desktop-cli"
cli_package=$(bun -e 'import { getCurrentCli } from "./scripts/utils.ts"; console.log(getCurrentCli().package.replace("@opencode/", ""))')
cli_package=$(bun -e 'import { getCurrentCli } from "./script/utils.ts"; console.log(getCurrentCli().package.replace("@opencode/", ""))')
# copyBuiltCliToResources joins this dist with the npm package name getCurrentCli()
# reports, not the Nix build's name. It reads only .version from the manifest and
# writes it as opencode-cli.version beside the binary.

View file

@ -28,6 +28,7 @@
"check": "bun run lint && bun run typecheck",
"typecheck:profile": "bun script/profile-typecheck.ts",
"typecheck:profile:packages": "bun script/profile-typecheck-packages.ts",
"pack": "bun run script/pack.ts",
"upgrade-opentui": "bun run script/upgrade-opentui.ts",
"postinstall": "bun run --cwd packages/core fix-node-pty",
"prepare": "husky",
@ -54,9 +55,9 @@
"@octokit/rest": "22.0.0",
"@hono/standard-validator": "0.2.0",
"@hono/zod-validator": "0.4.2",
"@opentui/core": "0.6.8",
"@opentui/keymap": "0.6.8",
"@opentui/solid": "0.6.8",
"@opentui/core": "0.7.0",
"@opentui/keymap": "0.7.0",
"@opentui/solid": "0.7.0",
"@tanstack/solid-virtual": "3.13.37",
"@standard-schema/spec": "1.1.0",
"ulid": "3.0.1",
@ -156,9 +157,9 @@
"electron"
],
"overrides": {
"@opentui/core": "catalog:",
"@opentui/keymap": "catalog:",
"@opentui/solid": "catalog:",
"@opentui/core": "0.7.0",
"@opentui/keymap": "0.7.0",
"@opentui/solid": "0.7.0",
"@effect/platform-node-shared": "catalog:",
"@types/bun": "catalog:",
"@types/node": "catalog:",

View file

@ -1,6 +1,6 @@
# @opencode/ai
Schema-first APIs for text, images, video, speech, and transcription, built with Effect.
Schema-first APIs for text, images, video, speech, transcription, and decisions, built with Effect.
`@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed:
@ -50,6 +50,26 @@ Run `LLM.stream(...)` instead of `generate` when you want incremental `LLMEvent`
`LLM.request(...)`. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
### Raw provider events
Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
before the events parsed from that frame. `data` is the parsed JSON frame, so frames this package doesn't handle yet
are visible too. Raw events are off by default, and `generate` ignores them. Translate a frame with a stream map:
```ts
import { Stream } from "effect"
import { LLM, LLMEvent } from "@opencode/ai/effect"
const flagged = (data: unknown) =>
typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
const events = LLM.stream({ model, prompt: "Say hello.", includeRaw: true }).pipe(
Stream.map((event) =>
event.type === "raw" && flagged(event.data) ? LLMEvent.providerError({ message: "Flagged by moderation" }) : event,
),
)
```
### Google Interactions
`Google.configure({ apiKey }).interactions(modelID)` selects the Interactions API; `.model(modelID)` still selects
@ -62,13 +82,11 @@ live under `providerMetadata.vertex`. The default is still full-history replay w
```ts
const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
const response =
yield *
LLM.generate({
model,
prompt: "Say hello.",
providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
})
const response = yield* LLM.generate({
model,
prompt: "Say hello.",
providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
})
```
Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
@ -93,7 +111,8 @@ const image = Effect.gen(function* () {
const response = yield* Image.generate({
model: openai.image("gpt-image-2"),
prompt: "A robot tending a rooftop garden",
size: "1024x1024",
aspect: "1:1",
resolution: "1K",
providerOptions: { quality: "high" }, // typed per image model
})
yield* Media.write(response.image, "./garden.png")
@ -222,6 +241,38 @@ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
### Extraction (experimental)
Extraction models read typed values out of text instead of answering questions with probabilities. A field of type
`text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to
match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today, so it lives under
`@opencode/ai/experimental`.
```ts
import { ai } from "@opencode/ai"
import { Extraction } from "@opencode/ai/experimental"
import { CloudflareWorkersAI } from "@opencode/ai/providers"
const response = await ai.run(
Extraction.generate({
model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"),
input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.",
fields: {
invoiceNumber: { type: "text" },
dueDate: { type: "date", instructions: "Issue date plus the net payment days" },
total: { type: "number", decimals: 2, unit: "USD" },
contacts: { type: "list", items: "text" },
},
}),
)
response.answers.total.value // 1080, or null when the input does not say
```
Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and
forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to
Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AIClient.layer`). Images are not supported
yet.
## Alibaba Cloud Model Studio
`Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
@ -297,10 +348,11 @@ is unit-tested for all six regions.
### Images
`alibaba.image(...)` uses the native multimodal generation API (`/api/v1/services/aigc/multimodal-generation/generation`)
for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `size` lowers to
`W*H`, and `images` are sent as URLs or data URLs for editing. Native `parameters` include `negativePrompt`,
`promptExtend`, `watermark`, `thinkingMode`, and `enableSequential`; raw keys such as `bbox_list` or `size: "2K"`
pass through. Results are URLs that Model Studio keeps for 24 hours. A complete `baseURL` for images includes `/api/v1`.
for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `aspect` and
`resolution` lower to a `W*H` size, `providerOptions.size` sets it exactly, and `images` are sent as URLs or data URLs
for editing. Native `parameters` include `size`, `seed`, `negativePrompt`, `promptExtend`, `watermark`, `thinkingMode`,
and `enableSequential`; raw keys such as `bbox_list` pass through. Results are URLs that Model Studio keeps for 24
hours. A complete `baseURL` for images includes `/api/v1`.
## Z.AI
@ -1070,8 +1122,10 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
- **`Video.request` / `generate` / `stream` / `start` / `resume`** — queued video generation through a provider-neutral request; `VideoClient` is its Effect service and layer.
- **`Speech.request` / `Speech.generate` / `Speech.stream`** — text-to-speech through a provider-neutral request; `SpeechClient` is its Effect service and layer.
- **`Transcription.request` / `generate` / `stream` / `start` / `resume`** — speech-to-text over inline, streaming, and queued routes; `TranscriptionClient` is its Effect service and layer.
- **`Decision.request` / `Decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
- **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
- **`@opencode/ai`** (Promise root) — `AI.make({ layer? })` and a default `ai` client exposing `llm`, `image`, `video`, `speech`, and `transcription` as Promise / `AsyncIterable` APIs, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets.
- **`@opencode/ai`** (Promise root) — `AI.make({ layer? })` and a default `ai` client exposing `llm`, `image`, `video`, `speech`, `transcription`, and `decision` as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets.
- **`@opencode/ai/experimental`** — APIs that may still change: `Extraction` (typed values read out of text) and `Realtime` (`Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or a short-lived WebSocket URL and token).
## Testing
@ -1290,13 +1344,33 @@ cache: {
tools?: boolean,
system?: boolean,
messages?: "latest-user-message" | "latest-assistant" | { tail: number },
ttlSeconds?: number, // ≥ 3600 → 1h on Anthropic/Bedrock; else 5m
ttl?: CacheTTL, // "5m", "30m", "1h", "12h", "24h", ...
}
```
An object with placement fields places exactly those breakpoints. An object with only `ttl` keeps automatic placement.
### Cache lifetime
`ttl` is a duration in models.dev's format (`<number>` followed by `ms`, `s`, `m`, `h` or `d`). It is sent to the provider as given, so use one the provider accepts. Leaving it unset keeps the provider default.
```ts
LLM.request({ model, system, prompt, cache: { ttl: "1h" } })
```
| Protocol | How `ttl` is sent |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Anthropic Messages family, Meta Messages | `ttl` on every `cache_control` marker |
| Bedrock Converse | `ttl` on every `cachePoint`; older Claude releases that only cache for 5m drop `"1h"` |
| OpenRouter, DigitalOcean, Alibaba Chat markers | `ttl` on every `cache_control` marker |
| OpenAI Responses (OpenAI, Azure, Cloudflare AI Gateway) | `"24h"` → `prompt_cache_retention: "24h"`; anything else → `prompt_cache_options: { ttl }` |
| Chat Completions without markers (OpenAI-compatible, Moonshot, DeepInfra) | same mapping as OpenAI Responses |
OpenAI's two fields cover different models: `prompt_cache_retention` (`"in_memory"` or `"24h"`) is the only control before GPT-5.6, and GPT-5.6+ reads `prompt_cache_options.ttl` (`"30m"` or `"12h"`). Sending `prompt_cache_options` to an older model returns a 400. `"in_memory"` is not a duration; send it with an HTTP body overlay.
### Manual hints
Inline `CacheHint` on any text / system / tool / tool-result part overrides automatic placement. The auto policy preserves manual hints, counts them against Anthropic and Bedrock's four-breakpoint limit, and only fills the remaining slots.
Inline `CacheHint` (`{ type: "ephemeral", ttl? }`) on any text / system / tool / tool-result part overrides automatic placement. The auto policy preserves manual hints, counts them against Anthropic and Bedrock's four-breakpoint limit, and only fills the remaining slots.
```ts
LLM.request({
@ -1329,12 +1403,12 @@ import { OpenAI, CloudflareAIGateway } from "@opencode/ai/providers"
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).responses("gpt-4o-mini")
const gateway = CloudflareAIGateway.configure({
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
accountId,
gatewayApiKey: process.env.CLOUDFLARE_API_TOKEN,
}).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
```
Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock, Azure OpenAI, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, Fireworks, Groq, Mistral, OpenRouter, TogetherAI, Vercel AI Gateway, and xAI. Z.ai currently exposes image generation. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock (Converse and Mantle), Azure OpenAI, Alibaba, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, DigitalOcean, Fireworks, Groq, Meta, MiniMax, Mistral, Moonshot, OpenRouter, TogetherAI, Venice, Vercel AI Gateway, xAI, Z.ai, and Z.ai Coding Plan. TypeSafe AI and OpenCode expose decision models only. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
@ -1444,5 +1518,5 @@ This package is built on Effect. Public methods in `@opencode/ai/effect` return
## See also
- `AGENTS.md` — architecture, route construction, contributor guide
- `example/tutorial.ts` — runnable end-to-end walkthrough
- `example/tutorial.ts` — runnable end-to-end walkthrough (`bun example/tutorial.ts <example>`)
- `test/provider/*.test.ts` — fixture-first protocol tests; `*.recorded.test.ts` files cover live cassettes

View file

@ -1,7 +1,8 @@
import { Config, Effect, Formatter, Schema, Stream } from "effect"
import { HttpClientResponse } from "effect/http"
import { NodeFileSystem } from "@effect/platform-node"
import { AIClient, Image, LLM, LLMRequest, Media, Message, ProviderID, Tool, ToolRuntime } from "@opencode/ai/effect"
import { Route, Auth, Endpoint, Framing, Protocol } from "@opencode/ai/route"
import { Route, Auth, Endpoint, Framing, Protocol, RequestExecutor } from "@opencode/ai/route"
import { OpenAI } from "@opencode/ai/providers"
/**
@ -9,7 +10,10 @@ import { OpenAI } from "@opencode/ai/providers"
*
* Run from `packages/ai` with an OpenAI key in the environment:
*
* OPENAI_API_KEY=... bun example/tutorial.ts
* OPENAI_API_KEY=... bun example/tutorial.ts [example]
*
* where `example` is one of the keys of `examples` at the bottom (default
* `tools`). The `fake` example runs offline and needs no key.
*
* The file is intentionally written as a normal TypeScript program. You can
* hover imports and local values to see how the public API is typed.
@ -188,7 +192,7 @@ const FakeProtocol = Protocol.make<FakeBody, string, string, void>({
event: Schema.String,
initial: () => undefined,
step: (_, frame) => Effect.succeed([undefined, [{ type: "text-delta", id: "text-0", text: frame }]] as const),
onHalt: () => [{ type: "finish", reason: { normalized: "stop" } }],
onHalt: () => Effect.succeed([{ type: "finish", reason: { normalized: "stop" } }]),
},
})
@ -213,6 +217,24 @@ const FakeEcho = {
}),
}
// 7. Run the fake provider offline. `RequestExecutor.middleware` sees every HTTP
// request before it is sent; here it answers with two SSE frames instead of
// calling the network.
const fakeExecutor = RequestExecutor.middleware((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
new Response("data: hello\n\ndata: from fake-echo\n\n", { headers: { "content-type": "text/event-stream" } }),
),
),
)
const generateFake = Effect.gen(function* () {
const response = yield* LLM.generate({ model: FakeEcho.configure().model("echo-1"), prompt: "Say hello." })
console.log("\n== fake provider ==")
console.log("generated text:", response.text)
})
// 8. Image generation uses the same facade and the same request/generate shape.
// `response.image` is a `Media.Asset`: bytes decode lazily and are cached, and
// `Media.write` persists them through the Effect `FileSystem`.
@ -220,9 +242,9 @@ const generateImage = Effect.gen(function* () {
const response = yield* Image.generate({
model: openai.image("gpt-image-1-mini"),
prompt: "A flat black circle centered on a plain white background.",
size: "1024x1024",
format: "jpeg",
providerOptions: { quality: "low" },
aspect: "1:1",
// Exact pixel sizes and output formats are provider options.
providerOptions: { quality: "low", outputFormat: "jpeg" },
})
console.log("\n== image ==")
@ -233,17 +255,25 @@ const generateImage = Effect.gen(function* () {
})
// Provide every modality client and the HTTP request executor once with
// `AIClient.layer` (`AIClient.layerWith(executor)` swaps the executor). Keep one
// path enabled at a time so the tutorial can demonstrate generate, stream, or
// tool-loop behavior without spending tokens on every example.
// `AIClient.layer`; `AIClient.layerWith(executor)` swaps the executor, as the
// fake example does. One example runs at a time so the tutorial does not spend
// tokens on every path.
const examples: Record<string, Effect.Effect<void, unknown, AIClient.Services>> = {
generate: generateOnce,
stream: streamText,
tools: streamWithTools,
object: generateStructuredObject,
"dynamic-object": generateDynamicObject.pipe(
Effect.andThen((response) => Effect.sync(() => console.log(response.object))),
),
image: generateImage,
fake: generateFake,
}
const program = Effect.gen(function* () {
// yield* generateOnce
// yield* streamText
// yield* generateStructuredObject
// yield* generateDynamicObject.pipe(Effect.andThen((response) => Effect.sync(() => console.log(response.object))))
// yield* generateImage
yield* streamWithTools
}).pipe(Effect.provide(AIClient.layer))
const name = process.argv[2] ?? "tools"
if (!Object.hasOwn(examples, name))
throw new Error(`Unknown example ${name}; pick one of ${Object.keys(examples).join(", ")}`)
Effect.runPromise(program)
Effect.runPromise(
examples[name].pipe(Effect.provide(name === "fake" ? AIClient.layerWith(fakeExecutor) : AIClient.layer)),
)

View file

@ -9,7 +9,8 @@
"test": "bun test --timeout 30000 --only-failures",
"typecheck": "bun check --no-script && bun check --no-script -p tsconfig.types.json",
"typecheck:tsc": "tsc --noEmit && tsc --noEmit -p tsconfig.types.json",
"build": "tsc -p tsconfig.build.json"
"build": "tsc -p tsconfig.build.json",
"pack": "bun run script/pack.ts"
},
"files": [
"dist"
@ -18,7 +19,131 @@
".": "./src/index.ts",
"./effect": "./src/effect.ts",
"./testing": "./src/testing.ts",
"./*": "./src/*.ts"
"./experimental": "./src/experimental.ts",
"./route": "./src/route.ts",
"./providers": "./src/providers.ts",
"./providers/alibaba": "./src/providers/alibaba.ts",
"./providers/alibaba/chat": "./src/providers/alibaba/chat.ts",
"./providers/alibaba/images": "./src/providers/alibaba/images.ts",
"./providers/alibaba/messages": "./src/providers/alibaba/messages.ts",
"./providers/alibaba/responses": "./src/providers/alibaba/responses.ts",
"./providers/amazon-bedrock": "./src/providers/amazon-bedrock.ts",
"./providers/amazon-bedrock-mantle": "./src/providers/amazon-bedrock-mantle.ts",
"./providers/amazon-bedrock/mantle": "./src/providers/amazon-bedrock/mantle.ts",
"./providers/amazon-bedrock/mantle/chat": "./src/providers/amazon-bedrock/mantle/chat.ts",
"./providers/amazon-bedrock/mantle/messages": "./src/providers/amazon-bedrock/mantle/messages.ts",
"./providers/amazon-bedrock/mantle/responses": "./src/providers/amazon-bedrock/mantle/responses.ts",
"./providers/anthropic": "./src/providers/anthropic.ts",
"./providers/anthropic-compatible": "./src/providers/anthropic-compatible.ts",
"./providers/assemblyai": "./src/providers/assemblyai.ts",
"./providers/azure": "./src/providers/azure.ts",
"./providers/azure/chat": "./src/providers/azure/chat.ts",
"./providers/azure/images": "./src/providers/azure/images.ts",
"./providers/azure/responses": "./src/providers/azure/responses.ts",
"./providers/baseten": "./src/providers/baseten.ts",
"./providers/baseten/decisions": "./src/providers/baseten/decisions.ts",
"./providers/black-forest-labs": "./src/providers/black-forest-labs.ts",
"./providers/cartesia": "./src/providers/cartesia.ts",
"./providers/cerebras": "./src/providers/cerebras.ts",
"./providers/cloudflare-ai-gateway": "./src/providers/cloudflare-ai-gateway.ts",
"./providers/cloudflare-ai-gateway/decisions": "./src/providers/cloudflare-ai-gateway/decisions.ts",
"./providers/cloudflare-workers-ai": "./src/providers/cloudflare-workers-ai.ts",
"./providers/cloudflare-workers-ai/decisions": "./src/providers/cloudflare-workers-ai/decisions.ts",
"./providers/cloudflare-workers-ai/images": "./src/providers/cloudflare-workers-ai/images.ts",
"./providers/cohere": "./src/providers/cohere.ts",
"./providers/cohere/chat": "./src/providers/cohere/chat.ts",
"./providers/deepgram": "./src/providers/deepgram.ts",
"./providers/deepinfra": "./src/providers/deepinfra.ts",
"./providers/deepseek": "./src/providers/deepseek.ts",
"./providers/digitalocean": "./src/providers/digitalocean.ts",
"./providers/digitalocean/decisions": "./src/providers/digitalocean/decisions.ts",
"./providers/digitalocean/images": "./src/providers/digitalocean/images.ts",
"./providers/elevenlabs": "./src/providers/elevenlabs.ts",
"./providers/fal": "./src/providers/fal.ts",
"./providers/fireworks": "./src/providers/fireworks.ts",
"./providers/google": "./src/providers/google.ts",
"./providers/google-vertex": "./src/providers/google-vertex.ts",
"./providers/google-vertex-chat": "./src/providers/google-vertex-chat.ts",
"./providers/google-vertex-interactions": "./src/providers/google-vertex-interactions.ts",
"./providers/google-vertex-messages": "./src/providers/google-vertex-messages.ts",
"./providers/google-vertex-mistral": "./src/providers/google-vertex-mistral.ts",
"./providers/google-vertex-responses": "./src/providers/google-vertex-responses.ts",
"./providers/google-vertex/chat": "./src/providers/google-vertex/chat.ts",
"./providers/google-vertex/gemini": "./src/providers/google-vertex/gemini.ts",
"./providers/google-vertex/images": "./src/providers/google-vertex/images.ts",
"./providers/google-vertex/interactions": "./src/providers/google-vertex/interactions.ts",
"./providers/google-vertex/messages": "./src/providers/google-vertex/messages.ts",
"./providers/google-vertex/mistral": "./src/providers/google-vertex/mistral.ts",
"./providers/google-vertex/responses": "./src/providers/google-vertex/responses.ts",
"./providers/google/images": "./src/providers/google/images.ts",
"./providers/google/interactions": "./src/providers/google/interactions.ts",
"./providers/groq": "./src/providers/groq.ts",
"./providers/meta": "./src/providers/meta.ts",
"./providers/meta/chat": "./src/providers/meta/chat.ts",
"./providers/meta/messages": "./src/providers/meta/messages.ts",
"./providers/meta/responses": "./src/providers/meta/responses.ts",
"./providers/minimax": "./src/providers/minimax.ts",
"./providers/minimax/chat": "./src/providers/minimax/chat.ts",
"./providers/minimax/messages": "./src/providers/minimax/messages.ts",
"./providers/minimax/responses": "./src/providers/minimax/responses.ts",
"./providers/mistral": "./src/providers/mistral.ts",
"./providers/moonshot": "./src/providers/moonshot.ts",
"./providers/moonshot/chat": "./src/providers/moonshot/chat.ts",
"./providers/moonshot/messages": "./src/providers/moonshot/messages.ts",
"./providers/moonshot/responses": "./src/providers/moonshot/responses.ts",
"./providers/openai": "./src/providers/openai.ts",
"./providers/openai-compatible": "./src/providers/openai-compatible.ts",
"./providers/openai-compatible-responses": "./src/providers/openai-compatible-responses.ts",
"./providers/openai-compatible/images": "./src/providers/openai-compatible/images.ts",
"./providers/openai-compatible/responses": "./src/providers/openai-compatible/responses.ts",
"./providers/openai/chat": "./src/providers/openai/chat.ts",
"./providers/openai/images": "./src/providers/openai/images.ts",
"./providers/openai/responses": "./src/providers/openai/responses.ts",
"./providers/opencode": "./src/providers/opencode.ts",
"./providers/opencode/decisions": "./src/providers/opencode/decisions.ts",
"./providers/openrouter": "./src/providers/openrouter.ts",
"./providers/openrouter/decisions": "./src/providers/openrouter/decisions.ts",
"./providers/openrouter/images": "./src/providers/openrouter/images.ts",
"./providers/replicate": "./src/providers/replicate.ts",
"./providers/runway": "./src/providers/runway.ts",
"./providers/stability": "./src/providers/stability.ts",
"./providers/togetherai": "./src/providers/togetherai.ts",
"./providers/typesafe-ai": "./src/providers/typesafe-ai.ts",
"./providers/typesafe-ai/decisions": "./src/providers/typesafe-ai/decisions.ts",
"./providers/venice": "./src/providers/venice.ts",
"./providers/vercel-ai-gateway": "./src/providers/vercel-ai-gateway.ts",
"./providers/vercel-ai-gateway/chat": "./src/providers/vercel-ai-gateway/chat.ts",
"./providers/vercel-ai-gateway/decisions": "./src/providers/vercel-ai-gateway/decisions.ts",
"./providers/vercel-ai-gateway/images": "./src/providers/vercel-ai-gateway/images.ts",
"./providers/vercel-ai-gateway/messages": "./src/providers/vercel-ai-gateway/messages.ts",
"./providers/vercel-ai-gateway/responses": "./src/providers/vercel-ai-gateway/responses.ts",
"./providers/xai": "./src/providers/xai.ts",
"./providers/xai/images": "./src/providers/xai/images.ts",
"./providers/zai": "./src/providers/zai.ts",
"./providers/zai-coding-plan": "./src/providers/zai-coding-plan.ts",
"./providers/zai-coding-plan/chat": "./src/providers/zai-coding-plan/chat.ts",
"./providers/zai-coding-plan/messages": "./src/providers/zai-coding-plan/messages.ts",
"./providers/zai-coding-plan/responses": "./src/providers/zai-coding-plan/responses.ts",
"./providers/zai/chat": "./src/providers/zai/chat.ts",
"./providers/zai/images": "./src/providers/zai/images.ts",
"./protocols": "./src/protocols.ts",
"./protocols/alibaba-images": "./src/protocols/alibaba-images.ts",
"./protocols/cloudflare-run-decisions": "./src/protocols/cloudflare-run-decisions.ts",
"./protocols/cloudflare-workers-ai-images": "./src/protocols/cloudflare-workers-ai-images.ts",
"./protocols/deepgram-transcription": "./src/protocols/deepgram-transcription.ts",
"./protocols/google-images": "./src/protocols/google-images.ts",
"./protocols/google-speech": "./src/protocols/google-speech.ts",
"./protocols/google-transcription": "./src/protocols/google-transcription.ts",
"./protocols/openai-chat": "./src/protocols/openai-chat.ts",
"./protocols/openai-decisions": "./src/protocols/openai-decisions.ts",
"./protocols/openai-images": "./src/protocols/openai-images.ts",
"./protocols/openai-responses": "./src/protocols/openai-responses.ts",
"./protocols/openai-speech": "./src/protocols/openai-speech.ts",
"./protocols/openai-transcription": "./src/protocols/openai-transcription.ts",
"./protocols/system-one": "./src/protocols/system-one.ts",
"./protocols/xai-images": "./src/protocols/xai-images.ts",
"./protocols/xai-video": "./src/protocols/xai-video.ts",
"./protocols/zai-images": "./src/protocols/zai-images.ts"
},
"devDependencies": {
"@clack/prompts": "1.0.0-alpha.1",
@ -37,5 +162,10 @@
"aws4fetch": "1.0.20",
"effect": "catalog:",
"google-auth-library": "10.5.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/anomalyco/opencode.git",
"directory": "packages/ai"
}
}

View file

@ -0,0 +1,5 @@
#!/usr/bin/env bun
import path from "node:path"
import { pack } from "@opencode/script/pack"
await pack(path.resolve(import.meta.dir, ".."))

View file

@ -1,38 +0,0 @@
#!/usr/bin/env bun
import { Script } from "@opencode/script"
import { $ } from "bun"
import { fileURLToPath } from "url"
const dir = fileURLToPath(new URL("..", import.meta.url))
process.chdir(dir)
async function published(name: string, version: string) {
return (await $`npm view ${name}@${version} version`.nothrow()).exitCode === 0
}
await $`bun run build`
const originalText = await Bun.file("package.json").text()
const pkg = JSON.parse(originalText) as {
name: string
version: string
exports: Record<string, string>
}
if (await published(pkg.name, pkg.version)) {
console.log(`already published ${pkg.name}@${pkg.version}`)
} else {
for (const [key, value] of Object.entries(pkg.exports)) {
const file = value.replace("./src/", "./dist/").replace(".ts", "")
// @ts-ignore
pkg.exports[key] = {
import: file + ".js",
types: file + ".d.ts",
}
}
await Bun.write("package.json", JSON.stringify(pkg, null, 2))
try {
await $`bun pm pack`
await $`npm publish *.tgz --tag ${Script.channel} --access public`
} finally {
await Bun.write("package.json", originalText)
}
}

View file

@ -10,7 +10,7 @@
//
// Manual `cache: CacheHint` placements on individual parts are preserved and
// count against the four-breakpoint budget; auto only fills remaining slots.
import { CacheHint, type CachePolicy, type CachePolicyObject } from "./schema/options.js"
import { CacheHint, type CachePolicy, type CachePolicyObject, type CacheTTL } from "./schema/options.js"
import { LLMRequest, Message, ToolDefinition, type ContentPart, type ToolEntry } from "./schema/messages.js"
import { effortUpdate } from "./effort-updates.js"
@ -27,13 +27,25 @@ const BREAKPOINT_CAP = 4
// - undefined → "auto" — caching is on by default.
// - "auto" → tools + first/last system + final message boundary.
// - "none" → no auto placement; manual `CacheHint`s still flow.
// - `{ ttl }` → "auto" with that lifetime.
// - object form → exactly what the caller asked for.
const resolve = (policy: CachePolicy | undefined): CachePolicyObject => {
if (policy === undefined || policy === "auto") return AUTO
if (policy === "none") return NONE
return policy
if (typeof policy === "object" && !isAuto(policy)) return policy
return AUTO
}
const isAuto = (policy: CachePolicy | undefined) =>
policy === undefined ||
policy === "auto" ||
(typeof policy === "object" &&
policy.tools === undefined &&
policy.system === undefined &&
policy.messages === undefined)
/** The requested cache lifetime, for routes that send it as a request-level option instead of on markers. */
export const requestTTL = (request: LLMRequest) => (typeof request.cache === "object" ? request.cache.ttl : undefined)
// Protocols whose wire format ignores inline cache markers (OpenAI's implicit
// prefix caching, Gemini's implicit + out-of-band CachedContent). Skip the
// whole policy pass for these — emitting hints would be harmless but pointless.
@ -67,8 +79,8 @@ const gatewayPolicy = (modelID: string): CachePolicyObject => {
return NONE
}
const makeHint = (ttlSeconds: number | undefined): CacheHint =>
ttlSeconds !== undefined ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" })
const makeHint = (ttl: CacheTTL | undefined): CacheHint =>
ttl !== undefined ? new CacheHint({ type: "ephemeral", ttl }) : new CacheHint({ type: "ephemeral" })
interface Budget {
remaining: number
@ -179,7 +191,7 @@ export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
const policy = selectPolicy(request)
if (!policy.tools && !policy.system && !policy.messages) return request
const hint = makeHint(policy.ttlSeconds)
const hint = makeHint(requestTTL(request))
const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countHints(request)) }
const tools = policy.tools ? markLastTool(request.tools, hint, budget) : request.tools
const system = policy.system ? markSystemBoundaries(request.system, hint, budget) : request.system
@ -189,11 +201,17 @@ export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
return LLMRequest.update(request, { tools, system, messages })
}
/** Whether the cache policy places inline markers, which then carry the requested lifetime. */
export const placesMarkers = (request: LLMRequest) => {
const policy = selectPolicy(request)
return Boolean(policy.tools || policy.system || policy.messages)
}
// A declared cache format overrides the route allowlist and its model-ID heuristics.
const selectPolicy = (request: LLMRequest): CachePolicyObject => {
const format = request.model.compatibility?.cacheFormat
const route = request.model.route.id
const auto = request.cache === undefined || request.cache === "auto"
const auto = isAuto(request.cache)
if (format === "alibaba") return auto ? QWEN : { ...resolve(request.cache), tools: false }
if (format === "anthropic") return resolve(request.cache)
if (!RESPECTS_INLINE_HINTS.has(route)) return NONE

View file

@ -155,10 +155,11 @@ export interface DecisionModelRoute<Options extends DecisionOptions = DecisionOp
export class DecisionModelCompatibility extends Schema.Class<DecisionModelCompatibility>("Decision.ModelCompatibility")(
{
/**
* Where a System One host reads media, from models.dev `[api.systemone] compatibility.image_input`:
* `assets` (TypeSafe's assets map), `images` (top-level lists) or `state` (items inside a state list).
* Where a System One host reads media, from models.dev `[api.systemone] compatibility.media_input`, named after
* where the media goes in the body: `assets` (TypeSafe's assets map, referenced from the state), `state` (items
* inside a state list) or `root` (one top-level list per kind: `images`, `audio`, `videos`).
*/
imageInput: Schema.optional(Schema.Literals(["assets", "images", "state"])),
mediaInput: Schema.optional(Schema.Literals(["assets", "state", "root"])),
},
) {}
@ -176,6 +177,8 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
readonly route: DecisionModelRoute<Options>
readonly http?: HttpOptions
readonly compatibility?: DecisionModelCompatibility
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
readonly providerOptions?: ProviderOptions
constructor(input: DecisionModel.Input<Options>) {
this.id = input.id
@ -183,6 +186,7 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
this.route = input.route
this.http = input.http
this.compatibility = input.compatibility
this.providerOptions = input.providerOptions
}
static make<Options extends DecisionOptions = DecisionOptions>(input: DecisionModel.MakeInput<Options>) {
@ -201,6 +205,7 @@ export namespace DecisionModel {
readonly route: DecisionModelRoute<Options>
readonly http?: HttpOptions
readonly compatibility?: DecisionModelCompatibility
readonly providerOptions?: ProviderOptions
}
export interface MakeInput<Options extends DecisionOptions = DecisionOptions>

View file

@ -2,16 +2,109 @@ export { AIClient } from "./ai-client.js"
export { LLMClient } from "./route/client.js"
export { ImageClient } from "./image-client.js"
export { Auth } from "./route/auth.js"
export { Provider } from "./provider.js"
export { ProviderPackage } from "./provider-package.js"
export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js"
export type { Interface as LLMClientShape, LLMClientService } from "./route/client.js"
export {
ProtocolID,
RouteID,
ModelID,
ProviderID,
ResponseID,
ContentBlockID,
ToolCallID,
JsonSchema,
ProviderOptions,
ProviderMetadata,
HttpTimeout,
RequestEncoding,
HttpOptions,
GenerationOptions,
LanguageModelDefaults,
ReasoningEfforts,
ReasoningEffort,
LanguageModelCompatibility,
LanguageModel,
LanguageModelSchema,
CacheTTL,
CacheHint,
CachePolicyObject,
CachePolicy,
MessageRole,
SystemPart,
TextPart,
MediaPart,
ToolResultValue,
ToolOutput,
ToolCallPart,
ToolResultPart,
ReasoningPart,
CompactionPart,
EffortPart,
ContentPart,
Message,
ToolDefinition,
ToolNamespace,
ToolEntry,
ToolChoice,
LLMRequest,
FinishReason,
Usage,
MediaUsage,
CompactionResponse,
CompactionCheckpointResponse,
StepStart,
TextStart,
TextDelta,
TextEnd,
ReasoningStart,
ReasoningDelta,
ReasoningEnd,
ToolInputStart,
ToolInputDelta,
ToolInputEnd,
ToolInputError,
ToolCall,
ToolResult,
ToolError,
FinishReasonDetails,
StepFinish,
Finish,
MediaEvent,
ProviderErrorEvent,
LLMEvent,
LLMResponse,
HttpContext,
HttpRateLimitDetails,
InvalidRequestError,
UnsupportedOperationError,
ProviderConfigurationError,
NoRouteError,
AuthenticationError,
RateLimitError,
QuotaExceededError,
ContentPolicyError,
ProviderInternalError,
TransportType,
TransportOperation,
TransportError,
InvalidProviderOutputError,
UnknownProviderError,
TimeoutError,
AIErrorReason,
AIError,
} from "./schema/index.js"
export type {
RouteLanguageModelInput,
RouteRoutedLanguageModelInput,
Interface as LLMClientShape,
LLMClientService,
} from "./route/client.js"
export * from "./schema/index.js"
GenerationOptionsFields,
GenerationOptionsInput,
LanguageModelInput,
LanguageModelProviderOptions,
ToolDefinitionInput,
ToolNamespaceInput,
ToolNamespaceEntryInput,
ToolEntryInput,
UsageInput,
} from "./schema/index.js"
export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js"
export type {
ImageModelOptions,
@ -125,7 +218,7 @@ export type {
Snapshot as GenerationSnapshot,
Status as GenerationStatus,
} from "./generation.js"
export { Tool, ToolFailure, toDefinitions } from "./tool.js"
export { Tool, ToolFailure, emptyInputJsonSchema, toDefinitions } from "./tool.js"
export { ToolRuntime } from "./tool-runtime.js"
export type { DispatchResult as ToolDispatchResult, ToolSettlement } from "./tool-runtime.js"
export type {
@ -142,11 +235,6 @@ export type {
ToolToModelOutput,
} from "./tool.js"
export * as LLM from "./llm.js"
export type {
Definition as ProviderDefinition,
LanguageModelFactory as ProviderLanguageModelFactory,
LanguageModelOptions as ProviderLanguageModelOptions,
} from "./provider.js"
export type {
Definition as ProviderPackageDefinition,
Settings as ProviderPackageSettings,

View file

@ -1,3 +1,16 @@
export { Extraction, ExtractionModel, ExtractionRequest, ExtractionResponse } from "./experimental/extraction.js"
export type {
ExtractionAnswerFor,
ExtractionAnswersFor,
ExtractionField,
ExtractionFields,
ExtractionModelOptions,
ExtractionOptions,
ExtractionRequestFor,
ExtractionRequestInput,
ExtractionResponseFor,
ExtractionRoute,
} from "./experimental/extraction.js"
export { Realtime } from "./experimental/realtime.js"
export type {
RealtimeConnectInput,

View file

@ -0,0 +1,106 @@
import { Effect, Schema } from "effect"
import { ExtractionAnswers, ExtractionModel, ExtractionResponse, type ExtractionRequestFor } from "./extraction.js"
import { JsonObject, ProviderShared } from "../protocols/shared.js"
import { Endpoint } from "../route/endpoint.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { Usage, mergeJsonRecords } from "../schema/index.js"
const route = MediaProtocol.identity({
id: "cloudflare-run-extraction",
name: "Cloudflare Run",
provider: "cloudflare-workers-ai",
})
const decodeEnvelope = route.decodeJson(
Schema.Struct({
result: Schema.Struct({
model: Schema.String,
answers: Schema.Record(Schema.String, JsonObject),
truncated: Schema.optional(Schema.Boolean),
state_text: Schema.optional(Schema.String),
usage: Schema.optional(
Schema.StructWithRest(
Schema.Struct({ input_tokens: Schema.optional(Schema.Number), output_tokens: Schema.optional(Schema.Number) }),
[JsonObject],
),
),
}),
}),
)
/** Posts Clairic's `{ model, state, fields }` body to Cloudflare's `/ai/run/{model}`. */
export const protocol = MediaProtocol.inline<ExtractionRequestFor, ExtractionResponse>(route, {
body: {
from: (request) =>
Effect.succeed(
MediaProtocol.json({
...mergeJsonRecords(request.providerOptions, request.http?.body),
model: request.model.id,
state: request.input,
fields: Object.fromEntries(
Object.entries(request.fields).map(([name, field]) => {
const { nullThreshold, ...rest } = field
return [name, nullThreshold === undefined ? rest : { ...rest, null_threshold: nullThreshold }]
}),
),
...(request.referenceDate === undefined ? {} : { reference_date: request.referenceDate }),
}),
),
},
response: {
decode: Effect.fn("CloudflareRunExtraction.decodeResponse")(function* (response, context) {
const output = yield* decodeEnvelope(response)
const result = output.value.result
// Each answer decodes as the field it answers; extra answers are dropped.
const answers = yield* Effect.forEach(Object.entries(context.request.fields), ([name, field]) => {
if (!Object.hasOwn(result.answers, name))
return Effect.fail(output.invalid(`${route.name} returned no answer for ${name}`))
if (!Object.hasOwn(ExtractionAnswers, field.type)) return Effect.succeed([name, result.answers[name]] as const)
return Schema.decodeUnknownEffect(ExtractionAnswers[field.type as keyof typeof ExtractionAnswers])(
result.answers[name],
).pipe(
Effect.map((answer) => [name, answer] as const),
Effect.mapError((cause) => output.invalid(`${route.name} returned an invalid answer for ${name}`, cause)),
)
})
return new ExtractionResponse({
answers: Object.fromEntries(answers),
usage:
result.usage === undefined
? undefined
: new Usage({
inputTokens: result.usage.input_tokens,
outputTokens: result.usage.output_tokens,
totalTokens: ProviderShared.totalTokens(result.usage.input_tokens, result.usage.output_tokens, undefined),
providerMetadata: { [route.provider]: result.usage },
}),
providerMetadata: {
[route.provider]: {
model: result.model,
...(result.truncated === undefined ? {} : { truncated: result.truncated }),
...(result.state_text === undefined ? {} : { stateText: result.state_text }),
},
},
})
}),
},
})
/** `baseURL` is the Run API base, `.../client/v4/accounts/{account}/ai/run`. */
export const model = (input: MediaRoute.ModelInput) =>
new ExtractionModel({
id: input.id,
provider: route.provider,
http: input.http,
route: MediaRoute.inline({
protocol,
endpoint: Endpoint.path<MediaProtocol.Body, ExtractionRequestFor>(({ request }) => `/${request.model.id}`, {
baseURL: input.baseURL,
}),
auth: input.auth,
headers: input.headers,
}),
})
export const CloudflareRunExtraction = { protocol, model } as const

View file

@ -0,0 +1,189 @@
import { Effect, Schema } from "effect"
import { MediaModel, tryRequest } from "../media-model.js"
import { RequestExecutor } from "../route/executor.js"
import type { MediaRoute } from "../route/media.js"
import { AIError, HttpOptions, ProviderMetadata, ProviderOptions, Usage, type OpenString } from "../schema/index.js"
// ---------------------------------------------------------------------------
// Answers
// ---------------------------------------------------------------------------
/** `[start, end)` character offsets into `input`. */
const Span = Schema.Tuple([Schema.Int, Schema.Int])
/** An ISO date for date estimates; anything else is numeric. */
const NumberOrDate = Schema.Union([Schema.Number, Schema.String])
/** `value` is null when the input does not determine it; `guess` is the most likely value either way. */
const valueAnswer = <Value extends Schema.Top>(value: Value) =>
Schema.Struct({
value: Schema.NullOr(value),
guess: Schema.optional(value),
nullProbability: Schema.optional(Schema.Number),
confidence: Schema.optional(Schema.Number),
span: Schema.optional(Span),
}).pipe(Schema.encodeKeys({ nullProbability: "p_null" }))
const StringAnswer = valueAnswer(Schema.String)
const NumberAnswer = valueAnswer(Schema.Number)
/** `value` is the most likely point; `p10` to `p90` is the 80% interval. */
const EstimateAnswer = Schema.Struct({
value: NumberOrDate,
mean: Schema.optional(NumberOrDate),
median: NumberOrDate,
p10: NumberOrDate,
p90: NumberOrDate,
belowProbability: Schema.optional(Schema.Number),
aboveProbability: Schema.optional(Schema.Number),
quantiles: Schema.optional(Schema.Array(NumberOrDate)),
}).pipe(Schema.encodeKeys({ belowProbability: "p_below", aboveProbability: "p_above" }))
/**
* The answer schema for each field type Clairic documents, decoding its wire keys (`p_null` and friends). Answers to
* other field types pass through as sent.
*/
export const ExtractionAnswers = {
text: StringAnswer,
number: NumberAnswer,
date: StringAnswer,
time: StringAnswer,
datetime: StringAnswer,
duration: NumberAnswer,
list: Schema.Struct({
value: Schema.NullOr(Schema.Array(Schema.Union([Schema.String, Schema.Number]))),
spans: Schema.optional(Schema.Array(Span)),
confidence: Schema.optional(Schema.Number),
}),
estimate: EstimateAnswer,
/** One estimate per step of the series. */
forecast: Schema.Struct({ value: Schema.Array(NumberOrDate), steps: Schema.Array(EstimateAnswer) }),
}
type Answers = typeof ExtractionAnswers
export type ExtractionAnswerFor<Field extends ExtractionField> = Field["type"] extends keyof Answers
? Answers[Field["type"]]["Type"]
: Readonly<Record<string, unknown>>
/** One answer per field, keyed by field name. */
export type ExtractionAnswersFor<Fields extends ExtractionFields> = {
readonly [Name in keyof Fields]: ExtractionAnswerFor<Fields[Name]>
}
// ---------------------------------------------------------------------------
// Fields
// ---------------------------------------------------------------------------
/** Options beyond these, such as `unit`, `decimals`, `items`, `min` or `max`, go to the host as written. */
const ExtractionFieldSchema = Schema.StructWithRest(
Schema.Struct({
type: Schema.String,
instructions: Schema.optional(Schema.String),
/** Probability of null above which the value is null; the host's default is 0.5. */
nullThreshold: Schema.optional(Schema.Number),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
)
export type ExtractionField = typeof ExtractionFieldSchema.Type & { readonly type: OpenString<keyof Answers> }
export type ExtractionFields = Readonly<Record<string, ExtractionField>>
// ---------------------------------------------------------------------------
// Model
// ---------------------------------------------------------------------------
export type ExtractionOptions = MediaModel.Options
export type ExtractionRoute = MediaRoute.InlineRoute<ExtractionRequestFor, ExtractionResponse>
export class ExtractionModel<Options extends ExtractionOptions = ExtractionOptions> extends MediaModel<
ExtractionRoute,
Options
> {
declare protected readonly _ExtractionModel: void
}
export type ExtractionModelOptions<Model> = Model extends ExtractionModel<infer Options> ? Options : never
// ---------------------------------------------------------------------------
// Request and response
// ---------------------------------------------------------------------------
export class ExtractionRequest extends Schema.Class<ExtractionRequest>("Extraction.Request")({
model: Schema.declare((value): value is ExtractionModel => value instanceof ExtractionModel, {
expected: "Extraction.Model",
}),
/** The text to read; text answers carry spans into it. */
input: Schema.String,
fields: Schema.Record(Schema.String, ExtractionFieldSchema).pipe(
Schema.refine((x): x is typeof x => Object.keys(x).length > 0, { message: "Extraction fields must not be empty" }),
),
/** ISO date that anchors dates written without a year. */
referenceDate: Schema.optional(Schema.String),
providerOptions: Schema.optional(ProviderOptions),
http: Schema.optional(HttpOptions),
}) {
declare protected readonly _ExtractionRequest: void
}
export type ExtractionRequestFor<
Options extends ExtractionOptions = ExtractionOptions,
Fields extends ExtractionFields = ExtractionFields,
> = Omit<ExtractionRequest, "model" | "fields" | "providerOptions"> & {
readonly model: ExtractionModel<Options>
readonly fields: Fields
readonly providerOptions?: Options
}
export type ExtractionRequestInput<
Model extends ExtractionModel = ExtractionModel,
Fields extends ExtractionFields = ExtractionFields,
> = {
readonly model: Model
readonly input: string
readonly fields: Fields
readonly referenceDate?: string
readonly providerOptions?: NoInfer<ExtractionModelOptions<Model>>
readonly http?: HttpOptions.Input
}
export class ExtractionResponse extends Schema.Class<ExtractionResponse>("Extraction.Response")({
answers: Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown)),
usage: Schema.optional(Usage),
providerMetadata: Schema.optional(ProviderMetadata),
}) {}
export type ExtractionResponseFor<Fields extends ExtractionFields> = Omit<ExtractionResponse, "answers"> & {
readonly answers: ExtractionAnswersFor<Fields>
}
// ---------------------------------------------------------------------------
// Call API
// ---------------------------------------------------------------------------
export function request<const Model extends ExtractionModel, const Fields extends ExtractionFields>(
input: ExtractionRequestInput<Model, Fields>,
): ExtractionRequestFor<ExtractionModelOptions<Model>, Fields>
export function request(input: ExtractionRequest): ExtractionRequest
export function request(input: ExtractionRequest | ExtractionRequestInput): ExtractionRequest
export function request(input: ExtractionRequest | ExtractionRequestInput) {
if (input instanceof ExtractionRequest) return input
return new ExtractionRequest({ ...input, http: HttpOptions.make(input.http) })
}
export function generate<const Model extends ExtractionModel, const Fields extends ExtractionFields>(
input: ExtractionRequestInput<Model, Fields>,
): Effect.Effect<ExtractionResponseFor<Fields>, AIError, RequestExecutor.Service>
export function generate(input: ExtractionRequest): Effect.Effect<ExtractionResponse, AIError, RequestExecutor.Service>
export function generate(input: ExtractionRequest | ExtractionRequestInput) {
return Effect.gen(function* () {
const executor = yield* RequestExecutor.Service
const built = yield* tryRequest(() => request(input))
return yield* built.model.route.generate(built, executor.execute)
})
}
export const Extraction = {
request,
generate,
} as const

View file

@ -38,6 +38,7 @@ export class ImageModel<Options extends ImageOptions = ImageOptions> extends Med
id: input.id,
provider: route.protocol.provider,
http: input.http,
providerOptions: input.providerOptions,
route: composeRoute(route, input, collectResponse) as ImageRoute,
})
}

View file

@ -2,14 +2,7 @@ import { Effect } from "effect"
import { Endpoint } from "./route/endpoint.js"
import { MediaRoute } from "./route/media.js"
import type { MediaProtocol } from "./route/media-protocol.js"
import {
AIError,
HttpOptions,
InvalidRequestError,
ModelID,
ProviderID,
type ProviderOptions,
} from "./schema/index.js"
import { AIError, HttpOptions, InvalidRequestError, ModelID, ProviderID, type ProviderOptions } from "./schema/index.js"
/**
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
@ -24,12 +17,15 @@ export class MediaModel<Route, Options> {
readonly provider: ProviderID
readonly route: Route
readonly http?: HttpOptions
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
readonly providerOptions?: ProviderOptions
constructor(input: MediaModel.Input<Route>) {
this.id = ModelID.make(input.id)
this.provider = ProviderID.make(input.provider)
this.route = input.route
this.http = input.http
this.providerOptions = input.providerOptions
}
}
@ -41,6 +37,7 @@ export namespace MediaModel {
readonly provider: string | ProviderID
readonly route: Route
readonly http?: HttpOptions
readonly providerOptions?: ProviderOptions
}
/** A protocol plus its canonical start path; `ModelInput.baseURL` overrides `baseURL` per deployment. */

View file

@ -10,6 +10,7 @@ import { Headers } from "effect/http"
import { HttpTransport } from "../route/transport/index.js"
import {
AIError,
CacheTTL,
HttpOptions,
LLMRequest,
LLMEvent,
@ -80,7 +81,7 @@ export type ContextManagement = typeof ContextManagement.Type
// =============================================================================
const AnthropicCacheControl = Schema.Struct({
type: Schema.tag("ephemeral"),
ttl: Schema.optional(Schema.Literals(["5m", "1h"])),
ttl: Schema.optional(CacheTTL),
})
const AnthropicServiceTier = knownString<"auto" | "standard_only">()
const AnthropicSpeed = knownString<"fast" | "standard">()
@ -533,9 +534,6 @@ const invalid = ProviderShared.invalidRequest
// that exceed it.
const ANTHROPIC_BREAKPOINT_CAP = 4
const EPHEMERAL_5M = { type: "ephemeral" as const }
const EPHEMERAL_1H = { type: "ephemeral" as const, ttl: "1h" as const }
const cacheControl = (breakpoints: Cache.Breakpoints, cache: CacheHint | undefined) => {
if (cache?.type !== "ephemeral" && cache?.type !== "persistent") return undefined
if (breakpoints.remaining <= 0) {
@ -543,7 +541,7 @@ const cacheControl = (breakpoints: Cache.Breakpoints, cache: CacheHint | undefin
return undefined
}
breakpoints.remaining -= 1
return Cache.ttlBucket(cache.ttlSeconds) === "1h" ? EPHEMERAL_1H : EPHEMERAL_5M
return { type: "ephemeral" as const, ...(cache.ttl === undefined ? {} : { ttl: cache.ttl }) }
}
const providerMetadata = (key: string, metadata: Record<string, unknown>): ProviderMetadata => ({ [key]: metadata })

View file

@ -13,6 +13,7 @@ import {
type LLMRequest,
type LanguageModel,
type ProviderMetadata,
type ProviderOptions,
type ReasoningPart,
type ToolCallPart,
type ToolDefinition,
@ -24,7 +25,7 @@ import { JsonObject, optionalArray, ProviderShared } from "./shared.js"
import { BedrockAuth } from "./utils/bedrock-auth.js"
import { BedrockCache } from "./utils/bedrock-cache.js"
import { BedrockMedia } from "./utils/bedrock-media.js"
import { supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
import { Lifecycle } from "./utils/lifecycle.js"
import { MistralToolID } from "./utils/mistral-tool-id.js"
import { ToolStream } from "./utils/tool-stream.js"
@ -125,6 +126,12 @@ const BedrockToolChoice = Schema.Union([
Schema.Struct({ tool: Schema.Struct({ name: Schema.String }) }),
])
// Value sets from the Converse API reference. Unknown values pass through for forward compatibility.
const ServiceTierType = ProviderShared.knownString<"priority" | "default" | "flex" | "reserved">()
const GuardrailTrace = ProviderShared.knownString<"enabled" | "disabled" | "enabled_full">()
const GuardrailStreamProcessingMode = ProviderShared.knownString<"sync" | "async">()
const TextFormatType = ProviderShared.knownString<"json_schema">()
const BedrockBodyFields = {
modelId: Schema.String,
messages: Schema.Array(BedrockMessage),
@ -144,6 +151,30 @@ const BedrockBodyFields = {
}),
),
additionalModelRequestFields: Schema.optional(JsonObject),
serviceTier: Schema.optional(Schema.Struct({ type: ServiceTierType })),
guardrailConfig: Schema.optional(
Schema.Struct({
guardrailIdentifier: Schema.String,
guardrailVersion: Schema.String,
trace: Schema.optional(GuardrailTrace),
streamProcessingMode: Schema.optional(GuardrailStreamProcessingMode),
}),
),
outputConfig: Schema.optional(
Schema.Struct({
textFormat: Schema.Struct({
type: TextFormatType,
structure: Schema.Struct({
jsonSchema: Schema.Struct({
schema: Schema.String,
name: Schema.optional(Schema.String),
description: Schema.optional(Schema.String),
}),
}),
}),
}),
),
requestMetadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
}
const BedrockConverseBody = Schema.Struct(BedrockBodyFields)
export type BedrockConverseBody = Schema.Schema.Type<typeof BedrockConverseBody>
@ -467,10 +498,57 @@ const isHighReasoningEffort = Schema.is(
}),
)
// Claude 4.6+ pairs effort with adaptive thinking; earlier Claude models take effort beside a manual budget.
const supportsAdaptiveThinking = (model: LanguageModel) => {
const version = claudeVersion(model.id)
return version !== undefined && (version.major > 4 || (version.major === 4 && version.minor >= 6))
}
const effortFields = (model: LanguageModel, effort: string) => {
if (model.id.includes("anthropic")) return { output_config: { effort } }
// gpt-oss takes the flat chat-completions spelling; newer OpenAI and xAI models take the Responses one.
if (model.id.includes("openai.gpt-oss")) return { reasoning_effort: effort }
if (model.id.includes("openai.") || model.id.includes("xai.")) return { reasoning: { effort } }
return { reasoningConfig: { type: "enabled", maxReasoningEffort: effort } }
}
const Options = Schema.Struct({
thinking: Schema.optional(Schema.Struct({ type: Schema.Literal("enabled"), budgetTokens: Schema.Number })),
/** Claude thinking. `adaptive` and `disabled` apply to Claude models only. */
thinking: Schema.optional(
Schema.Union([
Schema.Struct({ type: Schema.Literal("enabled"), budgetTokens: Schema.Number }),
Schema.Struct({
type: Schema.Literal("adaptive"),
display: Schema.optional(ProviderShared.knownString<"summarized" | "omitted">()),
}),
Schema.Struct({ type: Schema.Literal("disabled") }),
]),
),
/** Reasoning effort, sent in the field each model family reads. */
effort: Schema.optional(ProviderShared.knownString<"low" | "medium" | "high" | "xhigh" | "max">()),
serviceTier: Schema.optional(ServiceTierType),
/** Constrains the response text to a JSON schema. */
outputFormat: Schema.optional(
Schema.Struct({
type: TextFormatType,
schema: JsonObject,
name: Schema.optional(Schema.String),
description: Schema.optional(Schema.String),
}),
),
guardrail: Schema.optional(
Schema.Struct({
identifier: Schema.String,
version: Schema.String,
trace: Schema.optional(GuardrailTrace),
streamProcessingMode: Schema.optional(GuardrailStreamProcessingMode),
}),
),
/** Key-value pairs for filtering invocation logs. */
requestMetadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
})
export type OptionsInput = typeof Options.Type
/** Caller-facing provider options; unknown keys are accepted and ignored. */
export type OptionsInput = ProviderOptions & typeof Options.Encoded
const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))
// Claude on Bedrock requires the thinking budget below `maxTokens`, with a minimum of 1,024.
const MIN_THINKING_BUDGET = 1_024
@ -486,7 +564,7 @@ const isThinkingDisabled = Schema.is(
// Claude 5.1+ binds each thinking signature to the prefix above it. Ask Bedrock to drop the affected blocks instead of
// failing when that prefix changes. `http.body` overlays this field by field, so callers can still override it.
const applyThinkingBindingDefault = (request: LLMRequest, thinking: Readonly<Record<string, unknown>> | undefined) => {
if (isThinkingDisabled(request.http?.body)) return thinking
if (thinking?.type === "disabled" || isThinkingDisabled(request.http?.body)) return thinking
if (!supportsThinkingBlockBinding(request.model)) return thinking
return {
...(thinking ?? { type: "adaptive" as const }),
@ -500,20 +578,32 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request:
const generation = request.generation
const options = yield* decodeOptions(request.providerOptions ?? {})
const maxTokens =
isNova2(request.model) && isHighReasoningEffort(request.http?.body) ? undefined : generation?.maxTokens
isNova2(request.model) && (options.effort === "high" || isHighReasoningEffort(request.http?.body))
? undefined
: generation?.maxTokens
const thinking = applyThinkingBindingDefault(
request,
options.thinking === undefined
? undefined
: {
(() => {
if (options.thinking?.type === "enabled")
return {
type: "enabled",
budget_tokens: ProviderShared.fitThinkingBudget(
options.thinking.budgetTokens,
maxTokens,
MIN_THINKING_BUDGET,
),
},
}
if (options.thinking !== undefined) return options.thinking
if (options.effort !== undefined && supportsAdaptiveThinking(request.model)) return { type: "adaptive" }
})(),
)
const additionalModelRequestFields = {
...(generation?.topK === undefined ? {} : { top_k: generation.topK }),
...(thinking === undefined ? {} : { thinking }),
...(options.effort === undefined ? {} : effortFields(request.model, options.effort)),
// Converse takes Anthropic betas in the body, and Bedrock rejects `block_binding` without this one.
...(thinking?.block_binding === undefined ? {} : { anthropic_beta: [THINKING_BINDING_BETA] }),
}
// Bedrock-Claude shares Anthropic's 4-breakpoint cap. Spend the budget in
// tools → system → messages order to favour the highest-impact prefixes.
const breakpoints = BedrockCache.breakpoints(request.model)
@ -554,17 +644,36 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request:
system,
inferenceConfig,
toolConfig,
// Converse's base inferenceConfig has no topK or thinking; Anthropic/Nova accept them
// Converse's base inferenceConfig has no topK, thinking or effort; models accept them
// as model-specific fields, so they go through additionalModelRequestFields.
additionalModelRequestFields:
generation?.topK === undefined && thinking === undefined
Object.keys(additionalModelRequestFields).length === 0 ? undefined : additionalModelRequestFields,
serviceTier: options.serviceTier === undefined ? undefined : { type: options.serviceTier },
guardrailConfig:
options.guardrail === undefined
? undefined
: {
...(generation?.topK === undefined ? {} : { top_k: generation.topK }),
...(thinking === undefined ? {} : { thinking }),
// Converse takes Anthropic betas in the body, and Bedrock rejects `block_binding` without this one.
...(thinking?.block_binding === undefined ? {} : { anthropic_beta: [THINKING_BINDING_BETA] }),
guardrailIdentifier: options.guardrail.identifier,
guardrailVersion: options.guardrail.version,
trace: options.guardrail.trace,
streamProcessingMode: options.guardrail.streamProcessingMode,
},
outputConfig:
options.outputFormat === undefined
? undefined
: {
textFormat: {
type: options.outputFormat.type,
structure: {
jsonSchema: {
schema: ProviderShared.encodeJson(options.outputFormat.schema),
name: options.outputFormat.name,
description: options.outputFormat.description,
},
},
},
},
requestMetadata: options.requestMetadata,
}
})

View file

@ -135,6 +135,7 @@ const consumeFrames = (route: string) => (state: FrameBufferState, input: FrameI
export const framing = (route: string): Framing.Definition<Frame> => ({
id: "aws-event-stream",
body: (frame) => frame.rawBody,
raw: ({ rawBody: _, ...event }) => event,
frame: (bytes) =>
bytes.pipe(
Stream.map((bytes): FrameInput => ({ _tag: "Chunk", bytes })),

View file

@ -27,7 +27,7 @@ export const protocol = DecisionRoute.protocol({
inlineMedia: true,
body: {
from: (request) =>
SystemOne.encodeBody(request, "images").pipe(Effect.map((input) => ({ model: request.model.id, input }))),
SystemOne.encodeBody(request, "root").pipe(Effect.map((input) => ({ model: request.model.id, input }))),
},
response: {
decode: (response, context) =>

View file

@ -1,6 +1,6 @@
import { Effect, Schema } from "effect"
import { Protocol } from "../route/protocol.js"
import type { LLMRequest } from "../schema/index.js"
import { CacheTTL, type LLMRequest } from "../schema/index.js"
import { AnthropicMessages } from "./anthropic-messages.js"
import { MetaResponses } from "./meta-responses.js"
import { JsonObject, optionalArray, ProviderShared } from "./shared.js"
@ -12,7 +12,7 @@ const WebSearch = Schema.Struct({
})
const MetaCacheControl = Schema.Struct({
type: Schema.tag("ephemeral"),
ttl: Schema.optional(Schema.Literals(["5m", "1h"])),
ttl: Schema.optional(CacheTTL),
})
const FunctionTool = Schema.Struct({
name: Schema.String,

View file

@ -24,7 +24,8 @@ import {
} from "../schema/index.js"
import { classifyProviderFailure } from "../provider-error.js"
import { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
import { cacheControl } from "./utils/cache.js"
import { placesMarkers, requestTTL } from "../cache-policy.js"
import * as Cache from "./utils/cache.js"
import { resolveParallelToolCalls } from "./open-responses.js"
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
import { Lifecycle } from "./utils/lifecycle.js"
@ -186,6 +187,8 @@ export const bodyFields = {
stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),
store: Schema.optional(Schema.Boolean),
prompt_cache_key: Schema.optional(Schema.String),
prompt_cache_retention: Schema.optional(Schema.String),
prompt_cache_options: Schema.optional(Schema.Struct({ ttl: Schema.optional(Schema.String) })),
reasoning_effort: Schema.optional(OpenResponsesOptions.ReasoningEffort),
verbosity: Schema.optional(OpenResponsesOptions.TextVerbositySchema),
service_tier: Schema.optional(OpenResponsesOptions.ServiceTierSchema),
@ -779,6 +782,8 @@ const lowerOptions = (request: LLMRequest, supportsStore: boolean, hasActiveTool
return {
...(supportsStore ? { store: options.store ?? false } : {}),
...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
// Inline markers carry the lifetime when the policy places them.
...(placesMarkers(request) ? {} : Cache.openAIRequestTTL(requestTTL(request))),
...(options.reasoningEffort ? { reasoning_effort: options.reasoningEffort } : {}),
...(options.textVerbosity ? { verbosity: options.textVerbosity } : {}),
...(options.serviceTier ? { service_tier: options.serviceTier } : {}),
@ -841,7 +846,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
// Provider wrappers that pass their own marker writer keep it; otherwise a declared cache format adds one.
const declaredCacheControl = (request: LLMRequest) =>
request.model.compatibility?.cacheFormat === undefined ? undefined : cacheControl()
request.model.compatibility?.cacheFormat === undefined ? undefined : Cache.cacheControl()
// =============================================================================
// Stream Parsing

View file

@ -7,6 +7,7 @@ import { Endpoint } from "../route/endpoint.js"
import { Protocol } from "../route/protocol.js"
import { HttpTransport } from "../route/transport/index.js"
import { LLMRequest, type ToolDefinition, type ToolEntry } from "../schema/index.js"
import { requestTTL } from "../cache-policy.js"
import { resolveEffortUpdates } from "../effort-updates.js"
import { OpenResponses } from "./open-responses.js"
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
@ -15,6 +16,7 @@ import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js"
import { OpenResponsesChannel } from "./open-responses-channel.js"
import { ResponsesCompaction } from "./utils/responses-compaction.js"
import { ResponsesCheckpoint } from "./utils/responses-checkpoint.js"
import * as Cache from "./utils/cache.js"
const ADAPTER = "openai-responses"
const NAME = "OpenAI Responses"
@ -116,6 +118,8 @@ const OpenAIResponsesToolChoice = Schema.Union([
const OpenAIResponsesCoreFields = {
...OpenResponses.coreFields,
prompt_cache_retention: Schema.optional(Schema.String),
prompt_cache_options: Schema.optional(Schema.Struct({ ttl: Schema.optional(Schema.String) })),
tools: optionalArray(OpenAIResponsesTools),
tool_choice: Schema.optional(OpenAIResponsesToolChoice),
reasoning: Schema.optional(
@ -226,6 +230,7 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
return {
...(yield* OpenResponses.lowerConversation(updates.request, adapter)),
...generation,
...Cache.openAIRequestTTL(requestTTL(request)),
...(generation.reasoning || reasoning.reasoningMode || reasoning.reasoningContext
? {
reasoning: {

View file

@ -19,8 +19,8 @@ export const DEFAULT_PATH = "/systemone"
export const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1"
/** `messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
type ImageInput = NonNullable<DecisionModelCompatibility["imageInput"]> | "messages"
/** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
type MediaInput = NonNullable<DecisionModelCompatibility["mediaInput"]> | "state.messages"
const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }))
const Answer = Schema.Union([
@ -58,13 +58,13 @@ export type Response = Schema.Schema.Type<typeof Response>
const ID = "system-one"
const NAME = "System One"
/** The System One body without `model`; media goes where the model's `imageInput` says, else `fallback`. */
/** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (
request: DecisionRequestFor,
fallback: ImageInput,
fallback: MediaInput,
) {
const questions = yield* encodeQuestions(request.questions)
const placed = yield* placeMedia(request, request.model.compatibility?.imageInput ?? fallback)
const placed = yield* placeMedia(request, request.model.compatibility?.mediaInput ?? fallback)
return { ...mergeJsonRecords(request.providerOptions, request.http?.body), ...placed, questions }
})
@ -103,7 +103,7 @@ const encodeQuestions = (questions: ReadonlyArray<DecisionQuestion>) =>
] as const)
}).pipe(Effect.map(Object.fromEntries))
const placeMedia = Effect.fnUntraced(function* (request: DecisionRequestFor, imageInput: ImageInput) {
const placeMedia = Effect.fnUntraced(function* (request: DecisionRequestFor, mediaInput: MediaInput) {
const parts = request.input
const unsupported = (asset: Media.Asset, accepted: string) =>
new AIError({
@ -116,9 +116,9 @@ const placeMedia = Effect.fnUntraced(function* (request: DecisionRequestFor, ima
})
const media = parts.flatMap((part) => (part.type === "media" ? [part.media] : []))
if (media.length === 0) return { state: state(parts.map(plain)) }
if (imageInput === "state") return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) }
if (mediaInput === "state") return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) }
// Chat-style content in one user message: text and JSON as text parts, media as in `state`.
if (imageInput === "messages")
if (mediaInput === "state.messages")
return {
state: {
messages: [
@ -133,7 +133,7 @@ const placeMedia = Effect.fnUntraced(function* (request: DecisionRequestFor, ima
],
},
}
if (imageInput === "images") {
if (mediaInput === "root") {
const lists = { image: "images", audio: "audio", video: "videos" } as const
const unplaced = media.find((asset) => !Object.hasOwn(lists, asset.kind))
if (unplaced !== undefined) return yield* unsupported(unplaced, "images, audio and video")

View file

@ -1,14 +1,14 @@
import { Schema } from "effect"
import type { CacheHint, LLMRequest } from "../../schema/index.js"
import { newBreakpoints, ttlBucket } from "./cache.js"
import { CacheTTL, type CacheHint, type LLMRequest } from "../../schema/index.js"
import { newBreakpoints } from "./cache.js"
// Bedrock cache markers are positional: emit a `cachePoint` block immediately
// after the content the caller wants treated as a cacheable prefix. Bedrock
// accepts optional `ttl: "5m" | "1h"` on cachePoint.
// accepts an optional `ttl` such as "5m" or "1h" on cachePoint.
export const CachePointBlock = Schema.Struct({
cachePoint: Schema.Struct({
type: Schema.tag("default"),
ttl: Schema.optional(Schema.Literals(["5m", "1h"])),
ttl: Schema.optional(CacheTTL),
}),
})
export type CachePointBlock = Schema.Schema.Type<typeof CachePointBlock>
@ -44,9 +44,6 @@ export const breakpoints = (model: LLMRequest["model"]) => {
}
export type Breakpoints = ReturnType<typeof breakpoints>
const DEFAULT_5M: CachePointBlock = { cachePoint: { type: "default" } }
const DEFAULT_1H: CachePointBlock = { cachePoint: { type: "default", ttl: "1h" } }
export const block = (breakpoints: Breakpoints, cache: CacheHint | undefined): CachePointBlock | undefined => {
if (!breakpoints.supported) return undefined
if (cache?.type !== "ephemeral" && cache?.type !== "persistent") return undefined
@ -55,7 +52,9 @@ export const block = (breakpoints: Breakpoints, cache: CacheHint | undefined): C
return undefined
}
breakpoints.remaining -= 1
return breakpoints.ttl1h && ttlBucket(cache.ttlSeconds) === "1h" ? DEFAULT_1H : DEFAULT_5M
// Older Claude releases cache for five minutes only, so a one-hour request falls back to the default.
const ttl = cache.ttl === "1h" && !breakpoints.ttl1h ? undefined : cache.ttl
return { cachePoint: { type: "default", ...(ttl === undefined ? {} : { ttl }) } }
}
export * as BedrockCache from "./bedrock-cache.js"

View file

@ -1,5 +1,5 @@
// Shared counter and TTL mapping for provider cache-marker lowering.
import type { CacheHint } from "../../schema/index.js"
// Shared counter and lifetime mapping for provider cache lowering.
import type { CacheHint, CacheTTL } from "../../schema/index.js"
export interface Breakpoints {
remaining: number
@ -8,16 +8,20 @@ export interface Breakpoints {
export const newBreakpoints = (cap: number): Breakpoints => ({ remaining: cap, dropped: 0 })
// Requests of at least one hour use the explicit `"1h"` bucket; shorter
// requests omit the wire TTL and use the provider default.
export const ttlBucket = (ttlSeconds: number | undefined): "1h" | undefined =>
ttlSeconds !== undefined && ttlSeconds >= 3600 ? "1h" : undefined
export const cacheControl = () => {
const breakpoints = newBreakpoints(4)
return (cache: CacheHint | undefined) => {
if (cache === undefined || breakpoints.remaining === 0) return undefined
breakpoints.remaining -= 1
return { type: "ephemeral" as const, ttl: ttlBucket(cache.ttlSeconds) }
return { type: "ephemeral" as const, ttl: cache.ttl }
}
}
// OpenAI's request-level lifetime. `prompt_cache_retention` takes only "24h" (or "in_memory") and is the only
// control before GPT-5.6; every other lifetime goes to `prompt_cache_options.ttl`, which GPT-5.6+, Kimi and
// DeepInfra read.
export const openAIRequestTTL = (ttl: CacheTTL | undefined) => {
if (ttl === undefined) return {}
if (ttl === "24h") return { prompt_cache_retention: ttl }
return { prompt_cache_options: { ttl } }
}

View file

@ -3,7 +3,7 @@ import { isRecord } from "../../utils/record.js"
// Gemini's `parametersJsonSchema` accepts standard JSON Schema, but rejects a few shapes that
// published tool schemas commonly contain. Rewrite only those and send everything else unchanged.
const SCHEMA_MAPS = new Set([
export const SCHEMA_MAPS = new Set([
"properties",
"patternProperties",
"$defs",
@ -11,9 +11,9 @@ const SCHEMA_MAPS = new Set([
"dependentSchemas",
"dependencies",
])
const VALUES = new Set(["const", "default", "enum", "examples", "dependentRequired"])
export const VALUES = new Set(["const", "default", "enum", "examples", "dependentRequired"])
const mapValues = (record: Record<string, unknown>, map: (value: unknown, key: string) => unknown) =>
export const mapValues = (record: Record<string, unknown>, map: (value: unknown, key: string) => unknown) =>
Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value, key)]))
const normalizeNode = (schema: unknown): unknown => {

View file

@ -2,6 +2,8 @@ import { ToolDefinition, type JsonSchema, type LanguageModel, type LLMRequest }
import { isRecord } from "../../utils/record.js"
import { GeminiJsonSchema } from "./gemini-json-schema.js"
const { SCHEMA_MAPS, VALUES, mapValues } = GeminiJsonSchema
const tupleItemsSchema = (items: ReadonlyArray<unknown>) => {
const projected = items.map(moonshotNode)
if (projected.length === 0) return {}
@ -27,10 +29,16 @@ const moonshotNode = (schema: unknown): unknown => {
return Object.fromEntries([
...(type === undefined ? [] : [["type", type]]),
...Object.entries(schema).flatMap(([key, value]) => {
if (key === "items" && Array.isArray(value)) return [[key, tupleItemsSchema(value)]]
if (VALUES.has(key)) return [[key, value]]
if (SCHEMA_MAPS.has(key) && isRecord(value)) return [[key, mapValues(value, moonshotNode)]]
if (key === "items") {
if (Array.isArray(schema.prefixItems)) return []
if (Array.isArray(value)) return [[key, tupleItemsSchema(value)]]
}
if (key === "prefixItems") {
if ("items" in schema) return []
return [["items", tupleItemsSchema(Array.isArray(value) ? value : [])]]
if (!Array.isArray(value)) return "items" in schema ? [] : [["items", {}]]
const rest = isRecord(schema.items) ? [schema.items] : Array.isArray(schema.items) ? schema.items : []
return [["items", tupleItemsSchema([...value, ...rest])]]
}
if (key === "unevaluatedItems") return []
return [[key, moonshotNode(value)]]

View file

@ -203,7 +203,7 @@ const fromRequest = Effect.fn("VeniceChat.fromRequest")(function* (request: LLMR
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`), value]),
),
prompt_cache_retention: options.promptCacheRetention,
prompt_cache_retention: options.promptCacheRetention ?? body.prompt_cache_retention,
parallel_tool_calls: options.parallelToolCalls,
min_p: options.minP,
top_k: request.generation?.topK,

View file

@ -1,36 +0,0 @@
import type { LanguageModel, ModelID, ProviderID } from "./schema/index.js"
export type LanguageModelOptions = Pick<LanguageModel.Input, "defaults" | "compatibility">
/**
* Advanced structural provider definition helper. Built-in providers should
* prefer explicit `configure(options).model(id)` facades so deployment config is
* chosen before model selection. The optional `apis` map remains for external
* structural providers that expose multiple route selectors behind one provider.
*/
export type LanguageModelFactory<Options extends LanguageModelOptions = LanguageModelOptions> = (
id: string | ModelID,
options?: Options,
) => LanguageModel
type AnyLanguageModelFactory = (...args: never[]) => LanguageModel
export interface Definition<Factory extends AnyLanguageModelFactory = LanguageModelFactory> {
readonly id: ProviderID
readonly model: Factory
readonly apis?: Record<string, AnyLanguageModelFactory>
}
type DefinitionShape = {
readonly id: ProviderID
readonly model: (...args: never[]) => LanguageModel
readonly apis?: Record<string, (...args: never[]) => LanguageModel>
}
type NoExtraFields<Input, Shape> = Input & Record<Exclude<keyof Input, keyof Shape>, never>
export const make = <DefinitionType extends DefinitionShape>(
definition: NoExtraFields<DefinitionType, DefinitionShape>,
) => definition
export * as Provider from "./provider.js"

View file

@ -9,7 +9,13 @@ import { Route, type RouteDefaultsInput } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import { Framing } from "../route/framing.js"
import { MediaRoute } from "../route/media.js"
import { ProviderConfigurationError, ProviderID, ToolDefinition, type ModelID } from "../schema/index.js"
import {
ProviderConfigurationError,
ProviderID,
ToolDefinition,
type ModelID,
type ProviderOptions,
} from "../schema/index.js"
export const id = ProviderID.make("alibaba")
@ -107,30 +113,35 @@ export const configure = (input: Config) => {
.model<MessagesOptionsInput>({ id, compatibility: { requireSignature: false } })
const responses = (id: string | ModelID) => responsesRoute.with(common).model<ResponsesOptionsInput>({ id })
const media = MediaRoute.deployment({ ...input, baseURL: baseURL ?? `https://${host}/api/v1` }, opts.auth)
const image = (id: string | ModelID) => AlibabaImages.model({ ...media, id })
const image = (id: string | ModelID, providerOptions?: ProviderOptions) =>
AlibabaImages.model({ ...media, id, providerOptions })
return { id, model: chat, chat, messages, responses, image, configure }
}
export const provider = { id, configure }
export const model: ProviderPackage.Definition<Settings, ChatOptionsInput>["model"] = (id, input) =>
fromSettings(input).chat(id)
configure(config(input)).chat(id)
export const messagesModel: ProviderPackage.Definition<
Settings<MessagesOptionsInput>,
MessagesOptionsInput
>["model"] = (id, input) => fromSettings(input).messages(id)
>["model"] = (id, input) => configure(config(input)).messages(id)
export const responsesModel: ProviderPackage.Definition<
Settings<ResponsesOptionsInput>,
ResponsesOptionsInput
>["model"] = (id, input) => fromSettings(input).responses(id)
>["model"] = (id, input) => configure(config(input)).responses(id)
export const imageModel = (id: string, settings: Settings) => {
const input = config(settings)
return configure(input).image(id, input.providerOptions)
}
function fromSettings(input: Settings<Config["providerOptions"]>) {
function config(input: Settings<Config["providerOptions"]>) {
const { body, ...rest } = input
return configure({
return {
...rest,
http: body === undefined ? undefined : { body },
providerOptions: Struct.omit(rest, ["apiKey", "baseURL", "headers", "region", "workspaceID"]),
})
}
}
export const webSearch = () => hostedTool("web_search", "Search the web with Alibaba's hosted search tool.")

View file

@ -0,0 +1,2 @@
export { imageModel as model } from "../alibaba.js"
export type { Settings } from "../alibaba.js"

View file

@ -21,18 +21,19 @@ export type Config = RouteDefaultsInput & {
readonly region?: string
/** Override the computed `https://bedrock-runtime.<region>.amazonaws.com` URL. */
readonly baseURL?: string
readonly providerOptions?: BedrockConverse.OptionsInput
}
export interface Settings extends ProviderPackage.Settings {
readonly apiKey?: string
readonly auth?: "bearer" | "sigv4"
readonly baseURL?: string
readonly credentials?: BedrockCredentials
readonly profile?: string
readonly region?: string
readonly topP?: number
readonly thinking?: BedrockConverse.OptionsInput["thinking"]
}
export type Settings = ProviderPackage.Settings &
BedrockConverse.OptionsInput & {
readonly apiKey?: string
readonly auth?: "bearer" | "sigv4"
readonly baseURL?: string
readonly credentials?: BedrockCredentials
readonly profile?: string
readonly region?: string
readonly topP?: number
}
export const routes = [BedrockConverse.route]
const bedrockBaseURL = (region: string) => `https://bedrock-runtime.${region}.amazonaws.com`
@ -57,22 +58,25 @@ export const configure = (input: Config = {}) => {
const route = configuredRoute(input)
return {
id,
model: (modelID: string | ModelID) => route.model({ id: modelID }),
model: (modelID: string | ModelID) => route.model<BedrockConverse.OptionsInput>({ id: modelID }),
configure,
}
}
export const provider = configure()
export const model: ProviderPackage.Definition<Settings>["model"] = (modelID, settings) =>
export const model: ProviderPackage.Definition<Settings, BedrockConverse.OptionsInput>["model"] = (
modelID,
{ apiKey, auth, baseURL, credentials, profile, region, topP, headers, body, ...providerOptions },
) =>
configure({
apiKey: settings.apiKey,
auth: settings.auth,
baseURL: settings.baseURL,
credentials: settings.credentials,
generation: settings.topP === undefined ? undefined : { topP: settings.topP },
headers: settings.headers === undefined ? undefined : { ...settings.headers },
http: settings.body === undefined ? undefined : { body: { ...settings.body } },
providerOptions: settings.thinking === undefined ? undefined : { thinking: settings.thinking },
profile: settings.profile,
region: settings.region,
apiKey,
auth,
baseURL,
credentials,
generation: topP === undefined ? undefined : { topP },
headers: headers === undefined ? undefined : { ...headers },
http: body === undefined ? undefined : { body: { ...body } },
providerOptions,
profile,
region,
}).model(modelID)

Some files were not shown because too many files have changed in this diff Show more