diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c6dfb0ebda4..fb542222c0d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -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 diff --git a/.github/publish-python-sdk.yml b/.github/publish-python-sdk.yml deleted file mode 100644 index 151ecb9944b..00000000000 --- a/.github/publish-python-sdk.yml +++ /dev/null @@ -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 diff --git a/.github/release/download/action.yml b/.github/release/download/action.yml new file mode 100644 index 00000000000..de159d799b1 --- /dev/null +++ b/.github/release/download/action.yml @@ -0,0 +1,21 @@ +name: Download release artifacts +description: Downloads artifacts into $RUNNER_TEMP/in/ 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 }} diff --git a/packages/cli/script/entitlements.plist b/.github/release/entitlements/cli.plist similarity index 100% rename from packages/cli/script/entitlements.plist rename to .github/release/entitlements/cli.plist diff --git a/packages/desktop/resources/entitlements.cli.plist b/.github/release/entitlements/desktop-cli.plist similarity index 100% rename from packages/desktop/resources/entitlements.cli.plist rename to .github/release/entitlements/desktop-cli.plist diff --git a/packages/desktop/resources/entitlements.plist b/.github/release/entitlements/desktop.plist similarity index 100% rename from packages/desktop/resources/entitlements.plist rename to .github/release/entitlements/desktop.plist diff --git a/.github/release/lib.sh b/.github/release/lib.sh new file mode 100644 index 00000000000..de0d95b0f48 --- /dev/null +++ b/.github/release/lib.sh @@ -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// 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 . +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 [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 +} diff --git a/.github/release/plan-release.sh b/.github/release/plan-release.sh new file mode 100755 index 00000000000..3c069a7508f --- /dev/null +++ b/.github/release/plan-release.sh @@ -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- 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- desktop only +# pull_request -> pr 0.0.0-pr- 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" diff --git a/.github/release/publish-aur.sh b/.github/release/publish-aur.sh new file mode 100755 index 00000000000..3d1a8ec1912 --- /dev/null +++ b/.github/release/publish-aur.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# publish-aur.sh : 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"}' diff --git a/.github/release/publish-cli.sh b/.github/release/publish-cli.sh new file mode 100755 index 00000000000..de398ebbc2f --- /dev/null +++ b/.github/release/publish-cli.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# publish-cli.sh : 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 diff --git a/.github/release/publish-desktop.sh b/.github/release/publish-desktop.sh new file mode 100755 index 00000000000..75aa5a12c93 --- /dev/null +++ b/.github/release/publish-desktop.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# publish-desktop.sh +# : 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}')" diff --git a/.github/release/publish-docker.sh b/.github/release/publish-docker.sh new file mode 100755 index 00000000000..d6702fde29e --- /dev/null +++ b/.github/release/publish-docker.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# publish-docker.sh : pushes the multi-arch OCI image to ghcr.io/anomalyco/opencode: +# 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" diff --git a/.github/release/publish-github-release.sh b/.github/release/publish-github-release.sh new file mode 100755 index 00000000000..f57963dd448 --- /dev/null +++ b/.github/release/publish-github-release.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# publish-github-release.sh ...: attaches the CLI archives and desktop builds in the given artifact dirs, plus +# a SHA256SUMS, to the v 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 diff --git a/.github/release/publish-homebrew.sh b/.github/release/publish-homebrew.sh new file mode 100755 index 00000000000..59f39bdc77a --- /dev/null +++ b/.github/release/publish-homebrew.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# publish-homebrew.sh : 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"}' diff --git a/.github/release/publish-npm.sh b/.github/release/publish-npm.sh new file mode 100755 index 00000000000..ed63a4a0aa4 --- /dev/null +++ b/.github/release/publish-npm.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# publish-npm.sh ...: 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" diff --git a/.github/release/publish-version-pr.sh b/.github/release/publish-version-pr.sh new file mode 100755 index 00000000000..e1a37776641 --- /dev/null +++ b/.github/release/publish-version-pr.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# publish-version-pr.sh : 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" diff --git a/.github/release/render-aur.sh b/.github/release/render-aur.sh new file mode 100755 index 00000000000..7b6818b20df --- /dev/null +++ b/.github/release/render-aur.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# render-aur.sh : 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" < +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" < : 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" < : 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"/*/* diff --git a/.github/release/repack-windows.sh b/.github/release/repack-windows.sh new file mode 100755 index 00000000000..4c9b9284e64 --- /dev/null +++ b/.github/release/repack-windows.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# repack-windows.sh : checks every signature in , then writes the signed CLI back +# into npm tarballs and opencode-.zip archives in . +. "$(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 diff --git a/.github/release/sign-cli-macos.sh b/.github/release/sign-cli-macos.sh new file mode 100755 index 00000000000..34dfb603d10 --- /dev/null +++ b/.github/release/sign-cli-macos.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# sign-cli-macos.sh : 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-.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 diff --git a/.github/release/sign-desktop-macos.sh b/.github/release/sign-desktop-macos.sh new file mode 100755 index 00000000000..6d8cfe59465 --- /dev/null +++ b/.github/release/sign-desktop-macos.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# sign-desktop-macos.sh ...: signs each unsigned .app inside-out with hardened runtime, +# notarizes them in one submission, staples them, and only then builds opencode-desktop-mac-.{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 diff --git a/.github/release/tag-release.sh b/.github/release/tag-release.sh new file mode 100755 index 00000000000..29da48314ba --- /dev/null +++ b/.github/release/tag-release.sh @@ -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 tag at it. Writes sha= 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" diff --git a/.github/release/unpack-windows.sh b/.github/release/unpack-windows.sh new file mode 100755 index 00000000000..afb760026f8 --- /dev/null +++ b/.github/release/unpack-windows.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# unpack-windows.sh : lays out what the signing action signs in : +# cli//package from the Windows CLI npm tarballs, and desktop-/ 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 diff --git a/.github/release/upload/action.yml b/.github/release/upload/action.yml new file mode 100644 index 00000000000..bd03680f3a1 --- /dev/null +++ b/.github/release/upload/action.yml @@ -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, - + 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 diff --git a/.github/release/verify-artifacts.sh b/.github/release/verify-artifacts.sh new file mode 100755 index 00000000000..aeba5091f80 --- /dev/null +++ b/.github/release/verify-artifacts.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# verify-artifacts.sh : checks every artifact downloaded into / 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 diff --git a/.github/release/verify-signatures-windows.sh b/.github/release/verify-signatures-windows.sh new file mode 100755 index 00000000000..14d554df09b --- /dev/null +++ b/.github/release/verify-signatures-windows.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# verify-signatures-windows.sh : fails unless every .exe and .node under 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\" +" diff --git a/.github/release/write-checksums.sh b/.github/release/write-checksums.sh new file mode 100755 index 00000000000..b7a44278a29 --- /dev/null +++ b/.github/release/write-checksums.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# write-checksums.sh : writes /SHA256SUMS for every file under 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 diff --git a/.github/workflows/bot-docs-locale.yml b/.github/workflows/bot-docs-locale.yml index 82e81de204b..c90ad57cd89 100644 --- a/.github/workflows/bot-docs-locale.yml +++ b/.github/workflows/bot-docs-locale.yml @@ -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: diff --git a/.github/workflows/bot-nix-hashes.yml b/.github/workflows/bot-nix-hashes.yml index e63309e4674..24af010e506 100644 --- a/.github/workflows/bot-nix-hashes.yml +++ b/.github/workflows/bot-nix-hashes.yml @@ -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 diff --git a/.github/workflows/check-test.yml b/.github/workflows/check-test.yml index 0daa9fd3c4b..71e1b4f83ed 100644 --- a/.github/workflows/check-test.yml +++ b/.github/workflows/check-test.yml @@ -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' diff --git a/.github/workflows/deploy-changelog.yml b/.github/workflows/deploy-changelog.yml index 66ec7be03ad..7956e1526fa 100644 --- a/.github/workflows/deploy-changelog.yml +++ b/.github/workflows/deploy-changelog.yml @@ -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 diff --git a/.github/workflows/deploy-files.yml b/.github/workflows/deploy-files.yml index 34e292821b6..4d903aec525 100644 --- a/.github/workflows/deploy-files.yml +++ b/.github/workflows/deploy-files.yml @@ -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 diff --git a/.github/workflows/deploy-www.yml b/.github/workflows/deploy-www.yml index 8752fcadc99..3e768e92d2b 100644 --- a/.github/workflows/deploy-www.yml +++ b/.github/workflows/deploy-www.yml @@ -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 diff --git a/.github/workflows/notify-discord.yml b/.github/workflows/notify-discord.yml deleted file mode 100644 index 0b2b1cde051..00000000000 --- a/.github/workflows/notify-discord.yml +++ /dev/null @@ -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 }} diff --git a/.github/workflows/publish-vscode.yml b/.github/workflows/publish-vscode.yml deleted file mode 100644 index 547d4ace64a..00000000000 --- a/.github/workflows/publish-vscode.yml +++ /dev/null @@ -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 }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index f7254569866..00000000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -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--[.] 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 }} diff --git a/.github/workflows/release-dry-run.yml b/.github/workflows/release-dry-run.yml new file mode 100644 index 00000000000..7a35035e7e5 --- /dev/null +++ b/.github/workflows/release-dry-run.yml @@ -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. 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 }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000000..6ef2a560509 --- /dev/null +++ b/.github/workflows/release.yml @@ -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. 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 }} diff --git a/.opencode/skills/app-e2e-tests/SKILL.md b/.opencode/skills/app-e2e-tests/SKILL.md index 5bef2eafc2a..4a63ca2f45f 100644 --- a/.opencode/skills/app-e2e-tests/SKILL.md +++ b/.opencode/skills/app-e2e-tests/SKILL.md @@ -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=/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=/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 -n playwright-windows-app-2-1 -D `. Artifacts are named `playwright---` (`test.yml:301-314`). App e2e results are in `/app/e2e/`. +- **Download:** `gh run download -n playwright-windows-app-2-1 -D `. Artifacts are named `playwright---` (`check-test.yml:314-327`). App e2e results are in `/app/e2e/`. - **In CI, the failing first attempt has no trace and no video** (`playwright.config.ts:62-65`). - `test-results/-/` holds `error-context.md` (the aria snapshot at the failure) and `test-failed-1.png`. - `--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. diff --git a/.opencode/skills/component-tests/SKILL.md b/.opencode/skills/component-tests/SKILL.md index d675fb27c63..032b7d225ed 100644 --- a/.opencode/skills/component-tests/SKILL.md +++ b/.opencode/skills/component-tests/SKILL.md @@ -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 (, session-ui-components)` and `e2e (, 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 (, session-ui-components)` and `e2e (, app-components)`. - If CI skipped them, report your local cold run in the PR. ## When CI flakes -- **Download the artifact.** Run `gh run download -n playwright---components- -D ` (`test.yml:301-314`). Results are in `/session-ui/component-tests/` or `/app/component-tests/`. Only the first retry has a trace and, in CI, a video: `test-results/-components-retry1/`. +- **Download the artifact.** Run `gh run download -n playwright---components- -D ` (`check-test.yml:314-327`). Results are in `/session-ui/component-tests/` or `/app/component-tests/`. Only the first retry has a trace and, in CI, a video: `test-results/-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; diff --git a/.opencode/skills/tui-tests/SKILL.md b/.opencode/skills/tui-tests/SKILL.md index 5c74851333e..6b2f45c01b0 100644 --- a/.opencode/skills/tui-tests/SKILL.md +++ b/.opencode/skills/tui-tests/SKILL.md @@ -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. diff --git a/.opencode/skills/unit-tests/SKILL.md b/.opencode/skills/unit-tests/SKILL.md index dc5d8eba85a..6e8d967acf9 100644 --- a/.opencode/skills/unit-tests/SKILL.md +++ b/.opencode/skills/unit-tests/SKILL.md @@ -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/#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) [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 `; `--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. diff --git a/README.ar.md b/README.ar.md index c7d0a701637..79b79db0bb1 100644 --- a/README.ar.md +++ b/README.ar.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.bn.md b/README.bn.md index 3b641fc8144..f684723d14d 100644 --- a/README.bn.md +++ b/README.bn.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.br.md b/README.br.md index c4baaa37edd..dd0ad403b7a 100644 --- a/README.br.md +++ b/README.br.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.bs.md b/README.bs.md index 901df6f95a8..a5bc0324a94 100644 --- a/README.bs.md +++ b/README.bs.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.da.md b/README.da.md index 8ef13be7c9d..a4596c025c5 100644 --- a/README.da.md +++ b/README.da.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.de.md b/README.de.md index e0e46026654..042c2b42815 100644 --- a/README.de.md +++ b/README.de.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.es.md b/README.es.md index c9ac6192af9..129619b7a04 100644 --- a/README.es.md +++ b/README.es.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.fr.md b/README.fr.md index 1b0d822f0a9..cab6c14b15f 100644 --- a/README.fr.md +++ b/README.fr.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.gr.md b/README.gr.md index 1874b0669e1..4eb428ba745 100644 --- a/README.gr.md +++ b/README.gr.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.it.md b/README.it.md index 3800448ee90..6d34ba64292 100644 --- a/README.it.md +++ b/README.it.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.ja.md b/README.ja.md index f99f4881ec2..751fc8714c5 100644 --- a/README.ja.md +++ b/README.ja.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.ko.md b/README.ko.md index c91395f2bd1..0d69b9eed6d 100644 --- a/README.ko.md +++ b/README.ko.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.md b/README.md index a8551f97c57..60adea0e397 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.no.md b/README.no.md index 66f219329b9..68b557df3b5 100644 --- a/README.no.md +++ b/README.no.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.pl.md b/README.pl.md index 0678de6068d..0618af87d61 100644 --- a/README.pl.md +++ b/README.pl.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.ru.md b/README.ru.md index a5ab7104944..e369c7f47de 100644 --- a/README.ru.md +++ b/README.ru.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.th.md b/README.th.md index f06abc17dc4..f1d7a6f356c 100644 --- a/README.th.md +++ b/README.th.md @@ -11,7 +11,7 @@

Discord npm - สถานะการสร้าง + สถานะการสร้าง

diff --git a/README.tr.md b/README.tr.md index ef084543fef..e009219bacc 100644 --- a/README.tr.md +++ b/README.tr.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.uk.md b/README.uk.md index 32852565a8f..6b38e51242f 100644 --- a/README.uk.md +++ b/README.uk.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.vi.md b/README.vi.md index 5295504cd84..d25173ac007 100644 --- a/README.vi.md +++ b/README.vi.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.zh.md b/README.zh.md index fbdfb9d3ed0..2f364601e4a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.zht.md b/README.zht.md index a22b6159e22..be90cb3cba6 100644 --- a/README.zht.md +++ b/README.zht.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/V2_HTTP_API_AUDIT.md b/V2_HTTP_API_AUDIT.md deleted file mode 100644 index ab850f81f39..00000000000 --- a/V2_HTTP_API_AUDIT.md +++ /dev/null @@ -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. | diff --git a/bun.lock b/bun.lock index 6343caf5fe6..061f7188b61 100644 --- a/bun.lock +++ b/bun.lock @@ -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=="], diff --git a/install b/install index 5e8a3cd4cfb..84f97f5467e 100755 --- a/install +++ b/install @@ -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" diff --git a/nix/desktop.nix b/nix/desktop.nix index 73a4e806fe2..35ddfd03c53 100644 --- a/nix/desktop.nix +++ b/nix/desktop.nix @@ -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. diff --git a/package.json b/package.json index 23459b28019..47fc91f7faa 100644 --- a/package.json +++ b/package.json @@ -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:", diff --git a/packages/ai/README.md b/packages/ai/README.md index 6c46aea2574..ebfb9ce4ed4 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -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 (`` 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 `) - `test/provider/*.test.ts` — fixture-first protocol tests; `*.recorded.test.ts` files cover live cassettes diff --git a/packages/ai/example/tutorial.ts b/packages/ai/example/tutorial.ts index 0dd9269b8a4..216903cf810 100644 --- a/packages/ai/example/tutorial.ts +++ b/packages/ai/example/tutorial.ts @@ -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({ 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> = { + 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)), +) diff --git a/packages/ai/package.json b/packages/ai/package.json index c08bf3a246d..8964c6af50c 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -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" } } diff --git a/packages/ai/script/pack.ts b/packages/ai/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/ai/script/pack.ts @@ -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, "..")) diff --git a/packages/ai/script/publish.ts b/packages/ai/script/publish.ts deleted file mode 100644 index 77eca8806a6..00000000000 --- a/packages/ai/script/publish.ts +++ /dev/null @@ -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 -} -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) - } -} diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index b00d8cc2480..565da406917 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -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 diff --git a/packages/ai/src/decision.ts b/packages/ai/src/decision.ts index 83009bd2c0b..9417b541827 100644 --- a/packages/ai/src/decision.ts +++ b/packages/ai/src/decision.ts @@ -155,10 +155,11 @@ export interface DecisionModelRoute("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 { readonly route: DecisionModelRoute 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) { this.id = input.id @@ -183,6 +186,7 @@ export class DecisionModel { this.route = input.route this.http = input.http this.compatibility = input.compatibility + this.providerOptions = input.providerOptions } static make(input: DecisionModel.MakeInput) { @@ -201,6 +205,7 @@ export namespace DecisionModel { readonly route: DecisionModelRoute readonly http?: HttpOptions readonly compatibility?: DecisionModelCompatibility + readonly providerOptions?: ProviderOptions } export interface MakeInput diff --git a/packages/ai/src/effect.ts b/packages/ai/src/effect.ts index 79f1685eebf..325c02ebcc1 100644 --- a/packages/ai/src/effect.ts +++ b/packages/ai/src/effect.ts @@ -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, diff --git a/packages/ai/src/experimental.ts b/packages/ai/src/experimental.ts index 01688ab0bb1..c54af26af6d 100644 --- a/packages/ai/src/experimental.ts +++ b/packages/ai/src/experimental.ts @@ -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, diff --git a/packages/ai/src/experimental/cloudflare-run-extraction.ts b/packages/ai/src/experimental/cloudflare-run-extraction.ts new file mode 100644 index 00000000000..0e2ca356c8c --- /dev/null +++ b/packages/ai/src/experimental/cloudflare-run-extraction.ts @@ -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(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(({ request }) => `/${request.model.id}`, { + baseURL: input.baseURL, + }), + auth: input.auth, + headers: input.headers, + }), + }) + +export const CloudflareRunExtraction = { protocol, model } as const diff --git a/packages/ai/src/experimental/extraction.ts b/packages/ai/src/experimental/extraction.ts new file mode 100644 index 00000000000..03e86954efc --- /dev/null +++ b/packages/ai/src/experimental/extraction.ts @@ -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: 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["type"] extends keyof Answers + ? Answers[Field["type"]]["Type"] + : Readonly> + +/** One answer per field, keyed by field name. */ +export type ExtractionAnswersFor = { + readonly [Name in keyof Fields]: ExtractionAnswerFor +} + +// --------------------------------------------------------------------------- +// 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 } +export type ExtractionFields = Readonly> + +// --------------------------------------------------------------------------- +// Model +// --------------------------------------------------------------------------- + +export type ExtractionOptions = MediaModel.Options + +export type ExtractionRoute = MediaRoute.InlineRoute + +export class ExtractionModel extends MediaModel< + ExtractionRoute, + Options +> { + declare protected readonly _ExtractionModel: void +} + +export type ExtractionModelOptions = Model extends ExtractionModel ? Options : never + +// --------------------------------------------------------------------------- +// Request and response +// --------------------------------------------------------------------------- + +export class ExtractionRequest extends Schema.Class("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 & { + readonly model: ExtractionModel + 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> + readonly http?: HttpOptions.Input +} + +export class ExtractionResponse extends Schema.Class("Extraction.Response")({ + answers: Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown)), + usage: Schema.optional(Usage), + providerMetadata: Schema.optional(ProviderMetadata), +}) {} + +export type ExtractionResponseFor = Omit & { + readonly answers: ExtractionAnswersFor +} + +// --------------------------------------------------------------------------- +// Call API +// --------------------------------------------------------------------------- + +export function request( + input: ExtractionRequestInput, +): ExtractionRequestFor, 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( + input: ExtractionRequestInput, +): Effect.Effect, AIError, RequestExecutor.Service> +export function generate(input: ExtractionRequest): Effect.Effect +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 diff --git a/packages/ai/src/image.ts b/packages/ai/src/image.ts index 84e5eb041ef..cd456563875 100644 --- a/packages/ai/src/image.ts +++ b/packages/ai/src/image.ts @@ -38,6 +38,7 @@ export class ImageModel extends Med id: input.id, provider: route.protocol.provider, http: input.http, + providerOptions: input.providerOptions, route: composeRoute(route, input, collectResponse) as ImageRoute, }) } diff --git a/packages/ai/src/media-model.ts b/packages/ai/src/media-model.ts index 8d611564d74..ea4f0ecee21 100644 --- a/packages/ai/src/media-model.ts +++ b/packages/ai/src/media-model.ts @@ -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 { 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) { 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. */ diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts index 3a461cd94b5..1a6bb5af33b 100644 --- a/packages/ai/src/protocols/anthropic-messages.ts +++ b/packages/ai/src/protocols/anthropic-messages.ts @@ -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): ProviderMetadata => ({ [key]: metadata }) diff --git a/packages/ai/src/protocols/bedrock-converse.ts b/packages/ai/src/protocols/bedrock-converse.ts index 01d4bd9dfdd..e86a77334ae 100644 --- a/packages/ai/src/protocols/bedrock-converse.ts +++ b/packages/ai/src/protocols/bedrock-converse.ts @@ -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 @@ -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> | 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, } }) diff --git a/packages/ai/src/protocols/bedrock-event-stream.ts b/packages/ai/src/protocols/bedrock-event-stream.ts index 6a385b442be..f730f115a34 100644 --- a/packages/ai/src/protocols/bedrock-event-stream.ts +++ b/packages/ai/src/protocols/bedrock-event-stream.ts @@ -135,6 +135,7 @@ const consumeFrames = (route: string) => (state: FrameBufferState, input: FrameI export const framing = (route: string): Framing.Definition => ({ id: "aws-event-stream", body: (frame) => frame.rawBody, + raw: ({ rawBody: _, ...event }) => event, frame: (bytes) => bytes.pipe( Stream.map((bytes): FrameInput => ({ _tag: "Chunk", bytes })), diff --git a/packages/ai/src/protocols/cloudflare-run-decisions.ts b/packages/ai/src/protocols/cloudflare-run-decisions.ts index 2d1a93cbf96..c806029ac4f 100644 --- a/packages/ai/src/protocols/cloudflare-run-decisions.ts +++ b/packages/ai/src/protocols/cloudflare-run-decisions.ts @@ -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) => diff --git a/packages/ai/src/protocols/meta-messages.ts b/packages/ai/src/protocols/meta-messages.ts index 867c887c0f7..d5b2f5ef0eb 100644 --- a/packages/ai/src/protocols/meta-messages.ts +++ b/packages/ai/src/protocols/meta-messages.ts @@ -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, diff --git a/packages/ai/src/protocols/openai-chat.ts b/packages/ai/src/protocols/openai-chat.ts index 5c907c054db..6e651c5a845 100644 --- a/packages/ai/src/protocols/openai-chat.ts +++ b/packages/ai/src/protocols/openai-chat.ts @@ -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 diff --git a/packages/ai/src/protocols/openai-responses.ts b/packages/ai/src/protocols/openai-responses.ts index 42c598a3db8..542e9b68fb7 100644 --- a/packages/ai/src/protocols/openai-responses.ts +++ b/packages/ai/src/protocols/openai-responses.ts @@ -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: { diff --git a/packages/ai/src/protocols/system-one.ts b/packages/ai/src/protocols/system-one.ts index da9000be9cc..fd4b9382bbc 100644 --- a/packages/ai/src/protocols/system-one.ts +++ b/packages/ai/src/protocols/system-one.ts @@ -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 | "messages" +/** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */ +type MediaInput = NonNullable | "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 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) => ] 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") diff --git a/packages/ai/src/protocols/utils/bedrock-cache.ts b/packages/ai/src/protocols/utils/bedrock-cache.ts index 7330efc36b1..b5695b24b97 100644 --- a/packages/ai/src/protocols/utils/bedrock-cache.ts +++ b/packages/ai/src/protocols/utils/bedrock-cache.ts @@ -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 @@ -44,9 +44,6 @@ export const breakpoints = (model: LLMRequest["model"]) => { } export type Breakpoints = ReturnType -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" diff --git a/packages/ai/src/protocols/utils/cache.ts b/packages/ai/src/protocols/utils/cache.ts index 45cbde48cb6..bc5052f6ff0 100644 --- a/packages/ai/src/protocols/utils/cache.ts +++ b/packages/ai/src/protocols/utils/cache.ts @@ -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 } } +} diff --git a/packages/ai/src/protocols/utils/gemini-json-schema.ts b/packages/ai/src/protocols/utils/gemini-json-schema.ts index d9af7870a9d..b5d491d148b 100644 --- a/packages/ai/src/protocols/utils/gemini-json-schema.ts +++ b/packages/ai/src/protocols/utils/gemini-json-schema.ts @@ -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, map: (value: unknown, key: string) => unknown) => +export const mapValues = (record: Record, map: (value: unknown, key: string) => unknown) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value, key)])) const normalizeNode = (schema: unknown): unknown => { diff --git a/packages/ai/src/protocols/utils/tool-schema.ts b/packages/ai/src/protocols/utils/tool-schema.ts index b2525eb93d5..05af2e48665 100644 --- a/packages/ai/src/protocols/utils/tool-schema.ts +++ b/packages/ai/src/protocols/utils/tool-schema.ts @@ -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) => { 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)]] diff --git a/packages/ai/src/protocols/venice-chat.ts b/packages/ai/src/protocols/venice-chat.ts index 660611700be..3fe448b1f9c 100644 --- a/packages/ai/src/protocols/venice-chat.ts +++ b/packages/ai/src/protocols/venice-chat.ts @@ -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, diff --git a/packages/ai/src/provider.ts b/packages/ai/src/provider.ts deleted file mode 100644 index 265896cbcf3..00000000000 --- a/packages/ai/src/provider.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { LanguageModel, ModelID, ProviderID } from "./schema/index.js" - -export type LanguageModelOptions = Pick - -/** - * 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 = ( - id: string | ModelID, - options?: Options, -) => LanguageModel - -type AnyLanguageModelFactory = (...args: never[]) => LanguageModel - -export interface Definition { - readonly id: ProviderID - readonly model: Factory - readonly apis?: Record -} - -type DefinitionShape = { - readonly id: ProviderID - readonly model: (...args: never[]) => LanguageModel - readonly apis?: Record LanguageModel> -} - -type NoExtraFields = Input & Record, never> - -export const make = ( - definition: NoExtraFields, -) => definition - -export * as Provider from "./provider.js" diff --git a/packages/ai/src/providers/alibaba.ts b/packages/ai/src/providers/alibaba.ts index 955d016006f..0d1a0c40343 100644 --- a/packages/ai/src/providers/alibaba.ts +++ b/packages/ai/src/providers/alibaba.ts @@ -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({ id, compatibility: { requireSignature: false } }) const responses = (id: string | ModelID) => responsesRoute.with(common).model({ 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["model"] = (id, input) => - fromSettings(input).chat(id) + configure(config(input)).chat(id) export const messagesModel: ProviderPackage.Definition< Settings, MessagesOptionsInput ->["model"] = (id, input) => fromSettings(input).messages(id) +>["model"] = (id, input) => configure(config(input)).messages(id) export const responsesModel: ProviderPackage.Definition< Settings, 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) { +function config(input: Settings) { 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.") diff --git a/packages/ai/src/providers/alibaba/images.ts b/packages/ai/src/providers/alibaba/images.ts new file mode 100644 index 00000000000..ffaeba45754 --- /dev/null +++ b/packages/ai/src/providers/alibaba/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../alibaba.js" +export type { Settings } from "../alibaba.js" diff --git a/packages/ai/src/providers/amazon-bedrock.ts b/packages/ai/src/providers/amazon-bedrock.ts index 5f35fc4f33d..4d7ea859533 100644 --- a/packages/ai/src/providers/amazon-bedrock.ts +++ b/packages/ai/src/providers/amazon-bedrock.ts @@ -21,18 +21,19 @@ export type Config = RouteDefaultsInput & { readonly region?: string /** Override the computed `https://bedrock-runtime..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({ id: modelID }), configure, } } export const provider = configure() -export const model: ProviderPackage.Definition["model"] = (modelID, settings) => +export const model: ProviderPackage.Definition["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) diff --git a/packages/ai/src/providers/azure.ts b/packages/ai/src/providers/azure.ts index aa3ae6b6328..025ae57aa26 100644 --- a/packages/ai/src/providers/azure.ts +++ b/packages/ai/src/providers/azure.ts @@ -3,7 +3,16 @@ import { type AtLeastOne, type ProviderAuthOption } from "../route/auth-options. import type { Route, RouteDefaultsInput, CompactionOperations } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import type { ProviderPackage } from "../provider-package.js" -import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js" +import { MediaRoute } from "../route/media.js" +import { + HttpOptions, + ProviderConfigurationError, + ProviderID, + mergeHttpOptions, + type ModelID, + type ProviderOptions, +} from "../schema/index.js" +import { OpenAIImages } from "../protocols/openai-images.js" import * as OpenAIChat from "../protocols/openai-chat.js" import * as OpenAIResponses from "../protocols/openai-responses.js" import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options.js" @@ -131,11 +140,27 @@ export const configure = (input: Config) => { .with(withOpenAIOptions(modelID, modelDefaults)) .model({ id: modelID, compatibility: { supportsPromptCacheKey: true } }) + const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => { + const target = endpoint(input, modelID) + const media = MediaRoute.deployment({ ...input, baseURL: target.baseURL }, auth(input)) + return OpenAIImages.model({ + ...media, + id: modelID, + provider: id, + providerOptions, + http: mergeHttpOptions( + media.http, + target.query === undefined ? undefined : new HttpOptions({ query: target.query }), + ), + }) + } + return { id, model: responses, responses, chat, + image, configure, } } @@ -179,4 +204,8 @@ export const chatModel: ProviderPackage.Definition configure(config(settings)).chat(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} export const model = responsesModel diff --git a/packages/ai/src/providers/azure/images.ts b/packages/ai/src/providers/azure/images.ts new file mode 100644 index 00000000000..b2567121f0a --- /dev/null +++ b/packages/ai/src/providers/azure/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../azure.js" +export type { Settings } from "../azure.js" diff --git a/packages/ai/src/providers/baseten.ts b/packages/ai/src/providers/baseten.ts index e5a80243976..d6e9b5bdcb5 100644 --- a/packages/ai/src/providers/baseten.ts +++ b/packages/ai/src/providers/baseten.ts @@ -6,7 +6,7 @@ import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { Route, type RouteDefaultsInput } from "../route/client.js" import { DecisionRoute } from "../route/decision.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" export const id = ProviderID.make("baseten") @@ -47,7 +47,9 @@ const decisionProtocol = DecisionRoute.protocol({ id: "baseten-system-one", body: { from: (request) => - SystemOne.encodeBody(request, "messages").pipe(Effect.map((body) => ({ ...body, model: request.model.id }))), + SystemOne.encodeBody(request, "state.messages").pipe( + Effect.map((body) => ({ ...body, model: request.model.id })), + ), }, }) @@ -69,7 +71,8 @@ export const configure = (input: LanguageModelOptions = {}) => { headers: input.headers, http: input.http, }) - const decision = (modelID: string | ModelID) => decisionRoute.model({ id: modelID }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + decisionRoute.model({ id: modelID, providerOptions }) return { id, model: (modelID: string | ModelID) => configured.model({ id: modelID }), @@ -81,16 +84,21 @@ export const configure = (input: LanguageModelOptions = {}) => { export const provider = configure() export const decision = provider.decision -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { apiKey, baseURL, body, headers, ...providerOptions }, -) => - configure({ +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, providerOptions, - }).model(modelID) + } +} export * as Baseten from "./baseten.js" diff --git a/packages/ai/src/providers/baseten/decisions.ts b/packages/ai/src/providers/baseten/decisions.ts new file mode 100644 index 00000000000..664c78e7cb0 --- /dev/null +++ b/packages/ai/src/providers/baseten/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../baseten.js" +export type { Settings } from "../baseten.js" diff --git a/packages/ai/src/providers/cloudflare-ai-gateway.ts b/packages/ai/src/providers/cloudflare-ai-gateway.ts index 159cafb5d6f..dd7a6700656 100644 --- a/packages/ai/src/providers/cloudflare-ai-gateway.ts +++ b/packages/ai/src/providers/cloudflare-ai-gateway.ts @@ -6,7 +6,7 @@ import { Auth } from "../route/auth.js" import { Endpoint } from "../route/endpoint.js" import type { AtLeastOne, ProviderAuthOption } from "../route/auth-options.js" import type { RouteDefaultsInput } from "../route/client.js" -import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js" +import { ProviderConfigurationError, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" import { encodeJson } from "../utils/json.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" @@ -132,7 +132,7 @@ export const configure = (input: LanguageModelOptions) => { const messages = messagesRoute.with(passthrough("anthropic/v1")) const chat = route.with(rest) // The Run API base is derived per call so a chat-only configuration without an account still constructs. - const decision = (value: string | ModelID) => + const decision = (value: string | ModelID, providerOptions?: ProviderOptions) => CloudflareRunDecisions.route .with({ provider: id, @@ -141,7 +141,7 @@ export const configure = (input: LanguageModelOptions) => { headers: rest.headers, http: input.http, }) - .model({ id: value }) + .model({ id: value, providerOptions }) return { id, model: (value: string | ModelID) => { @@ -162,26 +162,30 @@ export const configure = (input: LanguageModelOptions) => { export const provider = { id, configure } -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { - accountId, - apiKey, - baseURL: configuredBaseURL, - body, - cacheKey, - cacheTtl, - collectLog, - gatewayApiKey, - gatewayId, - headers, - metadata, - skipCache, - ...providerOptions - }, -) => { +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} + +function config({ + accountId, + apiKey, + baseURL: configuredBaseURL, + body, + cacheKey, + cacheTtl, + collectLog, + gatewayApiKey, + gatewayId, + headers, + metadata, + skipCache, + ...providerOptions +}: Settings) { const connection = configuredBaseURL === undefined ? { accountId: accountId ?? "" } : { baseURL: configuredBaseURL } - return configure({ + return { ...connection, apiKey, cacheKey, @@ -194,7 +198,7 @@ export const model: ProviderPackage.Definition { const auth = AuthOptions.bearer(input, authEnvVars) const configured = route.with({ ...defaults, endpoint: { baseURL: baseURL(input) }, auth }) // The Run API base is derived per call so a chat-only configuration without an account still constructs. - const decision = (modelID: string | ModelID) => + const runDeployment = () => MediaRoute.deployment({ ...input, baseURL: runBaseURL(input) }, auth) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => CloudflareRunDecisions.route .with({ provider: id, @@ -77,31 +79,42 @@ export const configure = (input: LanguageModelOptions) => { headers: input.headers, http: input.http, }) - .model({ id: modelID }) + .model({ id: modelID, providerOptions }) return { id, model: (modelID: string | ModelID) => configured.model({ id: modelID }), decision, - image: (modelID: string | ModelID) => - CloudflareWorkersAIImages.model({ - ...MediaRoute.deployment({ ...input, baseURL: runBaseURL(input) }, auth), - id: modelID, - }), + image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + CloudflareWorkersAIImages.model({ ...runDeployment(), id: modelID, providerOptions }), + experimental: { + extraction: (modelID: string | ModelID) => CloudflareRunExtraction.model({ ...runDeployment(), id: modelID }), + }, configure, } } export const provider = { id, configure } -export const model: ProviderPackage.Definition["model"] = (modelID, settings) => { +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} + +function config(settings: Settings) { const { accountId: _, apiKey, baseURL: _url, body, headers, ...providerOptions } = settings - return configure({ + return { apiKey, baseURL: baseURL(settings), headers, http: body === undefined ? undefined : { body }, providerOptions, - }).model(modelID) + } } export * as CloudflareWorkersAI from "./cloudflare-workers-ai.js" diff --git a/packages/ai/src/providers/cloudflare-workers-ai/decisions.ts b/packages/ai/src/providers/cloudflare-workers-ai/decisions.ts new file mode 100644 index 00000000000..3c37970be18 --- /dev/null +++ b/packages/ai/src/providers/cloudflare-workers-ai/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../cloudflare-workers-ai.js" +export type { Settings } from "../cloudflare-workers-ai.js" diff --git a/packages/ai/src/providers/cloudflare-workers-ai/images.ts b/packages/ai/src/providers/cloudflare-workers-ai/images.ts new file mode 100644 index 00000000000..4faf2cf11a9 --- /dev/null +++ b/packages/ai/src/providers/cloudflare-workers-ai/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../cloudflare-workers-ai.js" +export type { Settings } from "../cloudflare-workers-ai.js" diff --git a/packages/ai/src/providers/digitalocean.ts b/packages/ai/src/providers/digitalocean.ts index cd4e5f4c935..61468cf84df 100644 --- a/packages/ai/src/providers/digitalocean.ts +++ b/packages/ai/src/providers/digitalocean.ts @@ -1,12 +1,14 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" +import { OpenAIImages } from "../protocols/openai-images.js" import { SystemOne } from "../protocols/system-one.js" import { cacheControl } from "../protocols/utils/cache.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { Route, type RouteDefaultsInput } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" +import { MediaRoute } from "../route/media.js" import { Protocol } from "../route/protocol.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" export const id = ProviderID.make("digitalocean") @@ -57,7 +59,11 @@ export const configure = (input: LanguageModelOptions = {}) => { headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers }, http: input.http, }) - const decision = (modelID: string | ModelID) => decisionRoute.model({ id: modelID }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + decisionRoute.model({ id: modelID, providerOptions }) + const media = MediaRoute.deployment({ ...input, baseURL: endpoint ?? baseURL }, auth) + const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions }) return { id, model: (modelID: string | ModelID) => @@ -67,6 +73,7 @@ export const configure = (input: LanguageModelOptions = {}) => { supportsPromptCacheKey: true, }, }), + image, decision, configure, } @@ -74,17 +81,27 @@ export const configure = (input: LanguageModelOptions = {}) => { export const provider = configure() export const decision = provider.decision +export const image = provider.image -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { apiKey, baseURL, body, headers, ...providerOptions }, -) => - configure({ +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: { body }, providerOptions, - }).model(modelID) + } +} export * as DigitalOcean from "./digitalocean.js" diff --git a/packages/ai/src/providers/digitalocean/decisions.ts b/packages/ai/src/providers/digitalocean/decisions.ts new file mode 100644 index 00000000000..8b1dd32dc1b --- /dev/null +++ b/packages/ai/src/providers/digitalocean/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../digitalocean.js" +export type { Settings } from "../digitalocean.js" diff --git a/packages/ai/src/providers/digitalocean/images.ts b/packages/ai/src/providers/digitalocean/images.ts new file mode 100644 index 00000000000..84848eae7bd --- /dev/null +++ b/packages/ai/src/providers/digitalocean/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../digitalocean.js" +export type { Settings } from "../digitalocean.js" diff --git a/packages/ai/src/providers/google-vertex.ts b/packages/ai/src/providers/google-vertex.ts index 622ec50ca5e..0d36ce9265d 100644 --- a/packages/ai/src/providers/google-vertex.ts +++ b/packages/ai/src/providers/google-vertex.ts @@ -1,11 +1,19 @@ import { Effect } from "effect" import type { ProviderPackage } from "../provider-package.js" import { Gemini } from "../protocols/gemini.js" +import { GoogleImages } from "../protocols/google-images.js" import { ProviderShared } from "../protocols/shared.js" import { Auth } from "../route/auth.js" import { Route, type RouteDefaultsInput } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderConfigurationError, ProviderID, type LLMRequest, type ModelID } from "../schema/index.js" +import { MediaRoute } from "../route/media.js" +import { + ProviderConfigurationError, + ProviderID, + type LLMRequest, + type ModelID, + type ProviderOptions, +} from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" export interface GeminiOptionsInput extends Gemini.OptionsInput { @@ -78,11 +86,15 @@ const configuredRoute = (input: Config, modelID: string | ModelID) => { accessToken: _accessToken, apiKey: _apiKey, auth: _auth, - baseURL, - location: inputLocation, - project: inputProject, + baseURL: _baseURL, + location: _location, + project: _project, ...rest } = input + return route.with({ ...rest, ...connection(input, modelID) }) +} + +const connection = (input: Config, modelID: string | ModelID) => { const apiKey = GoogleVertexShared.apiKey(input) const endpointModel = modelID.startsWith("endpoints/") if (apiKey !== undefined && endpointModel) @@ -90,18 +102,17 @@ const configuredRoute = (input: Config, modelID: string | ModelID) => { provider: id, message: "Google Vertex tuned models do not support Express Mode API keys", }) - const location = GoogleVertexShared.location(inputLocation) - const project = GoogleVertexShared.project(inputProject) - const endpoint = - baseURL ?? + const location = GoogleVertexShared.location(input.location) + const project = GoogleVertexShared.project(input.project) + const baseURL = + input.baseURL ?? (apiKey ? "https://aiplatform.googleapis.com/v1/publishers/google" : `https://${GoogleVertexShared.host(location)}/v1beta1/projects/${GoogleVertexShared.requireProject(project)}/locations/${location}${endpointModel ? "" : "/publishers/google"}`) - return route.with({ - ...rest, - endpoint: { baseURL: endpoint }, + return { + endpoint: { baseURL }, auth: apiKey === undefined ? GoogleVertexShared.oauth(input, project) : Auth.header("x-goog-api-key", apiKey), - }) + } } export const configure = (input: Config = {}) => { @@ -109,6 +120,14 @@ export const configure = (input: Config = {}) => { id, model: (modelID: string | ModelID) => configuredRoute(input, modelID).model({ id: modelID }), + image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => { + const target = connection(input, modelID) + return GoogleImages.model({ + ...MediaRoute.deployment({ ...input, baseURL: target.endpoint.baseURL }, target.auth), + id: modelID, + providerOptions, + }) + }, configure, } } @@ -117,16 +136,20 @@ export const provider = { id, configure, } -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { accessToken, apiKey, baseURL, body, headers, location, project, ...providerOptions }, -) => { +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} + +function config({ accessToken, apiKey, baseURL, body, headers, location, project, ...providerOptions }: Settings) { if (apiKey !== undefined && accessToken !== undefined) throw new ProviderConfigurationError({ provider: id, message: "Google Vertex apiKey cannot be combined with accessToken or auth", }) - return configure({ + return { ...(apiKey === undefined ? { accessToken: accessToken } : { apiKey: apiKey }), baseURL, headers, @@ -134,5 +157,5 @@ export const model: ProviderPackage.Definition { model: (modelID: string | ModelID) => route.model({ id: modelID }), interactions: (modelID: string | ModelID) => interactionsRoute(input).model({ id: modelID }), - image: (modelID: string | ModelID) => GoogleImages.model({ ...media, id: modelID }), + image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + GoogleImages.model({ ...media, id: modelID, providerOptions }), video: (modelID: string | ModelID) => GoogleVideo.model({ ...media, id: modelID }), speech: (modelID: string | ModelID) => GoogleSpeech.model({ ...media, id: modelID }), transcription: (modelID: string | ModelID) => GoogleTranscription.model({ ...media, id: modelID }), @@ -69,17 +70,22 @@ export const configure = (input: Config = {}) => { } export const provider = configure() -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { apiKey, baseURL, body, headers, ...providerOptions }, -) => - configure({ +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, providerOptions, - }).model(modelID) + } +} export const image = provider.image export const interactions = provider.interactions diff --git a/packages/ai/src/providers/google/images.ts b/packages/ai/src/providers/google/images.ts new file mode 100644 index 00000000000..dd33f4720cd --- /dev/null +++ b/packages/ai/src/providers/google/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../google.js" +export type { Settings } from "../google.js" diff --git a/packages/ai/src/providers/openai-compatible.ts b/packages/ai/src/providers/openai-compatible.ts index 40fa5d50848..c3db022c044 100644 --- a/packages/ai/src/providers/openai-compatible.ts +++ b/packages/ai/src/providers/openai-compatible.ts @@ -1,5 +1,7 @@ -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" import { OpenAICompatibleChat } from "../protocols/openai-compatible-chat.js" +import { OpenAIImages } from "../protocols/openai-images.js" +import { MediaRoute } from "../route/media.js" import type { RouteDefaultsInput } from "../route/client.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import type { ProviderPackage } from "../provider-package.js" @@ -26,15 +28,19 @@ export const routes = [OpenAICompatibleChat.route] export const configure = (input: GenericModelOptions) => { const provider = input.provider ?? "openai-compatible" const { provider: _, baseURL, apiKey: _apiKey, auth: _auth, ...rest } = input + const auth = AuthOptions.bearer(input, []) const route = OpenAICompatibleChat.route.with({ ...rest, provider, endpoint: { baseURL }, - auth: AuthOptions.bearer(input, []), + auth, }) + const media = MediaRoute.deployment(input, auth) return { id: ProviderID.make(provider), model: (modelID: string | ModelID) => route.model({ id: modelID }), + image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + OpenAIImages.model({ ...media, id: modelID, provider, providerOptions }), configure, } } @@ -44,17 +50,22 @@ export const provider = { configure, } -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { apiKey, baseURL, body, headers, provider, ...providerOptions }, -) => - configure({ +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, provider, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, provider, providerOptions, - }).model(modelID) + } +} export * as OpenAICompatible from "./openai-compatible.js" diff --git a/packages/ai/src/providers/openai-compatible/images.ts b/packages/ai/src/providers/openai-compatible/images.ts new file mode 100644 index 00000000000..4f54187e8f6 --- /dev/null +++ b/packages/ai/src/providers/openai-compatible/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../openai-compatible.js" +export type { Settings } from "../openai-compatible.js" diff --git a/packages/ai/src/providers/openai.ts b/packages/ai/src/providers/openai.ts index ea46da6194b..6298a007276 100644 --- a/packages/ai/src/providers/openai.ts +++ b/packages/ai/src/providers/openai.ts @@ -9,6 +9,7 @@ import { mergeHttpOptions, type ModelID, type OpenString, + type ProviderOptions, } from "../schema/index.js" import * as OpenAIChat from "../protocols/openai-chat.js" import * as OpenAIResponses from "../protocols/openai-responses.js" @@ -18,7 +19,7 @@ import { OpenAISpeech } from "../protocols/openai-speech.js" import { OpenAITranscription } from "../protocols/openai-transcription.js" import { OpenAIDecisions, type OptionsInput as OpenAIDecisionOptionsInput } from "../protocols/openai-decisions.js" -export type { OpenAIOptionsInput, OpenAIResponseIncludable } from "./openai-options.js" +export type { OpenAIOptionsInput, OpenAIResponseIncludable, OpenAIServiceTier } from "./openai-options.js" export type { OpenAIImageOptions } from "../protocols/openai-images.js" export type { OpenAISpeechOptions } from "../protocols/openai-speech.js" export type { OpenAITranscriptionOptions } from "../protocols/openai-transcription.js" @@ -115,7 +116,8 @@ export const configure = (input: Config = {}) => { input.queryParams === undefined ? undefined : new HttpOptions({ query: input.queryParams }), ), } - const image = (modelID: string | ModelID) => OpenAIImages.model({ ...media, id: modelID }) + const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + OpenAIImages.model({ ...media, id: modelID, providerOptions }) const speech = (modelID: string | ModelID) => OpenAISpeech.model({ ...media, id: modelID }) const transcription = (modelID: string | ModelID) => OpenAITranscription.model({ ...media, id: modelID }) const decisionRoute = OpenAIDecisions.route.with({ @@ -124,7 +126,8 @@ export const configure = (input: Config = {}) => { headers: media.headers, http: media.http, }) - const decision = (modelID: string | ModelID) => decisionRoute.model({ id: modelID }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + decisionRoute.model({ id: modelID, providerOptions }) return { id, @@ -178,6 +181,14 @@ export const chatModel: ProviderPackage.Definition configure(config(settings)).chat(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} export const responses = provider.responses export const chat = provider.chat export const image = provider.image diff --git a/packages/ai/src/providers/openai/images.ts b/packages/ai/src/providers/openai/images.ts new file mode 100644 index 00000000000..f3381a410b3 --- /dev/null +++ b/packages/ai/src/providers/openai/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../openai.js" +export type { Settings } from "../openai.js" diff --git a/packages/ai/src/providers/opencode.ts b/packages/ai/src/providers/opencode.ts index 355481e0ef3..29a4ca36e77 100644 --- a/packages/ai/src/providers/opencode.ts +++ b/packages/ai/src/providers/opencode.ts @@ -1,4 +1,5 @@ -import { HttpOptions, ProviderID, type ModelID } from "../schema/index.js" +import { HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import type { ProviderPackage } from "../provider-package.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { SystemOne } from "../protocols/system-one.js" @@ -11,6 +12,8 @@ export type Options = ProviderAuthOption<"optional"> & { readonly http?: HttpOptions.Input } +export type Settings = ProviderPackage.Settings & { readonly apiKey?: string } + export const configure = (input: Options = {}) => { const route = SystemOne.route.with({ provider: id, @@ -21,11 +24,18 @@ export const configure = (input: Options = {}) => { headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers }, http: input.http, }) - const decision = (modelID: string | ModelID) => route.model({ id: modelID }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + route.model({ id: modelID, providerOptions }) return { id, decision, configure } } export const provider = configure() export const decision = provider.decision +export const decisionModel = (modelID: string, { apiKey, baseURL, body, headers, ...providerOptions }: Settings) => + configure({ apiKey, baseURL, headers, http: body === undefined ? undefined : { body } }).decision( + modelID, + providerOptions, + ) + export * as OpenCode from "./opencode.js" diff --git a/packages/ai/src/providers/opencode/decisions.ts b/packages/ai/src/providers/opencode/decisions.ts new file mode 100644 index 00000000000..597cbda7ea8 --- /dev/null +++ b/packages/ai/src/providers/opencode/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../opencode.js" +export type { Settings } from "../opencode.js" diff --git a/packages/ai/src/providers/openrouter.ts b/packages/ai/src/providers/openrouter.ts index f0972ac7ec5..e4a83be41f9 100644 --- a/packages/ai/src/providers/openrouter.ts +++ b/packages/ai/src/providers/openrouter.ts @@ -3,9 +3,11 @@ import { Route, type RouteDefaultsInput } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Protocol } from "../route/protocol.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" -import { ProviderID, type ModelID, type OpenString } from "../schema/index.js" +import { ProviderID, type ModelID, type OpenString, type ProviderOptions } from "../schema/index.js" import type { ProviderPackage } from "../provider-package.js" import { SystemOne } from "../protocols/system-one.js" +import { OpenAIImages } from "../protocols/openai-images.js" +import { MediaRoute } from "../route/media.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { cacheControl } from "../protocols/utils/cache.js" import { isRecord, JsonObject, lenient, ProviderShared } from "../protocols/shared.js" @@ -194,20 +196,29 @@ const configuredRoute = (input: LanguageModelOptions) => { export const configure = (input: LanguageModelOptions = {}) => { const route = configuredRoute(input) + const auth = AuthOptions.bearer(input, "OPENROUTER_API_KEY") const decisionRoute = SystemOne.route.with({ provider: id, providerMetadataKey: "openrouter", endpoint: { baseURL: input.baseURL ?? baseURL }, - auth: AuthOptions.bearer(input, "OPENROUTER_API_KEY"), + auth, headers: input.headers, http: input.http, }) - const decision = (modelID: string | ModelID) => - decisionRoute.model({ id: modelID, compatibility: { imageInput: "state" } }) + const media = MediaRoute.deployment({ ...input, baseURL: input.baseURL ?? baseURL }, auth) + const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + decisionRoute.model({ + id: modelID, + compatibility: { mediaInput: "state" }, + providerOptions, + }) return { id, model: (modelID: string | ModelID) => route.model({ id: modelID, compatibility: { supportsPromptCacheKey: true } }), + image, decision, configure, } @@ -215,14 +226,26 @@ export const configure = (input: LanguageModelOptions = {}) => { export const provider = configure() export const decision = provider.decision +export const image = provider.image export const model: ProviderPackage.Definition["model"] = ( modelID, - { apiKey, baseURL, body, headers, ...providerOptions }, -) => - configure({ + settings, +) => configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, providerOptions, - }).model(modelID) + } +} diff --git a/packages/ai/src/providers/openrouter/decisions.ts b/packages/ai/src/providers/openrouter/decisions.ts new file mode 100644 index 00000000000..236baa2e310 --- /dev/null +++ b/packages/ai/src/providers/openrouter/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../openrouter.js" +export type { Settings } from "../openrouter.js" diff --git a/packages/ai/src/providers/openrouter/images.ts b/packages/ai/src/providers/openrouter/images.ts new file mode 100644 index 00000000000..e4d8eb858e4 --- /dev/null +++ b/packages/ai/src/providers/openrouter/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../openrouter.js" +export type { Settings } from "../openrouter.js" diff --git a/packages/ai/src/providers/typesafe-ai.ts b/packages/ai/src/providers/typesafe-ai.ts index 85eea0b5927..9851b148c7d 100644 --- a/packages/ai/src/providers/typesafe-ai.ts +++ b/packages/ai/src/providers/typesafe-ai.ts @@ -1,4 +1,5 @@ -import { HttpOptions, ProviderID, type ModelID } from "../schema/index.js" +import { HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import type { ProviderPackage } from "../provider-package.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { SystemOne } from "../protocols/system-one.js" @@ -11,6 +12,8 @@ export type Options = ProviderAuthOption<"optional"> & { readonly http?: HttpOptions.Input } +export type Settings = ProviderPackage.Settings & { readonly apiKey?: string } + export const configure = (input: Options = {}) => { const route = SystemOne.route.with({ provider: id, @@ -21,11 +24,18 @@ export const configure = (input: Options = {}) => { headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers }, http: input.http, }) - const decision = (modelID: string | ModelID) => route.model({ id: modelID }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + route.model({ id: modelID, providerOptions }) return { id, decision, configure } } export const provider = configure() export const decision = provider.decision +export const decisionModel = (modelID: string, { apiKey, baseURL, body, headers, ...providerOptions }: Settings) => + configure({ apiKey, baseURL, headers, http: body === undefined ? undefined : { body } }).decision( + modelID, + providerOptions, + ) + export * as TypeSafeAI from "./typesafe-ai.js" diff --git a/packages/ai/src/providers/typesafe-ai/decisions.ts b/packages/ai/src/providers/typesafe-ai/decisions.ts new file mode 100644 index 00000000000..d8c981fdb84 --- /dev/null +++ b/packages/ai/src/providers/typesafe-ai/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../typesafe-ai.js" +export type { Settings } from "../typesafe-ai.js" diff --git a/packages/ai/src/providers/vercel-ai-gateway.ts b/packages/ai/src/providers/vercel-ai-gateway.ts index 59f46ed77ca..f461f5caaf3 100644 --- a/packages/ai/src/providers/vercel-ai-gateway.ts +++ b/packages/ai/src/providers/vercel-ai-gateway.ts @@ -13,7 +13,14 @@ import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" import { MediaRoute } from "../route/media.js" import type { Protocol } from "../route/protocol.js" -import { LLMRequest, ModelID, ProviderID, ProviderMetadata, ReasoningEffort } from "../schema/index.js" +import { + LLMRequest, + ModelID, + ProviderID, + ProviderMetadata, + ReasoningEffort, + type ProviderOptions, +} from "../schema/index.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" export const id = ProviderID.make("vercel-ai-gateway") @@ -230,7 +237,8 @@ export const configure = (input: Options = {}) => { return messages(modelID) } const media = MediaRoute.deployment({ ...input, baseURL: configured.endpoint.baseURL }, configured.auth) - const image = (modelID: string | ModelID) => OpenAIImages.model({ ...media, id: modelID, provider: id }) + const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions }) const decisionRoute = OpenAIDecisions.route.with({ provider: id, endpoint: { baseURL: configured.endpoint.baseURL }, @@ -238,7 +246,8 @@ export const configure = (input: Options = {}) => { headers: input.headers, http: input.http, }) - const decision = (modelID: string | ModelID) => decisionRoute.model({ id: modelID }) + const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + decisionRoute.model({ id: modelID, providerOptions }) return { id, model, messages, responses, chat, image, decision, configure } } @@ -250,24 +259,32 @@ export const chat = provider.chat export const image = provider.image export const model: ProviderPackage.Definition["model"] = (modelID, settings) => - fromSettings(settings).model(modelID) + configure(config(settings)).model(modelID) export const messagesModel: ProviderPackage.Definition["model"] = (modelID, settings) => - fromSettings(settings).messages(modelID) + configure(config(settings)).messages(modelID) export const responsesModel: ProviderPackage.Definition["model"] = ( modelID, settings, -) => fromSettings(settings).responses(modelID) +) => configure(config(settings)).responses(modelID) export const chatModel: ProviderPackage.Definition["model"] = (modelID, settings) => - fromSettings(settings).chat(modelID) + configure(config(settings)).chat(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} +export const decisionModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).decision(modelID, input.providerOptions) +} -function fromSettings({ apiKey, baseURL, headers, body, ...providerOptions }: Settings) { - return configure({ +function config({ apiKey, baseURL, headers, body, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, providerOptions, - }) + } } export * as VercelAIGateway from "./vercel-ai-gateway.js" diff --git a/packages/ai/src/providers/vercel-ai-gateway/decisions.ts b/packages/ai/src/providers/vercel-ai-gateway/decisions.ts new file mode 100644 index 00000000000..2e6fc19a73a --- /dev/null +++ b/packages/ai/src/providers/vercel-ai-gateway/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../vercel-ai-gateway.js" +export type { Settings } from "../vercel-ai-gateway.js" diff --git a/packages/ai/src/providers/vercel-ai-gateway/images.ts b/packages/ai/src/providers/vercel-ai-gateway/images.ts new file mode 100644 index 00000000000..45ff4925603 --- /dev/null +++ b/packages/ai/src/providers/vercel-ai-gateway/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../vercel-ai-gateway.js" +export type { Settings } from "../vercel-ai-gateway.js" diff --git a/packages/ai/src/providers/xai.ts b/packages/ai/src/providers/xai.ts index cfc98940b31..d8559e02692 100644 --- a/packages/ai/src/providers/xai.ts +++ b/packages/ai/src/providers/xai.ts @@ -2,7 +2,7 @@ import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { Route, type RouteDefaultsInput } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponsesChannel } from "../protocols/open-responses-channel.js" import { XAIResponses } from "../protocols/xai-responses.js" @@ -97,7 +97,8 @@ export const configure = (input: LanguageModelOptions = {}) => { model: responses, responses, chat, - image: (modelID: string | ModelID) => XAIImages.model({ ...media, id: modelID }), + image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + XAIImages.model({ ...media, id: modelID, providerOptions }), video: (modelID: string | ModelID) => XAIVideo.model({ ...media, id: modelID }), configure, } @@ -108,14 +109,21 @@ export const model: ProviderPackage.Definition< Settings, XAIProviderOptionsInput, typeof responsesRoute.compact ->["model"] = (modelID, { apiKey, baseURL, body, headers, ...providerOptions }) => - configure({ +>["model"] = (modelID, settings) => configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, providerOptions, - }).model(modelID) + } +} export const responses = provider.responses export const chat = provider.chat export const image = provider.image diff --git a/packages/ai/src/providers/xai/images.ts b/packages/ai/src/providers/xai/images.ts new file mode 100644 index 00000000000..fc3d3ab9b08 --- /dev/null +++ b/packages/ai/src/providers/xai/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../xai.js" +export type { Settings } from "../xai.js" diff --git a/packages/ai/src/providers/zai.ts b/packages/ai/src/providers/zai.ts index 760c4a3e2ca..1185f73bbed 100644 --- a/packages/ai/src/providers/zai.ts +++ b/packages/ai/src/providers/zai.ts @@ -6,7 +6,7 @@ import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { Route, type RouteDefaultsInput } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" export const id = ProviderID.make("zai") @@ -50,7 +50,8 @@ export const configure = (input: Config = {}) => { }) .model({ id: modelID, compatibility: ZAIChat.compatibility }) const media = MediaRoute.deployment(input, auth(input)) - const image = (modelID: string | ModelID) => ZAIImages.model({ ...media, id: modelID }) + const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => + ZAIImages.model({ ...media, id: modelID, providerOptions }) return { id, @@ -65,16 +66,21 @@ export const provider = configure() export const image = provider.image export const chat = provider.chat -export const model: ProviderPackage.Definition["model"] = ( - modelID, - { apiKey, baseURL, body, headers, ...providerOptions }, -) => - configure({ +export const model: ProviderPackage.Definition["model"] = (modelID, settings) => + configure(config(settings)).model(modelID) +export const imageModel = (modelID: string, settings: Settings) => { + const input = config(settings) + return configure(input).image(modelID, input.providerOptions) +} + +function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings) { + return { apiKey, baseURL, headers, http: body === undefined ? undefined : { body }, providerOptions, - }).model(modelID) + } +} export * as ZAI from "./zai.js" diff --git a/packages/ai/src/providers/zai/images.ts b/packages/ai/src/providers/zai/images.ts new file mode 100644 index 00000000000..83ee050c714 --- /dev/null +++ b/packages/ai/src/providers/zai/images.ts @@ -0,0 +1,2 @@ +export { imageModel as model } from "../zai.js" +export type { Settings } from "../zai.js" diff --git a/packages/ai/src/route/client.ts b/packages/ai/src/route/client.ts index 967645433fd..6b763f9d77c 100644 --- a/packages/ai/src/route/client.ts +++ b/packages/ai/src/route/client.ts @@ -1,4 +1,4 @@ -import { Cause, Context, Effect, Layer, Schema, Stream } from "effect" +import { Cause, Context, Effect, Layer, Option, Schema, Stream } from "effect" import { Auth } from "./auth.js" import { Endpoint, type EndpointPatch } from "./endpoint.js" import { RequestExecutor } from "./executor.js" @@ -335,7 +335,8 @@ const requireTerminalEvent = (route: string) => (events: Stream.Stream { - if (terminal) + // Raw events carry provider frames that may trail the terminal event. + if (terminal && !LLMEvent.is.raw(event)) return Effect.fail( ProviderShared.eventError(route, `Provider emitted ${event.type} after the terminal event`), ) @@ -346,6 +347,19 @@ const requireTerminalEvent = (route: string) => (events: Stream.Stream + typeof frame === "string" ? Option.getOrElse(decodeJsonOption(frame), () => frame) : frame + +// Transports may interleave their own marker objects with provider frames, e.g. Gemini's continuation boundary. +const isProviderFrame = (frame: unknown) => + typeof frame !== "object" || + frame === null || + Array.isArray(frame) || + Object.getPrototypeOf(frame) === Object.prototype + function makeFromTransport( input: MakeTransportInput, ): Route { @@ -456,7 +470,9 @@ function makeFromTransport( ), Effect.map(([next, output]) => { state = next - return output + return request.includeRaw && isProviderFrame(frame) + ? [LLMEvent.raw({ data: execution.raw?.(frame) ?? rawFrame(frame) }), ...output] + : output }), Effect.mapError(frameError(frame, event)), ), @@ -592,7 +608,7 @@ const compile = Effect.fn("LLM.compile")(function* (request: LLMRequest, options } }) -/** @internal Test-only projection of the execution compiler; not exported from package barrels. */ +/** Test-only projection of the execution compiler; exported from `@opencode/ai/testing`. */ export const compileRequest = Effect.fn("LLM.compileRequest")(function* (request: LLMRequest) { const compiled = yield* compile(request) return { diff --git a/packages/ai/src/route/decision.ts b/packages/ai/src/route/decision.ts index 55a7c583998..681eb82e4a1 100644 --- a/packages/ai/src/route/decision.ts +++ b/packages/ai/src/route/decision.ts @@ -8,7 +8,7 @@ import { type DecisionRequestFor, type DecisionResponse, } from "../decision.js" -import { HttpOptions, ProviderID, type AIError } from "../schema/index.js" +import { HttpOptions, ProviderID, type AIError, type ProviderOptions } from "../schema/index.js" import { Auth } from "./auth.js" import { Endpoint } from "./endpoint.js" import { RequestExecutorService } from "./executor-service.js" @@ -56,6 +56,7 @@ export interface Route { readonly model: (input: { readonly id: string readonly compatibility?: DecisionModelCompatibility.Input + readonly providerOptions?: ProviderOptions }) => DecisionModel } @@ -94,12 +95,14 @@ export const make = (input: MakeInput): Route => { model: (model: { readonly id: string readonly compatibility?: DecisionModelCompatibility.Input + readonly providerOptions?: ProviderOptions }) => { const send = transport(route) return DecisionModel.make({ id: model.id, provider, http: route.http, + providerOptions: model.providerOptions, compatibility: model.compatibility === undefined ? undefined : DecisionModelCompatibility.make(model.compatibility), route: { id: route.id, generate: send }, diff --git a/packages/ai/src/route/executor.ts b/packages/ai/src/route/executor.ts index 65850f5e55b..e7cbb2c7699 100644 --- a/packages/ai/src/route/executor.ts +++ b/packages/ai/src/route/executor.ts @@ -12,7 +12,7 @@ import { classifyProviderFailure, providerErrorMessage } from "../provider-error import { headerDetails, responseHttp, Service, type HttpMiddleware, type Interface } from "./executor-service.js" export { responseHttp, Service } from "./executor-service.js" -export type { HttpHandler, HttpMiddleware, Interface } from "./executor-service.js" +export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js" const normalizedHeaders = (headers: Headers.Headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value])) diff --git a/packages/ai/src/route/framing.ts b/packages/ai/src/route/framing.ts index 4ff92c2abc6..ea2889e5c77 100644 --- a/packages/ai/src/route/framing.ts +++ b/packages/ai/src/route/framing.ts @@ -23,6 +23,8 @@ export interface Definition { readonly frame: (bytes: Stream.Stream) => Stream.Stream /** Original wire representation when framing transforms the provider payload. */ readonly body?: (frame: Frame) => string | undefined + /** Provider value exposed as a `raw` event when framing adds fields of its own. Defaults to the frame. */ + readonly raw?: (frame: Frame) => unknown } /** diff --git a/packages/ai/src/route/index.ts b/packages/ai/src/route/index.ts index 3e840afdc99..c103b3ff131 100644 --- a/packages/ai/src/route/index.ts +++ b/packages/ai/src/route/index.ts @@ -26,6 +26,9 @@ export { Framing } from "./framing.js" export { Protocol } from "./protocol.js" export { HttpTransport, WebSocketTransport } from "./transport/index.js" export * as Transport from "./transport/index.js" +export { ProviderShared } from "../protocols/shared.js" +export { classifyProviderFailure } from "../provider-error.js" +export { mergeHttpOptions } from "../schema/index.js" export type { Definition as AuthShape, AuthInput, Credential, CredentialError } from "./auth.js" export type { ApiKeyMode, AuthOverride, ProviderAuthOption } from "./auth-options.js" export type { Definition as EndpointFn, EndpointInput } from "./endpoint.js" diff --git a/packages/ai/src/route/media.ts b/packages/ai/src/route/media.ts index 5af63162d68..0cfaedfa9e9 100644 --- a/packages/ai/src/route/media.ts +++ b/packages/ai/src/route/media.ts @@ -16,6 +16,8 @@ import { ProviderID, UnsupportedOperationError, mergeHttpOptions, + mergeProviderOptions, + type ProviderOptions, } from "../schema/index.js" import { encodeJson } from "../utils/json.js" import { sanitizeSurrogates } from "../utils/sanitize.js" @@ -24,7 +26,13 @@ export type Execute = Interface["execute"] /** The minimum a media request must carry for the route to build a transport request. */ export interface MediaRequest { - readonly model: { readonly id: string; readonly provider: ProviderID; readonly http?: HttpOptions } + readonly model: { + readonly id: string + readonly provider: ProviderID + readonly http?: HttpOptions + readonly providerOptions?: ProviderOptions + } + readonly providerOptions?: ProviderOptions readonly http?: HttpOptions } @@ -35,6 +43,8 @@ export interface ModelInput { readonly baseURL?: string readonly headers?: Record readonly http?: HttpOptions + /** Defaults under each request's `providerOptions`. */ + readonly providerOptions?: ProviderOptions } /** A provider facade's `configure(...)` input as the `ModelInput` every media selector shares, minus the model id. */ @@ -355,6 +365,7 @@ const makeTransport = ( ) { yield* rejectUnsupported(input.protocol.id, input.protocol.provider, request, protocol.unsupported) const http = mergeHttpOptions(routeHttp, request.model.http, request.http) + const providerOptions = mergeProviderOptions(request.model.providerOptions, request.providerOptions) const headers = Headers.fromInput(http?.headers) const prepared = protocol.prepare === undefined @@ -365,7 +376,10 @@ const makeTransport = ( ), ) // Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized. - const resolved: Request = { ...sanitizeSurrogates({ ...prepared, http }), model: request.model } + const resolved: Request = { + ...sanitizeSurrogates({ ...prepared, http, providerOptions }), + model: request.model, + } const body = yield* protocol.from(resolved) const url = withQuery( withQuery( diff --git a/packages/ai/src/route/transport/http.ts b/packages/ai/src/route/transport/http.ts index a9385338130..a2080994e5d 100644 --- a/packages/ai/src/route/transport/http.ts +++ b/packages/ai/src/route/transport/http.ts @@ -131,6 +131,7 @@ export const httpJson = (input: HttpJsonInput): HttpJs ), http, body: prepared.framing.body, + raw: prepared.framing.raw, } }), }) diff --git a/packages/ai/src/route/transport/index.ts b/packages/ai/src/route/transport/index.ts index 9690392dcc8..27d22e371d0 100644 --- a/packages/ai/src/route/transport/index.ts +++ b/packages/ai/src/route/transport/index.ts @@ -13,6 +13,7 @@ export interface TransportExecution { readonly frames: Stream.Stream readonly http?: HttpContext body?(frame: Frame): string | undefined + raw?(frame: Frame): unknown /** Optional successful-consumption acknowledgement. HTTP leaves this absent. */ readonly complete?: Effect.Effect } diff --git a/packages/ai/src/schema/events.ts b/packages/ai/src/schema/events.ts index 3f05398357e..adcd037e496 100644 --- a/packages/ai/src/schema/events.ts +++ b/packages/ai/src/schema/events.ts @@ -310,6 +310,13 @@ export const ProviderErrorEvent = Schema.Struct({ }).annotate({ identifier: "LLM.Event.ProviderError" }) export type ProviderErrorEvent = Schema.Schema.Type +/** One provider frame as received, emitted before the events parsed from it when the request sets `includeRaw`. */ +export const RawEvent = Schema.Struct({ + type: Schema.tag("raw"), + data: Schema.Unknown, +}).annotate({ identifier: "LLM.Event.Raw" }) +export type RawEvent = Schema.Schema.Type + const llmEventTagged = Schema.Union([ CompactionPart, StepStart, @@ -330,6 +337,7 @@ const llmEventTagged = Schema.Union([ StepFinish, Finish, ProviderErrorEvent, + RawEvent, ]).pipe(Schema.toTaggedUnion("type")) type WithID = Omit & { readonly id: ID | string } @@ -384,6 +392,7 @@ export const LLMEvent = Object.assign(llmEventTagged, { usage: input.usage === undefined ? undefined : Usage.from(input.usage), }), providerError: ProviderErrorEvent.make, + raw: RawEvent.make, is: { compaction: llmEventTagged.guards.compaction, stepStart: llmEventTagged.guards["step-start"], @@ -404,6 +413,7 @@ export const LLMEvent = Object.assign(llmEventTagged, { stepFinish: llmEventTagged.guards["step-finish"], finish: llmEventTagged.guards.finish, providerError: llmEventTagged.guards["provider-error"], + raw: llmEventTagged.guards.raw, }, }) export type LLMEvent = Schema.Schema.Type @@ -646,6 +656,7 @@ const reduceToolCall = (state: ResponseState, event: ToolCall): ResponseState => } const reduceResponseState = (state: ResponseState, event: LLMEvent): ResponseState => { + if (event.type === "raw") return state const next = appendEvent(state, event) switch (event.type) { case "compaction": diff --git a/packages/ai/src/schema/messages.ts b/packages/ai/src/schema/messages.ts index a9359bef1d0..ac3bfd451aa 100644 --- a/packages/ai/src/schema/messages.ts +++ b/packages/ai/src/schema/messages.ts @@ -395,6 +395,8 @@ const requestSchema = Schema.Struct({ // Stable cache affinity for protocols that support provider-managed prompt caching. promptCacheKey: Schema.optional(Schema.String), metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + /** Emit a `raw` event with each provider frame before the events parsed from it. */ + includeRaw: Schema.optional(Schema.Boolean), }) export class LLMRequest extends Schema.Class("LLM.Request")( @@ -427,6 +429,7 @@ export namespace LLMRequest { cache: request.cache, promptCacheKey: request.promptCacheKey, metadata: request.metadata, + includeRaw: request.includeRaw, }) export function update( diff --git a/packages/ai/src/schema/options.ts b/packages/ai/src/schema/options.ts index 0b4e77b813a..4e69d6c708f 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -342,9 +342,16 @@ export const LanguageModelSchema = Schema.declare((value): value is LanguageMode expected: "LLM.LanguageModel", }) +// Provider cache lifetime such as "5m", "30m", "1h" or "24h", in models.dev's duration format. It is sent as given; +// each provider accepts its own set, and omitting it keeps the provider default. +export const CacheTTL = Schema.TemplateLiteral([Schema.Number, Schema.Literals(["ms", "s", "m", "h", "d"])]).check( + Schema.isPattern(/^\d+(ms|s|m|h|d)$/), +) +export type CacheTTL = typeof CacheTTL.Type + export class CacheHint extends Schema.Class("LLM.CacheHint")({ type: Schema.Literals(["ephemeral", "persistent"]), - ttlSeconds: Schema.optional(Schema.Number), + ttl: Schema.optional(CacheTTL), }) {} // Auto-placement policy for prompt caching. The protocol-neutral lowering step @@ -356,7 +363,9 @@ export class CacheHint extends Schema.Class("LLM.CacheHint")({ // tool loops. // // Pass `"none"` to opt out entirely (the legacy behavior). Pass the granular -// object form to override individual choices. +// object form to choose placements exactly; an object with only `ttl` keeps +// the automatic placements and sets their lifetime. Routes without inline +// markers send `ttl` as a request-level cache option where one exists. export const CachePolicyObject = Schema.Struct({ tools: Schema.optional(Schema.Boolean), system: Schema.optional(Schema.Boolean), @@ -367,7 +376,7 @@ export const CachePolicyObject = Schema.Struct({ Schema.Struct({ tail: Schema.Natural }), ]), ), - ttlSeconds: Schema.optional(Schema.Number), + ttl: Schema.optional(CacheTTL), }) export type CachePolicyObject = Schema.Schema.Type diff --git a/packages/ai/src/speech.ts b/packages/ai/src/speech.ts index 38fc50d07c4..0c0535ed9a1 100644 --- a/packages/ai/src/speech.ts +++ b/packages/ai/src/speech.ts @@ -3,14 +3,7 @@ import { ProgressEvent, QueuedEvent } from "./generation.js" import { Media } from "./media.js" import { MediaModel, composeRoute, tryRequest } from "./media-model.js" import { MediaRoute } from "./route/media.js" -import { - AIError, - HttpOptions, - MediaUsage, - ProviderMetadata, - ProviderOptions, - type OpenString, -} from "./schema/index.js" +import { AIError, HttpOptions, MediaUsage, ProviderMetadata, ProviderOptions, type OpenString } from "./schema/index.js" import { SpeechClient, Service } from "./speech-client.js" // --------------------------------------------------------------------------- @@ -45,6 +38,7 @@ export class SpeechModel extends id: input.id, provider: route.protocol.provider, http: input.http, + providerOptions: input.providerOptions, route: composeRoute(route, input, collectResponse) as SpeechRoute, }) } diff --git a/packages/ai/src/testing.ts b/packages/ai/src/testing.ts index 420ff88282e..f7807d7b8f8 100644 --- a/packages/ai/src/testing.ts +++ b/packages/ai/src/testing.ts @@ -1,4 +1,5 @@ export * as TestLLM from "./testing.js" +export { compileRequest } from "./route/client.js" import { LLMClient, @@ -47,25 +48,12 @@ export interface TestInterface extends ClientInterface { export class Test extends Context.Service()("@opencode/ai/TestLLM/Test") {} -/** @deprecated Use TestInterface through Test and testLayer. */ -export interface Interface { - readonly requests: LLMRequest[] - readonly push: (...responses: readonly Response[]) => Effect.Effect - readonly always: (response: Response) => Effect.Effect - readonly wait: (count: number) => Effect.Effect - readonly gate: Effect.Effect - readonly client: ClientInterface -} - export interface LayerOptions { readonly transformRequest?: (request: LLMRequest) => LLMRequest /** Used after the one-shot response queue is exhausted. Omit to defect on unexpected requests. */ readonly fallback?: Response } -/** @deprecated Use Test and testLayer for normal client methods and test controls. */ -export class Service extends Context.Service()("@opencode/ai/TestLLM") {} - export const complete = ( options: { readonly reason: FinishReasonDetails @@ -173,7 +161,7 @@ const make = (options: LayerOptions) => }), ) } - const test = Test.of({ + return Test.of({ compact, stream, generate: (request) => @@ -216,44 +204,10 @@ const make = (options: LayerOptions) => } }), }) - - return { test, requests } }) /** Provides one shared implementation under the normal client and test-control tags. */ export const testLayer = (options: LayerOptions = {}) => Layer.effectContext( - Effect.map(make(options), (implementation) => - Context.make(LLMClient.Service, implementation.test).pipe(Context.add(Test, implementation.test)), - ), + Effect.map(make(options), (test) => Context.make(LLMClient.Service, test).pipe(Context.add(Test, test))), ) - -/** @deprecated Use testLayer; retained for published callers of the legacy control interface. */ -export const layer = (options: LayerOptions = {}) => - Layer.effect( - Service, - Effect.map(make(options), (implementation) => - Service.of({ - requests: implementation.requests, - push: implementation.test.push, - always: implementation.test.always, - wait: implementation.test.wait, - gate: implementation.test.gate(), - client: implementation.test, - }), - ), - ) - -/** @deprecated testLayer provides LLMClient.Service directly. */ -export const clientLayer = Layer.effect( - LLMClient.Service, - Effect.map(Service, (service) => service.client), -) - -export const push = (...responses: readonly Response[]) => Service.use((service) => service.push(...responses)) - -export const always = (response: Response) => Service.use((service) => service.always(response)) - -export const wait = (count: number) => Service.use((service) => service.wait(count)) - -export const gate = Service.use((service) => service.gate) diff --git a/packages/ai/src/transcription.ts b/packages/ai/src/transcription.ts index 33f0a8f55af..93facc5ff7d 100644 --- a/packages/ai/src/transcription.ts +++ b/packages/ai/src/transcription.ts @@ -48,6 +48,7 @@ export class TranscriptionModel> = { jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", + avif: "image/avif", + heic: "image/heic", + heif: "image/heif", pdf: "application/pdf", mp4: "video/mp4", + mov: "video/quicktime", webm: "video/webm", mp3: "audio/mpeg", m4a: "audio/mp4", diff --git a/packages/ai/src/video.ts b/packages/ai/src/video.ts index 336be963730..f9cba5030c2 100644 --- a/packages/ai/src/video.ts +++ b/packages/ai/src/video.ts @@ -38,6 +38,7 @@ export class VideoModel extends Med id: input.id, provider: route.protocol.provider, http: input.http, + providerOptions: input.providerOptions, route: composeRoute(route, input, collectResponse) as VideoRoute, }) } diff --git a/packages/ai/test/cache-policy.test.ts b/packages/ai/test/cache-policy.test.ts index 0d245495115..3ae8e8c5b34 100644 --- a/packages/ai/test/cache-policy.test.ts +++ b/packages/ai/test/cache-policy.test.ts @@ -389,7 +389,7 @@ describe("applyCachePolicy", () => { LLM.request({ model: anthropicModel, system: [ - { type: "text", text: "first system", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) }, + { type: "text", text: "first system", cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }, { type: "text", text: "last system" }, ], prompt: "hi", @@ -416,7 +416,7 @@ describe("applyCachePolicy", () => { { type: "text", text: "Manual context", - cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }), + cache: new CacheHint({ type: "ephemeral", ttl: "1h" }), }, { type: "text", text: "Project instructions" }, ], @@ -473,14 +473,27 @@ describe("applyCachePolicy", () => { expect(namespace.tools[1]).toHaveProperty("cache", { type: "ephemeral" }) }) - it.effect("ttlSeconds in the policy flows through to wire markers", () => + it.effect("a ttl-only policy keeps automatic placement", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + LLM.request({ model: anthropicModel, system: "Sys", prompt: "hi", cache: { ttl: "1h" } }), + ) + + expect(prepared.body).toMatchObject({ + system: [{ type: "text", text: "Sys", cache_control: { type: "ephemeral", ttl: "1h" } }], + messages: [{ role: "user", content: [{ type: "text", text: "hi", cache_control: { type: "ephemeral", ttl: "1h" } }] }], + }) + }), + ) + + it.effect("ttl in the policy flows through to wire markers", () => Effect.gen(function* () { const prepared = yield* compileRequest( LLM.request({ model: anthropicModel, system: "Sys", prompt: "hi", - cache: { system: true, ttlSeconds: 3600 }, + cache: { system: true, ttl: "1h" }, }), ) diff --git a/packages/ai/test/compile.test.ts b/packages/ai/test/compile.test.ts index 268140908ac..4e0b579b802 100644 --- a/packages/ai/test/compile.test.ts +++ b/packages/ai/test/compile.test.ts @@ -8,11 +8,11 @@ import { ToolCallPart, ToolDefinition, ToolNamespace, - mergeProviderOptions, } from "../src/effect.js" import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../src/protocols.js" import { Auth, LLMClient } from "../src/route.js" import { compileRequest } from "../src/route/client.js" +import { mergeProviderOptions } from "../src/schema/index.js" import { it } from "./lib/effect.js" import { dynamicResponse } from "./lib/http.js" import { deltaChunk } from "./lib/openai-chunks.js" diff --git a/packages/ai/test/exports.test.ts b/packages/ai/test/exports.test.ts index 03527dab49c..0605645b077 100644 --- a/packages/ai/test/exports.test.ts +++ b/packages/ai/test/exports.test.ts @@ -12,7 +12,6 @@ import { LLM, LLMClient, Media, - Provider, Speech, SpeechClient, SpeechEvent, @@ -21,7 +20,6 @@ import { VideoClient, } from "@opencode/ai/effect" import { Route, Protocol, RequestExecutor, WebSocketTransport } from "@opencode/ai/route" -import { Provider as ProviderSubpath } from "@opencode/ai/provider" import { Alibaba, AssemblyAI, @@ -51,6 +49,7 @@ import { ZAI, } from "@opencode/ai/providers" import { + AnthropicMessages, OpenAIChat, OpenAICompatibleChat, OpenAICompatibleResponses, @@ -58,7 +57,6 @@ import { OpenResponses, OpenResponsesChannel, } from "@opencode/ai/protocols" -import * as AnthropicMessages from "@opencode/ai/protocols/anthropic-messages" import { TestLLM } from "@opencode/ai/testing" describe("public exports", () => { @@ -91,9 +89,6 @@ describe("public exports", () => { expect(SpeechClient.layer).toBeDefined() expect(SpeechEvent.is.audioDelta).toBeFunction() expect(Generation).toBeFunction() - expect(Provider.make).toBeFunction() - expect(ProviderSubpath.make).toBe(Provider.make) - expect(TestLLM.layer).toBeFunction() expect(TestLLM.testLayer).toBeFunction() expect(TestLLM.Test.of).toBeFunction() expect(Decision.generate).toBeFunction() diff --git a/packages/ai/test/extraction.test.ts b/packages/ai/test/extraction.test.ts new file mode 100644 index 00000000000..7430e727d06 --- /dev/null +++ b/packages/ai/test/extraction.test.ts @@ -0,0 +1,227 @@ +import { describe, expect } from "bun:test" +import { Effect } from "effect" +import { Extraction } from "../src/experimental.js" +import { CloudflareWorkersAI } from "../src/providers.js" +import { it } from "./lib/effect.js" +import { dynamicResponse, json } from "./lib/http.js" + +const model = CloudflareWorkersAI.configure({ + accountId: "test-account", + apiKey: "cloudflare-key", +}).experimental.extraction("@cf/cloudflare/clairic") + +describe("Extraction", () => { + it.effect("sends Clairic fields and decodes typed answers", () => + Extraction.generate({ + model, + input: "Invoice INV-7 issued March 2, net 30, total $1,080.00. Contacts: Dana, Priya.", + fields: { + invoice: { type: "text", nullThreshold: 0.8 }, + total: { type: "number", decimals: 2, unit: "USD" }, + due: { type: "date", instructions: "Issue date plus net days" }, + contacts: { type: "list", items: "text" }, + payDays: { type: "estimate", min: 0, max: 120, step: 1 }, + sales: { type: "forecast", min: 0, max: 500, horizon: 2, interval: "month" }, + }, + referenceDate: "2026-01-01", + providerOptions: { options: { include_quantiles: true } }, + }).pipe( + Effect.tap((response) => + Effect.sync(() => { + expect(response.answers).toEqual({ + invoice: { + value: "INV-7", + guess: "INV-7", + nullProbability: 0.01, + confidence: 0.99, + span: [8, 13], + }, + total: { value: null, guess: 1080, nullProbability: 0.6, confidence: 0.9 }, + due: { value: "2026-04-01", nullProbability: 0, confidence: 1 }, + contacts: { + value: ["Dana", "Priya"], + spans: [ + [67, 71], + [73, 78], + ], + confidence: 0.98, + }, + payDays: { + value: 30, + mean: 29.5, + median: 30, + p10: 21, + p90: 38, + belowProbability: 0.001, + aboveProbability: 0.002, + quantiles: [20, 30, 40], + }, + sales: { + value: [140, 148], + steps: [ + { value: 140, mean: 140, median: 141, p10: 130, p90: 151 }, + { value: 148, mean: 148, median: 148, p10: 131, p90: 165 }, + ], + }, + }) + expect(response.usage?.inputTokens).toBe(655) + expect(response.usage?.providerMetadata?.["cloudflare-workers-ai"]).toMatchObject({ passes: 3 }) + expect(response.providerMetadata).toEqual({ "cloudflare-workers-ai": { model: "clairic", truncated: false } }) + }), + ), + Effect.provide( + dynamicResponse((input) => { + expect(input.request.url).toBe( + "https://api.cloudflare.com/client/v4/accounts/test-account/ai/run/@cf/cloudflare/clairic", + ) + expect(input.request.headers.authorization).toBe("Bearer cloudflare-key") + expect(JSON.parse(input.text)).toEqual({ + options: { include_quantiles: true }, + model: "@cf/cloudflare/clairic", + state: "Invoice INV-7 issued March 2, net 30, total $1,080.00. Contacts: Dana, Priya.", + fields: { + invoice: { type: "text", null_threshold: 0.8 }, + total: { type: "number", decimals: 2, unit: "USD" }, + due: { type: "date", instructions: "Issue date plus net days" }, + contacts: { type: "list", items: "text" }, + payDays: { type: "estimate", min: 0, max: 120, step: 1 }, + sales: { type: "forecast", min: 0, max: 500, horizon: 2, interval: "month" }, + }, + reference_date: "2026-01-01", + }) + return Effect.succeed( + json(input, { + result: { + model: "clairic", + answers: { + invoice: { + type: "text", + p_null: 0.01, + span: [8, 13], + guess: "INV-7", + confidence: 0.99, + value: "INV-7", + }, + total: { type: "number", p_null: 0.6, guess: 1080, confidence: 0.9, value: null }, + due: { type: "date", p_null: 0, confidence: 1, value: "2026-04-01" }, + contacts: { + type: "list", + value: ["Dana", "Priya"], + spans: [ + [67, 71], + [73, 78], + ], + confidence: 0.98, + }, + payDays: { + type: "estimate", + value: 30, + mean: 29.5, + median: 30, + p10: 21, + p90: 38, + p_below: 0.001, + p_above: 0.002, + quantiles: [20, 30, 40], + }, + sales: { + type: "forecast", + value: [140, 148], + median: [141, 148], + p10: [130, 131], + p90: [151, 165], + steps: [ + { value: 140, mean: 140, median: 141, p10: 130, p90: 151 }, + { value: 148, mean: 148, median: 148, p10: 131, p90: 165 }, + ], + }, + }, + truncated: false, + usage: { + state_tokens: 61, + image_tokens: 0, + schema_tokens: 472, + input_tokens: 655, + output_tokens: 0, + passes: 3, + }, + }, + success: true, + errors: [], + messages: [], + }), + ) + }), + ), + ), + ) + + it.effect("passes unknown field types through and drops extra answers", () => + Extraction.generate({ + model, + input: "Ship by May 20 in EUR.", + fields: { ship: { type: "date" }, money: { type: "currency", codes: ["EUR"] } }, + }).pipe( + Effect.tap((response) => + Effect.sync(() => + expect(response.answers).toEqual({ + ship: { value: "2026-05-20", confidence: 0.97 }, + money: { type: "currency", value: "EUR", p_null: 0 }, + }), + ), + ), + Effect.provide( + dynamicResponse((input) => { + expect(JSON.parse(input.text).fields.money).toEqual({ type: "currency", codes: ["EUR"] }) + return Effect.succeed( + json(input, { + result: { + model: "clairic", + answers: { + ship: { type: "date", value: "2026-05-20", confidence: 0.97, calendar: "gregorian" }, + money: { type: "currency", value: "EUR", p_null: 0 }, + extra: { type: "hologram", value: { x: 1 } }, + }, + future_flag: true, + }, + }), + ) + }), + ), + ), + ) + + it.effect("fails when a requested field has no answer", () => + Extraction.generate({ model, input: "Nothing here.", fields: { total: { type: "number" } } }).pipe( + Effect.flip, + Effect.tap((error) => Effect.sync(() => expect(error.reason._tag).toBe("InvalidProviderOutput"))), + Effect.provide( + dynamicResponse((input) => + Effect.succeed(json(input, { result: { model: "clairic", answers: {}, usage: { input_tokens: 1 } } })), + ), + ), + ), + ) + + it.effect("fails when an answer value does not match its field", () => + Extraction.generate({ model, input: "Total: lots.", fields: { total: { type: "number" } } }).pipe( + Effect.flip, + Effect.tap((error) => Effect.sync(() => expect(error.reason._tag).toBe("InvalidProviderOutput"))), + Effect.provide( + dynamicResponse((input) => + Effect.succeed( + json(input, { result: { model: "clairic", answers: { total: { type: "number", value: "lots" } } } }), + ), + ), + ), + ), + ) + + it.effect("rejects an empty field map before the network", () => + Extraction.generate({ model, input: "x", fields: {} }).pipe( + Effect.flip, + Effect.tap((error) => Effect.sync(() => expect(error.reason._tag).toBe("InvalidRequest"))), + Effect.provide(dynamicResponse(() => Effect.die("an invalid extraction request reached the network"))), + ), + ) +}) diff --git a/packages/ai/test/fixtures/recordings/bedrock-converse-options/constrains-claude-output-to-a-json-schema.json b/packages/ai/test/fixtures/recordings/bedrock-converse-options/constrains-claude-output-to-a-json-schema.json new file mode 100644 index 00000000000..bab0d590543 --- /dev/null +++ b/packages/ai/test/fixtures/recordings/bedrock-converse-options/constrains-claude-output-to-a-json-schema.json @@ -0,0 +1,33 @@ +{ + "version": 1, + "metadata": { + "tags": [ + "prefix:bedrock-converse-options", + "provider:amazon-bedrock", + "protocol:bedrock-converse" + ], + "name": "bedrock-converse-options/constrains-claude-output-to-a-json-schema", + "recordedAt": "2026-10-26T05:24:46.975Z" + }, + "interactions": [ + { + "transport": "http", + "request": { + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse-stream", + "headers": { + "content-type": "application/json" + }, + "body": "{\"modelId\":\"us.anthropic.claude-sonnet-4-6\",\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"What is 17*23?\"}]}],\"inferenceConfig\":{\"maxTokens\":200},\"outputConfig\":{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"{\\\"type\\\":\\\"object\\\",\\\"properties\\\":{\\\"product\\\":{\\\"type\\\":\\\"integer\\\"}},\\\"required\\\":[\\\"product\\\"],\\\"additionalProperties\\\":false}\",\"name\":\"answer\"}}}}}" + }, + "response": { + "status": 200, + "headers": { + "content-type": "application/vnd.amazon.eventstream" + }, + "body": "AAAArQAAAFJo8LSWCzpldmVudC10eXBlBwAMbWVzc2FnZVN0YXJ0DTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVViIsInJvbGUiOiJhc3Npc3RhbnQiff/V9LIAAADEAAAAV4y4VSULOmV2ZW50LXR5cGUHABFjb250ZW50QmxvY2tEZWx0YQ06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7ImNvbnRlbnRCbG9ja0luZGV4IjowLCJkZWx0YSI6eyJ0ZXh0Ijoie1wiIn0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OIn1nS/0LAAAAuQAAAFeN+nFbCzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsidGV4dCI6InByb2R1Y3RcIjoifSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXYifabu2fMAAACmAAAAV29KcQgLOmV2ZW50LXR5cGUHABFjb250ZW50QmxvY2tEZWx0YQ06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7ImNvbnRlbnRCbG9ja0luZGV4IjowLCJkZWx0YSI6eyJ0ZXh0IjoiMzkxIn0sInAiOiJhYmNkZWZnaGlqIn1V027xAAAAvwAAAFcCuoT7CzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsidGV4dCI6In0ifSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSksifT8Lk2QAAAC1AAAAVj8NrMwLOmV2ZW50LXR5cGUHABBjb250ZW50QmxvY2tTdG9wDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXIn2NFJ+9AAAAoAAAAFEJaSGdCzpldmVudC10eXBlBwALbWVzc2FnZVN0b3ANOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERSIsInN0b3BSZWFzb24iOiJlbmRfdHVybiJ9p5BdEgAAANsAAABOCmP9tgs6ZXZlbnQtdHlwZQcACG1ldGFkYXRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsibWV0cmljcyI6eyJsYXRlbmN5TXMiOjEyMDh9LCJwIjoiYWJjZCIsInVzYWdlIjp7ImlucHV0VG9rZW5zIjoxNTUsIm91dHB1dFRva2VucyI6OCwic2VydmVyVG9vbFVzYWdlIjp7fSwidG90YWxUb2tlbnMiOjE2M319Zt/PuA==", + "bodyEncoding": "base64" + } + } + ] +} diff --git a/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata.json b/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata.json new file mode 100644 index 00000000000..95485a59b04 --- /dev/null +++ b/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata.json @@ -0,0 +1,34 @@ +{ + "version": 1, + "metadata": { + "tags": [ + "prefix:bedrock-converse-options", + "provider:amazon-bedrock", + "protocol:bedrock-converse", + "reasoning" + ], + "name": "bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata", + "recordedAt": "2026-10-26T05:24:42.553Z" + }, + "interactions": [ + { + "transport": "http", + "request": { + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse-stream", + "headers": { + "content-type": "application/json" + }, + "body": "{\"modelId\":\"us.anthropic.claude-sonnet-4-6\",\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"How many primes are below 60? Reply with the number only.\"}]}],\"inferenceConfig\":{\"maxTokens\":4000},\"additionalModelRequestFields\":{\"thinking\":{\"type\":\"adaptive\",\"display\":\"summarized\"},\"output_config\":{\"effort\":\"high\"}},\"serviceTier\":{\"type\":\"default\"},\"requestMetadata\":{\"suite\":\"opencode-ai\"}}" + }, + "response": { + "status": 200, + "headers": { + "content-type": "application/vnd.amazon.eventstream" + }, + "body": "AAAAqwAAAFLnsEE2CzpldmVudC10eXBlBwAMbWVzc2FnZVN0YXJ0DTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1QiLCJyb2xlIjoiYXNzaXN0YW50In16qcl8AAAAvgAAAFc/2q1LCzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiUHIifX0sInAiOiJhYmNkZWZnaGlqa2xtbiJ9KsuSDAAAAPgAAABX6GkAogs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsidGV4dCI6ImltZXMgYmVsb3cgNjA6In19LCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NTY3In1+JGFAAAAAvAAAAFdFGv4rCzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiXG4yIn19LCJwIjoiYWJjZGVmZ2hpamsifd/D1UcAAADmAAAAVze5KUELOmV2ZW50LXR5cGUHABFjb250ZW50QmxvY2tEZWx0YQ06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7ImNvbnRlbnRCbG9ja0luZGV4IjowLCJkZWx0YSI6eyJyZWFzb25pbmdDb250ZW50Ijp7InRleHQiOiIsIDMsIDUsICJ9fSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVViJ94gGywwAAAO0AAABXQGkYUAs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsidGV4dCI6IjcsIDExLCAxMywifX0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaMCJ9HGS9oAAAAN0AAABX4Uig1gs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsidGV4dCI6IiAxNywgMTksIDIzIn19LCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKIn1J+fHjAAAA0gAAAFdjGDcHCzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiLCAyOSwgMzEsICJ9fSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6In3fWx7pAAAA2wAAAFduCFV2CzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiMzcsIDQxLCA0MywifX0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdIIn3POmzBAAAA1AAAAFfsWMKnCzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiIDQ3LCA1MywgNTkifX0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekEifX/dw1QAAADfAAAAV5uI87YLOmV2ZW50LXR5cGUHABFjb250ZW50QmxvY2tEZWx0YQ06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7ImNvbnRlbnRCbG9ja0luZGV4IjowLCJkZWx0YSI6eyJyZWFzb25pbmdDb250ZW50Ijp7InRleHQiOiJcblxuVGhhdCJ9fSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PIn0nPZ3pAAAA0AAAAFcZ2GRnCzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiJ3MgMTcifX0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQyJ9ANoZdAAAANEAAABXJLhN1ws6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsidGV4dCI6IiBwcmltZXMuIn19LCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBIn3Hr86AAAAA0wAAAFdeeB63CzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwiZGVsdGEiOnsicmVhc29uaW5nQ29udGVudCI6eyJ0ZXh0IjoiIn19LCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKSyJ99+quegAAApYAAABXg6NohQs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsic2lnbmF0dXJlIjoiRXNFQ0Nud0lFeEFCR0FJcVFKeE9CNGF5MjA0QWtxbTFEMnl3OG5CZXRTNzhKTEZIR0JVYzN0MGJoc205ZDVpRm9DY0ZsanI4OThhc2tQWGN4U2JyaklRUWMwS0V5SUdtd1FBemtqRXlFV05zWVhWa1pTMXpiMjV1WlhRdE5DMDJPQUJDQ0hSb2FXNXJhVzVuV2d3eU16STNOekU0TlRZM09ER29BWnJJKzlZR0VneWNVNy9ydnROZVdEYUtJbm9hREtQb0ZKQ1VCa3QwKzlFM0JTSXc4OUJSVDdJWVZTVkFtN3Voakg0Q1Z5TmJobFFkZmNLNHZqN2o1QTkwWWRzRytPd0pzU3ZtajNjUE1vQmhIMEV6S25NNm40MVhvek1acHJLRVFVejBxcmJCZVJJNlMvd0ludHc0bTNKNkUybUNkYktKUkN3SzJSS1owNFBKUnNEdUFRUDBnSTFnd1p0RWQzZzBNekNkZ3ZydlBvRmk4UG53ZlprMHp2UzVIVC85TGJOZlJodmFOckRpOVQyZy9EODkzQVljYlJwNDV3ays2RHFYczAwY3dsLzdMVHpZR0FFPSJ9fSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVIn0Kc31GAAAApgAAAFYYTUGeCzpldmVudC10eXBlBwAQY29udGVudEJsb2NrU3RvcA06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7ImNvbnRlbnRCbG9ja0luZGV4IjowLCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSCJ9XtkDNQAAAK4AAABXXzo6yQs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjEsImRlbHRhIjp7InRleHQiOiIxNyJ9LCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFycyJ9vjLcPQAAALIAAABWjS1w3As6ZXZlbnQtdHlwZQcAEGNvbnRlbnRCbG9ja1N0b3ANOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1Qifa+sENsAAACiAAAAUXOpcv0LOmV2ZW50LXR5cGUHAAttZXNzYWdlU3RvcA06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7InAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkciLCJzdG9wUmVhc29uIjoiZW5kX3R1cm4ifbmQA7wAAAEgAAAATv7bT18LOmV2ZW50LXR5cGUHAAhtZXRhZGF0YQ06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7Im1ldHJpY3MiOnsibGF0ZW5jeU1zIjoxMTYxfSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU4iLCJzZXJ2aWNlVGllciI6eyJ0eXBlIjoiZGVmYXVsdCJ9LCJ1c2FnZSI6eyJpbnB1dFRva2VucyI6MjIsIm91dHB1dFRva2VucyI6ODUsInNlcnZlclRvb2xVc2FnZSI6e30sInRvdGFsVG9rZW5zIjoxMDd9fc422g8=", + "bodyEncoding": "base64" + } + } + ] +} diff --git a/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier.json b/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier.json new file mode 100644 index 00000000000..229535d8e15 --- /dev/null +++ b/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier.json @@ -0,0 +1,34 @@ +{ + "version": 1, + "metadata": { + "tags": [ + "prefix:bedrock-converse-options", + "provider:amazon-bedrock", + "protocol:bedrock-converse", + "reasoning" + ], + "name": "bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier", + "recordedAt": "2026-10-26T05:24:44.284Z" + }, + "interactions": [ + { + "transport": "http", + "request": { + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/openai.gpt-oss-120b-1%3A0/converse-stream", + "headers": { + "content-type": "application/json" + }, + "body": "{\"modelId\":\"openai.gpt-oss-120b-1:0\",\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"What is 17*23? Reply with the number only.\"}]}],\"inferenceConfig\":{\"maxTokens\":1000},\"additionalModelRequestFields\":{\"reasoning_effort\":\"low\"},\"serviceTier\":{\"type\":\"priority\"},\"requestMetadata\":{\"suite\":\"opencode-ai\"}}" + }, + "response": { + "status": 200, + "headers": { + "content-type": "application/vnd.amazon.eventstream" + }, + "body": "AAAAnQAAAFLJ0QwQCzpldmVudC10eXBlBwAMbWVzc2FnZVN0YXJ0DTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGIiwicm9sZSI6ImFzc2lzdGFudCJ9EQf77QAAAMkAAABXdCiRlAs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InRleHQiOiIifSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVViJ9oXumJQAAAMAAAABWDj/Dcws6ZXZlbnQtdHlwZQcAEGNvbnRlbnRCbG9ja1N0b3ANOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVowMTIzNDU2NyJ9EPTSwQAAAMkAAABXdCiRlAs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjEsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsidGV4dCI6Ikp1c3QgY29tcHV0ZSAxNyoyMyA9IDM5MS4ifX0sInAiOiJhYiJ9u2fddQAAALcAAABWRc3/rAs6ZXZlbnQtdHlwZQcAEGNvbnRlbnRCbG9ja1N0b3ANOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MSwicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWSJ9hmJaHgAAAKMAAABXp6r+eAs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjIsImRlbHRhIjp7InRleHQiOiIzOTEifSwicCI6ImFiY2RlZmcifT1TPPUAAADBAAAAVjNf6sMLOmV2ZW50LXR5cGUHABBjb250ZW50QmxvY2tTdG9wDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjIsInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaMDEyMzQ1Njc4In0WfQjAAAAAnwAAAFEqGA7KCzpldmVudC10eXBlBwALbWVzc2FnZVN0b3ANOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNEIiwic3RvcFJlYXNvbiI6ImVuZF90dXJuIn2rNcIbAAABIQAAAE7Du2bvCzpldmVudC10eXBlBwAIbWV0YWRhdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJtZXRyaWNzIjp7ImxhdGVuY3lNcyI6MTU3NX0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OIiwic2VydmljZVRpZXIiOnsidHlwZSI6InByaW9yaXR5In0sInVzYWdlIjp7ImlucHV0VG9rZW5zIjo4MCwib3V0cHV0VG9rZW5zIjoyMSwic2VydmVyVG9vbFVzYWdlIjp7fSwidG90YWxUb2tlbnMiOjEwMX19od/llw==", + "bodyEncoding": "base64" + } + } + ] +} diff --git a/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-nova-2-reasoning-effort.json b/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-nova-2-reasoning-effort.json new file mode 100644 index 00000000000..7d775fa5ac5 --- /dev/null +++ b/packages/ai/test/fixtures/recordings/bedrock-converse-options/sends-nova-2-reasoning-effort.json @@ -0,0 +1,34 @@ +{ + "version": 1, + "metadata": { + "tags": [ + "prefix:bedrock-converse-options", + "provider:amazon-bedrock", + "protocol:bedrock-converse", + "reasoning" + ], + "name": "bedrock-converse-options/sends-nova-2-reasoning-effort", + "recordedAt": "2026-10-26T05:24:45.686Z" + }, + "interactions": [ + { + "transport": "http", + "request": { + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.amazon.nova-2-lite-v1%3A0/converse-stream", + "headers": { + "content-type": "application/json" + }, + "body": "{\"modelId\":\"us.amazon.nova-2-lite-v1:0\",\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"What is 17*23? Reply with the number only.\"}]}],\"inferenceConfig\":{\"maxTokens\":1000},\"additionalModelRequestFields\":{\"reasoningConfig\":{\"type\":\"enabled\",\"maxReasoningEffort\":\"low\"}}}" + }, + "response": { + "status": 200, + "headers": { + "content-type": "application/vnd.amazon.eventstream" + }, + "body": "AAAAmAAAAFIBMYNgCzpldmVudC10eXBlBwAMbWVzc2FnZVN0YXJ0DTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsicCI6ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QSIsInJvbGUiOiJhc3Npc3RhbnQifRK9PwwAAADaAAAAV1NofMYLOmV2ZW50LXR5cGUHABFjb250ZW50QmxvY2tEZWx0YQ06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7ImNvbnRlbnRCbG9ja0luZGV4IjowLCJkZWx0YSI6eyJyZWFzb25pbmdDb250ZW50Ijp7InRleHQiOiJbUkVEQUNURURdIn19LCJwIjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSCJ966snJwAAAM8AAABX+2hkNAs6ZXZlbnQtdHlwZQcAEWNvbnRlbnRCbG9ja0RlbHRhDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjAsImRlbHRhIjp7InJlYXNvbmluZ0NvbnRlbnQiOnsidGV4dCI6Ii4ifX0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRiJ9txtPJQAAAIkAAABWW9z5Sws6ZXZlbnQtdHlwZQcAEGNvbnRlbnRCbG9ja1N0b3ANOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MCwicCI6ImFiY2RlIn3nHPCvAAAApwAAAFdSKli4CzpldmVudC10eXBlBwARY29udGVudEJsb2NrRGVsdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJjb250ZW50QmxvY2tJbmRleCI6MSwiZGVsdGEiOnsidGV4dCI6IjM5MSJ9LCJwIjoiYWJjZGVmZ2hpamsifVFEEycAAACHAAAAVuTsRyoLOmV2ZW50LXR5cGUHABBjb250ZW50QmxvY2tTdG9wDTpjb250ZW50LXR5cGUHABBhcHBsaWNhdGlvbi9qc29uDTptZXNzYWdlLXR5cGUHAAVldmVudHsiY29udGVudEJsb2NrSW5kZXgiOjEsInAiOiJhYmMifVAMp9gAAACjAAAAUU7JW00LOmV2ZW50LXR5cGUHAAttZXNzYWdlU3RvcA06Y29udGVudC10eXBlBwAQYXBwbGljYXRpb24vanNvbg06bWVzc2FnZS10eXBlBwAFZXZlbnR7InAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdIIiwic3RvcFJlYXNvbiI6ImVuZF90dXJuIn3wGF+JAAABCwAAAE5IylFKCzpldmVudC10eXBlBwAIbWV0YWRhdGENOmNvbnRlbnQtdHlwZQcAEGFwcGxpY2F0aW9uL2pzb24NOm1lc3NhZ2UtdHlwZQcABWV2ZW50eyJtZXRyaWNzIjp7ImxhdGVuY3lNcyI6MTMzMn0sInAiOiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWCIsInVzYWdlIjp7ImlucHV0VG9rZW5zIjoxMDksIm91dHB1dFRva2VucyI6MjQ2LCJzZXJ2ZXJUb29sVXNhZ2UiOnt9LCJ0b3RhbFRva2VucyI6MzU1fX3ERMiI", + "bodyEncoding": "base64" + } + } + ] +} diff --git a/packages/ai/test/fixtures/recordings/cloudflare-workers-ai-extraction/extracts-invoice-fields.json b/packages/ai/test/fixtures/recordings/cloudflare-workers-ai-extraction/extracts-invoice-fields.json new file mode 100644 index 00000000000..f69c61f469f --- /dev/null +++ b/packages/ai/test/fixtures/recordings/cloudflare-workers-ai-extraction/extracts-invoice-fields.json @@ -0,0 +1,33 @@ +{ + "version": 1, + "metadata": { + "model": "@cf/cloudflare/clairic", + "tags": [ + "prefix:cloudflare-workers-ai-extraction", + "provider:cloudflare-workers-ai", + "protocol:cloudflare-run-extraction" + ], + "name": "cloudflare-workers-ai-extraction/extracts-invoice-fields", + "recordedAt": "2026-10-25T05:21:37.425Z" + }, + "interactions": [ + { + "transport": "http", + "request": { + "method": "POST", + "url": "https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/clairic", + "headers": { + "content-type": "application/json" + }, + "body": "{\"model\":\"@cf/cloudflare/clairic\",\"state\":\"Invoice INV-2291 from Northwind Supply, issued 2026-09-02, net 30. 4 pallets at $250.00 each, shipping $80.00. Contact: Dana Ruiz, Priya Shah.\",\"fields\":{\"invoiceNumber\":{\"type\":\"text\"},\"dueDate\":{\"type\":\"date\",\"instructions\":\"Issue date plus the net payment days\"},\"total\":{\"type\":\"number\",\"instructions\":\"Amount due including shipping\",\"unit\":\"USD\",\"decimals\":2},\"contacts\":{\"type\":\"list\",\"items\":\"text\"},\"poNumber\":{\"type\":\"text\",\"instructions\":\"Purchase order number\"}}}" + }, + "response": { + "status": 200, + "headers": { + "content-type": "application/json" + }, + "body": "{\"result\":{\"model\":\"clairic\",\"answers\":{\"invoiceNumber\":{\"type\":\"text\",\"p_null\":0.000005373362000682391,\"span\":[8,16],\"guess\":\"INV-2291\",\"confidence\":0.9999842643737793,\"value\":\"INV-2291\"},\"dueDate\":{\"type\":\"date\",\"p_null\":0.0000010241710697300732,\"guess\":\"2026-10-02\",\"confidence\":0.9999879599643642,\"value\":\"2026-10-02\"},\"total\":{\"type\":\"number\",\"p_null\":5.380287575462717e-7,\"guess\":1080,\"confidence\":0.9999545827141966,\"value\":1080},\"contacts\":{\"type\":\"list\",\"value\":[\"Dana Ruiz\",\"Priya Shah\"],\"spans\":[[120,129],[131,141]],\"confidence\":0.999993443529213},\"poNumber\":{\"type\":\"text\",\"p_null\":0.9999990463256836,\"span\":[8,16],\"guess\":\"INV-2291\",\"confidence\":0.9991962313652039,\"value\":null}},\"truncated\":false,\"usage\":{\"state_tokens\":61,\"image_tokens\":0,\"schema_tokens\":408,\"input_tokens\":591,\"output_tokens\":0,\"passes\":3}},\"success\":true,\"errors\":[],\"messages\":[]}" + } + } + ] +} diff --git a/packages/ai/test/http-timeout.test.ts b/packages/ai/test/http-timeout.test.ts index 47dfd58e430..08ea1096bb8 100644 --- a/packages/ai/test/http-timeout.test.ts +++ b/packages/ai/test/http-timeout.test.ts @@ -1,8 +1,8 @@ import { describe, expect } from "bun:test" import { Deferred, Effect, Fiber } from "effect" import * as TestClock from "effect/testing/TestClock" -import { HttpOptions, LLM, mergeHttpOptions } from "../src/effect.js" -import { LLMClient } from "../src/route.js" +import { HttpOptions, LLM } from "../src/effect.js" +import { LLMClient, mergeHttpOptions } from "../src/route.js" import { configure } from "../src/providers/openai.js" import { dynamicResponse } from "./lib/http.js" import { deltaChunk, finishChunk } from "./lib/openai-chunks.js" diff --git a/packages/ai/test/media.test.ts b/packages/ai/test/media.test.ts index c6cb3beefd5..5bd2891817f 100644 --- a/packages/ai/test/media.test.ts +++ b/packages/ai/test/media.test.ts @@ -291,6 +291,16 @@ describe("Media", () => { yield* fs.writeFile(plain, new TextEncoder().encode("# hi")) expect((yield* Media.file(plain)).mediaType).toBe("text/markdown") + for (const [name, mediaType] of [ + ["photo.avif", "image/avif"], + ["photo.HEIC", "image/heic"], + ["photo.heif", "image/heif"], + ["clip.mov", "video/quicktime"], + ]) { + yield* fs.writeFile(`${dir}/${name}`, Uint8Array.from([1, 2, 3])) + expect((yield* Media.file(`${dir}/${name}`)).mediaType).toBe(mediaType) + } + const target = `${dir}/copy.png` yield* Media.write(Media.base64("AQID", "image/png"), target) expect(yield* fs.readFile(target)).toEqual(Uint8Array.from([1, 2, 3])) diff --git a/packages/ai/test/provider-options/amazon-bedrock.types.ts b/packages/ai/test/provider-options/amazon-bedrock.types.ts new file mode 100644 index 00000000000..1c40584e7b7 --- /dev/null +++ b/packages/ai/test/provider-options/amazon-bedrock.types.ts @@ -0,0 +1,33 @@ +import { LLM } from "../../src/effect.js" +import { AmazonBedrock } from "../../src/providers.js" + +const model = AmazonBedrock.provider.model("us.anthropic.claude-sonnet-4-6") + +LLM.request({ + model, + prompt: "Hello", + providerOptions: { + effort: "future-effort", + serviceTier: "future-tier", + thinking: { type: "adaptive", display: "future-display" }, + guardrail: { identifier: "abc123", version: "DRAFT", trace: "future-trace", streamProcessingMode: "future-mode" }, + outputFormat: { type: "future-format", schema: { type: "object" } }, + requestMetadata: { suite: "opencode-ai" }, + }, +}) + +AmazonBedrock.model("us.amazon.nova-2-lite-v1:0", { effort: "low", serviceTier: "flex" }) + +LLM.request({ + model, + prompt: "Hello", + // @ts-expect-error Bedrock thinking modes are a fixed union. + providerOptions: { thinking: { type: "automatic" } }, +}) + +LLM.request({ + model, + prompt: "Hello", + // @ts-expect-error Converse request metadata values are strings. + providerOptions: { requestMetadata: { attempt: 1 } }, +}) diff --git a/packages/ai/test/provider-options/anthropic.types.ts b/packages/ai/test/provider-options/anthropic.types.ts index 89438bf967d..92954fd2e5f 100644 --- a/packages/ai/test/provider-options/anthropic.types.ts +++ b/packages/ai/test/provider-options/anthropic.types.ts @@ -10,13 +10,14 @@ LLM.request({ providerOptions: { serviceTier: "future-tier", thinking: { type: "adaptive", display: "future-display" }, + cacheControl: { type: "ephemeral", ttl: "30m" }, }, }) LLM.request({ model, prompt: "Hello", providerOptions: { - // @ts-expect-error Anthropic cache TTL values are protocol constraints. + // @ts-expect-error Cache TTLs are durations such as "5m" or "1h". cacheControl: { type: "ephemeral", ttl: "future-ttl" }, }, }) diff --git a/packages/ai/test/provider.types.ts b/packages/ai/test/provider.types.ts deleted file mode 100644 index c8dbf820083..00000000000 --- a/packages/ai/test/provider.types.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { Provider } from "../src/provider.js" -import { ProviderID, type LanguageModel } from "../src/schema/index.js" - -declare const model: (id: string) => LanguageModel -declare const requiredModel: (id: string, options: { readonly baseURL: string }) => LanguageModel -declare const chat: (id: string, options: { readonly apiKey: string }) => LanguageModel - -Provider.make({ - id: ProviderID.make("example"), - model, -}) - -Provider.make({ - id: ProviderID.make("bad"), - model, - // @ts-expect-error provider definitions should not grow accidental top-level fields. - routes: [], -}) - -const requiredProvider = Provider.make({ - id: ProviderID.make("required"), - model: requiredModel, -}) - -// Provider.make is advanced structural typing coverage; built-in providers use -// configure(...).model(id) facades instead of second-argument selectors. -requiredProvider.model("custom", { baseURL: "https://example.com/v1" }) - -// @ts-expect-error Provider.make preserves required model options. -requiredProvider.model("custom") - -const multiApiProvider = Provider.make({ - id: ProviderID.make("multi-api"), - model, - apis: { chat }, -}) - -multiApiProvider.apis.chat("chat-model", { apiKey: "key" }) - -// @ts-expect-error Provider.make preserves API-specific option types. -multiApiProvider.apis.chat("chat-model") diff --git a/packages/ai/test/provider/anthropic-messages.test.ts b/packages/ai/test/provider/anthropic-messages.test.ts index 685c4fe1d84..c1b264e2fe9 100644 --- a/packages/ai/test/provider/anthropic-messages.test.ts +++ b/packages/ai/test/provider/anthropic-messages.test.ts @@ -2430,12 +2430,12 @@ describe("Anthropic Messages route", () => { }), ) - it.effect("maps ttlSeconds >= 3600 to cache_control ttl: '1h'", () => + it.effect("sends the hint ttl on cache_control", () => Effect.gen(function* () { const prepared = yield* compileRequest( LLM.request({ model, - system: { type: "text", text: "system", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) }, + system: { type: "text", text: "system", cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }, prompt: "hi", }), ) diff --git a/packages/ai/test/provider/bedrock-converse-cache.test.ts b/packages/ai/test/provider/bedrock-converse-cache.test.ts index 5978cf11a82..89b8d336ee8 100644 --- a/packages/ai/test/provider/bedrock-converse-cache.test.ts +++ b/packages/ai/test/provider/bedrock-converse-cache.test.ts @@ -32,7 +32,7 @@ describe("Bedrock Converse cache policy", () => { it.effect(`omits checkpoints for ${id} (${JSON.stringify(policy)})`, () => Effect.gen(function* () { // Exercise both automatic placement and manual hints at every lowering site. - const cache = policy === "none" ? new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) : undefined + const cache = policy === "none" ? new CacheHint({ type: "ephemeral", ttl: "1h" }) : undefined const prepared = yield* compileRequest( LLM.request({ model: bedrock.model(id), @@ -84,8 +84,8 @@ describe("Bedrock Converse cache policy", () => { ["arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-sonnet-4-6", "1h"], ["arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.anthropic.claude-sonnet-4-6", "1h"], ] as const) { - for (const ttlSeconds of [undefined, 3600]) { - it.effect(`preserves Claude checkpoints for ${id} (TTL: ${ttlSeconds ?? "default"})`, () => + for (const ttlRequest of [undefined, "1h"] as const) { + it.effect(`preserves Claude checkpoints for ${id} (TTL: ${ttlRequest ?? "default"})`, () => Effect.gen(function* () { const prepared = yield* compileRequest( LLM.request({ @@ -97,11 +97,11 @@ describe("Bedrock Converse cache policy", () => { tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object" } }], prompt: "Question", cache: - ttlSeconds === undefined ? undefined : { tools: true, system: true, messages: { tail: 1 }, ttlSeconds }, + ttlRequest === undefined ? undefined : { tools: true, system: true, messages: { tail: 1 }, ttl: ttlRequest }, }), ) const marker = { - cachePoint: ttlSeconds === undefined || ttl === undefined ? { type: "default" } : { type: "default", ttl }, + cachePoint: ttlRequest === undefined || ttl === undefined ? { type: "default" } : { type: "default", ttl }, } expect(prepared.body).toMatchObject({ @@ -110,7 +110,7 @@ describe("Bedrock Converse cache policy", () => { system: [{ text: "Agent" }, marker, { text: "Project" }, marker], messages: [{ role: "user", content: [{ text: "Question" }, marker] }], }) - if (ttlSeconds === undefined || ttl === undefined) + if (ttlRequest === undefined || ttl === undefined) expect(JSON.stringify(prepared.body)).not.toContain('"ttl"') }), ) @@ -119,9 +119,9 @@ describe("Bedrock Converse cache policy", () => { const arn = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123" - for (const ttlSeconds of [undefined, 3600]) { + for (const ttlRequest of [undefined, "1h"] as const) { it.effect( - `emits checkpoints for an opaque ARN declaring the Anthropic cache format (TTL: ${ttlSeconds ?? "default"})`, + `emits checkpoints for an opaque ARN declaring the Anthropic cache format (TTL: ${ttlRequest ?? "default"})`, () => Effect.gen(function* () { const prepared = yield* compileRequest( @@ -134,10 +134,10 @@ describe("Bedrock Converse cache policy", () => { tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object" } }], prompt: "Question", cache: - ttlSeconds === undefined ? undefined : { tools: true, system: true, messages: { tail: 1 }, ttlSeconds }, + ttlRequest === undefined ? undefined : { tools: true, system: true, messages: { tail: 1 }, ttl: ttlRequest }, }), ) - const marker = { cachePoint: ttlSeconds === undefined ? { type: "default" } : { type: "default", ttl: "1h" } } + const marker = { cachePoint: ttlRequest === undefined ? { type: "default" } : { type: "default", ttl: "1h" } } expect(prepared.body).toMatchObject({ modelId: arn, @@ -145,7 +145,7 @@ describe("Bedrock Converse cache policy", () => { system: [{ text: "Agent" }, marker, { text: "Project" }, marker], messages: [{ role: "user", content: [{ text: "Question" }, marker] }], }) - if (ttlSeconds === undefined) expect(JSON.stringify(prepared.body)).not.toContain('"ttl"') + if (ttlRequest === undefined) expect(JSON.stringify(prepared.body)).not.toContain('"ttl"') }), ) } diff --git a/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts b/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts new file mode 100644 index 00000000000..20ecd3ff606 --- /dev/null +++ b/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts @@ -0,0 +1,119 @@ +import { describe, expect } from "bun:test" +import { Effect } from "effect" +import { LLM } from "../../src/effect.js" +import { LLMClient } from "../../src/route.js" +import { AmazonBedrock } from "../../src/providers.js" +import { recordedTests } from "../recorded-test.js" + +const RECORDING_REGION = process.env.BEDROCK_RECORDING_REGION ?? "us-east-1" + +const bedrock = (id: string, settings: Omit[1], "apiKey" | "region">) => + AmazonBedrock.model(id, { + apiKey: process.env.AWS_BEARER_TOKEN_BEDROCK ?? "fixture", + region: RECORDING_REGION, + ...settings, + }) + +const recorded = recordedTests({ + prefix: "bedrock-converse-options", + provider: "amazon-bedrock", + protocol: "bedrock-converse", + requires: ["AWS_BEARER_TOKEN_BEDROCK"], +}) + +describe("Bedrock Converse options recorded", () => { + // Claude on Bedrock only accepts the default tier; other tiers fail with "not supported for this model". + recorded.effect.with( + "sends Claude effort with adaptive thinking, service tier and request metadata", + { tags: ["reasoning"] }, + () => + Effect.gen(function* () { + const response = yield* LLMClient.generate( + LLM.request({ + id: "recorded_bedrock_options_claude", + model: bedrock("us.anthropic.claude-sonnet-4-6", { + effort: "high", + thinking: { type: "adaptive", display: "summarized" }, + serviceTier: "default", + requestMetadata: { suite: "opencode-ai" }, + }), + prompt: "How many primes are below 60? Reply with the number only.", + cache: "none", + generation: { maxTokens: 4_000 }, + }), + ) + + expect(response.finishReason?.normalized).toBe("stop") + expect(response.reasoning.length).toBeGreaterThan(0) + expect(response.text).toContain("17") + }), + ) + + recorded.effect.with("sends gpt-oss reasoning effort with the priority tier", { tags: ["reasoning"] }, () => + Effect.gen(function* () { + const response = yield* LLMClient.generate( + LLM.request({ + id: "recorded_bedrock_options_gpt_oss", + model: bedrock("openai.gpt-oss-120b-1:0", { + effort: "low", + serviceTier: "priority", + requestMetadata: { suite: "opencode-ai" }, + }), + prompt: "What is 17*23? Reply with the number only.", + cache: "none", + generation: { maxTokens: 1_000 }, + }), + ) + + expect(response.finishReason?.normalized).toBe("stop") + expect(response.reasoning.length).toBeGreaterThan(0) + expect(response.text).toContain("391") + }), + ) + + recorded.effect.with("sends Nova 2 reasoning effort", { tags: ["reasoning"] }, () => + Effect.gen(function* () { + const response = yield* LLMClient.generate( + LLM.request({ + id: "recorded_bedrock_options_nova", + model: bedrock("us.amazon.nova-2-lite-v1:0", { effort: "low" }), + prompt: "What is 17*23? Reply with the number only.", + cache: "none", + generation: { maxTokens: 1_000 }, + }), + ) + + expect(response.finishReason?.normalized).toBe("stop") + expect(response.reasoning.length).toBeGreaterThan(0) + expect(response.text).toContain("391") + }), + ) + + recorded.effect("constrains Claude output to a JSON schema", () => + Effect.gen(function* () { + const response = yield* LLMClient.generate( + LLM.request({ + id: "recorded_bedrock_options_output_format", + model: bedrock("us.anthropic.claude-sonnet-4-6", { + outputFormat: { + type: "json_schema", + name: "answer", + schema: { + type: "object", + properties: { product: { type: "integer" } }, + required: ["product"], + additionalProperties: false, + }, + }, + }), + prompt: "What is 17*23?", + cache: "none", + generation: { maxTokens: 200 }, + }), + ) + + expect(response.finishReason?.normalized).toBe("stop") + expect(JSON.parse(response.text)).toEqual({ product: 391 }) + }), + ) +}) diff --git a/packages/ai/test/provider/bedrock-converse-options.test.ts b/packages/ai/test/provider/bedrock-converse-options.test.ts new file mode 100644 index 00000000000..dfde0b8f6fd --- /dev/null +++ b/packages/ai/test/provider/bedrock-converse-options.test.ts @@ -0,0 +1,149 @@ +import { describe, expect } from "bun:test" +import { Effect } from "effect" +import { LLM } from "../../src/effect.js" +import { LLMClient } from "../../src/route.js" +import { compileRequest } from "../../src/route/client.js" +import { AmazonBedrock } from "../../src/providers.js" +import { it } from "../lib/effect.js" +import { dynamicResponse } from "../lib/http.js" + +const bedrock = (id: string, settings: Omit[1], "apiKey" | "baseURL">) => + AmazonBedrock.model(id, { baseURL: "https://bedrock-runtime.test", apiKey: "test-bearer", ...settings }) + +const request = (model: ReturnType) => + LLM.request({ model, prompt: "Say hello.", cache: "none", generation: { maxTokens: 64 } }) + +const body = (model: ReturnType) => + compileRequest(request(model)).pipe(Effect.map((prepared) => prepared.body)) + +const fields = (model: ReturnType) => + body(model).pipe(Effect.map((prepared) => prepared.additionalModelRequestFields)) + +const binding = { prefix_mismatch_behavior: "drop_block" } +const beta = ["thinking-binding-controls-2026-08-01"] + +describe("Bedrock Converse options", () => { + it.effect("maps effort to each model family's field", () => + Effect.gen(function* () { + expect(yield* fields(bedrock("us.anthropic.claude-sonnet-4-6", { effort: "high" }))).toEqual({ + thinking: { type: "adaptive" }, + output_config: { effort: "high" }, + }) + expect(yield* fields(bedrock("global.anthropic.claude-opus-5-5", { effort: "high" }))).toEqual({ + thinking: { type: "adaptive", block_binding: binding }, + output_config: { effort: "high" }, + anthropic_beta: beta, + }) + expect(yield* fields(bedrock("openai.gpt-oss-120b-1:0", { effort: "low" }))).toEqual({ reasoning_effort: "low" }) + expect(yield* fields(bedrock("openai.gpt-5.6", { effort: "low" }))).toEqual({ reasoning: { effort: "low" } }) + expect(yield* fields(bedrock("us.xai.grok-4.6", { effort: "low" }))).toEqual({ reasoning: { effort: "low" } }) + expect(yield* fields(bedrock("us.amazon.nova-2-lite-v1:0", { effort: "medium" }))).toEqual({ + reasoningConfig: { type: "enabled", maxReasoningEffort: "medium" }, + }) + }), + ) + + for (const id of ["us.anthropic.claude-opus-4-5-20251101-v1:0", "us.anthropic.claude-3-7-sonnet-20250219-v1:0"]) + it.effect(`keeps ${id} effort beside its manual thinking budget`, () => + Effect.gen(function* () { + expect(yield* fields(bedrock(id, { effort: "high" }))).toEqual({ output_config: { effort: "high" } }) + expect( + yield* fields(bedrock(id, { effort: "high", thinking: { type: "enabled", budgetTokens: 1_024 } })), + ).toEqual({ thinking: { type: "enabled", budget_tokens: 1_024 }, output_config: { effort: "high" } }) + }), + ) + + it.effect("sends explicit adaptive and disabled Claude thinking", () => + Effect.gen(function* () { + expect( + yield* fields( + bedrock("us.anthropic.claude-sonnet-4-6", { + effort: "low", + thinking: { type: "adaptive", display: "summarized" }, + }), + ), + ).toEqual({ thinking: { type: "adaptive", display: "summarized" }, output_config: { effort: "low" } }) + expect(yield* fields(bedrock("global.anthropic.claude-opus-5-5", { thinking: { type: "disabled" } }))).toEqual({ + thinking: { type: "disabled" }, + }) + }), + ) + + it.effect("omits maxTokens for Nova 2 at high effort", () => + Effect.gen(function* () { + expect((yield* body(bedrock("us.amazon.nova-2-lite-v1:0", { effort: "high" }))).inferenceConfig).toBeUndefined() + }), + ) + + it.effect("sends service tier, guardrail, structured output and request metadata", () => + Effect.gen(function* () { + const prepared = yield* body( + bedrock("us.anthropic.claude-sonnet-4-6", { + serviceTier: "priority", + guardrail: { identifier: "abc123", version: "1", trace: "enabled", streamProcessingMode: "async" }, + outputFormat: { + type: "json_schema", + name: "answer", + schema: { type: "object", properties: { product: { type: "integer" } } }, + }, + requestMetadata: { suite: "opencode-ai" }, + }), + ) + + expect(prepared).toEqual({ + modelId: "us.anthropic.claude-sonnet-4-6", + messages: [{ role: "user", content: [{ text: "Say hello." }] }], + inferenceConfig: { maxTokens: 64 }, + serviceTier: { type: "priority" }, + guardrailConfig: { + guardrailIdentifier: "abc123", + guardrailVersion: "1", + trace: "enabled", + streamProcessingMode: "async", + }, + outputConfig: { + textFormat: { + type: "json_schema", + structure: { + jsonSchema: { + name: "answer", + schema: '{"type":"object","properties":{"product":{"type":"integer"}}}', + }, + }, + }, + }, + requestMetadata: { suite: "opencode-ai" }, + }) + }), + ) + + it.effect("lets http.body override typed options field by field", () => + Effect.gen(function* () { + const sent: string[] = [] + yield* LLMClient.generate( + request( + bedrock("us.anthropic.claude-sonnet-4-6", { + effort: "low", + serviceTier: "priority", + body: { additionalModelRequestFields: { output_config: { effort: "max" } }, serviceTier: { type: "flex" } }, + }), + ), + ).pipe( + Effect.provide( + dynamicResponse((input) => + Effect.sync(() => { + sent.push(input.text) + return input.respond("{}", { status: 400 }) + }), + ), + ), + Effect.ignore, + ) + + expect(JSON.parse(sent[0]!)).toMatchObject({ + additionalModelRequestFields: { thinking: { type: "adaptive" }, output_config: { effort: "max" } }, + serviceTier: { type: "flex" }, + }) + }), + ) +}) diff --git a/packages/ai/test/provider/bedrock-converse.test.ts b/packages/ai/test/provider/bedrock-converse.test.ts index 15a86db20b6..d2dcada6319 100644 --- a/packages/ai/test/provider/bedrock-converse.test.ts +++ b/packages/ai/test/provider/bedrock-converse.test.ts @@ -849,6 +849,28 @@ describe("Bedrock Converse route", () => { }), ) + it.effect("raw events carry the event payload without decoder fields or padding", () => + Effect.gen(function* () { + const body = eventStreamBody( + ["contentBlockDelta", { contentBlockIndex: 0, delta: { text: "Hi" }, p: "abc" }], + ["messageStop", { stopReason: "end_turn" }], + ["metadata", { usage: { inputTokens: 5, outputTokens: 1, totalTokens: 6 } }], + ) + const events = Array.from( + yield* LLMClient.stream(LLMRequest.update(baseRequest, { includeRaw: true })).pipe( + Stream.runCollect, + Effect.provide(fixedBytes(body)), + ), + ) + + expect(events.filter((event) => event.type === "raw").map((event) => event.data)).toEqual([ + { contentBlockDelta: { contentBlockIndex: 0, delta: { text: "Hi" } } }, + { messageStop: { stopReason: "end_turn" } }, + { metadata: { usage: { inputTokens: 5, outputTokens: 1, totalTokens: 6 } } }, + ]) + }), + ) + it.effect("rejects truncated event-stream frames after message stop", () => Effect.gen(function* () { const partialFrames = [ @@ -2325,9 +2347,9 @@ describe("Bedrock Converse route", () => { }), ) - it.effect("maps ttlSeconds >= 3600 to cachePoint ttl: '1h'", () => + it.effect("sends the hint ttl on cachePoint", () => Effect.gen(function* () { - const cache = new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) + const cache = new CacheHint({ type: "ephemeral", ttl: "1h" }) const prepared = yield* compileRequest( LLM.request({ model, diff --git a/packages/ai/test/provider/digitalocean.test.ts b/packages/ai/test/provider/digitalocean.test.ts index cef03dc16a6..a14483713d0 100644 --- a/packages/ai/test/provider/digitalocean.test.ts +++ b/packages/ai/test/provider/digitalocean.test.ts @@ -49,7 +49,7 @@ describe("DigitalOcean", () => { LLM.request({ model: DigitalOcean.configure({ apiKey: "test-key" }).model("anthropic-claude-fable-5.1"), system: [ - { type: "text", text: "Base agent", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3_600 }) }, + { type: "text", text: "Base agent", cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }, { type: "text", text: "Project instructions" }, ], tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }], diff --git a/packages/ai/test/provider/extraction.recorded.test.ts b/packages/ai/test/provider/extraction.recorded.test.ts new file mode 100644 index 00000000000..a815c9e5f0d --- /dev/null +++ b/packages/ai/test/provider/extraction.recorded.test.ts @@ -0,0 +1,46 @@ +import { describe, expect } from "bun:test" +import { Effect } from "effect" +import { Extraction } from "../../src/experimental.js" +import { CloudflareWorkersAI } from "../../src/providers.js" +import { recordedTests } from "../recorded-test.js" + +const cloudflareWorkersAI = recordedTests({ + prefix: "cloudflare-workers-ai-extraction", + provider: "cloudflare-workers-ai", + protocol: "cloudflare-run-extraction", + requires: ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_KEY"], + metadata: { model: "@cf/cloudflare/clairic" }, + options: { + redact: { url: (url: string) => url.replace(/\/client\/v4\/accounts\/[^/]+\//, "/client/v4/accounts/{account}/") }, + }, +}) + +describe("Extraction recorded", () => { + cloudflareWorkersAI.effect("extracts invoice fields", () => + Effect.gen(function* () { + const response = yield* Extraction.generate({ + model: CloudflareWorkersAI.configure({ + accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "fixture-account", + apiKey: process.env.CLOUDFLARE_API_KEY ?? "fixture", + }).experimental.extraction("@cf/cloudflare/clairic"), + input: + "Invoice INV-2291 from Northwind Supply, issued 2026-09-02, net 30. 4 pallets at $250.00 each, shipping $80.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", instructions: "Amount due including shipping" }, + contacts: { type: "list", items: "text" }, + poNumber: { type: "text", instructions: "Purchase order number" }, + }, + }) + expect(response.answers.invoiceNumber.value).toBe("INV-2291") + expect(response.answers.invoiceNumber.span).toEqual([8, 16]) + expect(response.answers.dueDate.value).toBe("2026-10-02") + expect(response.answers.total.value).toBe(1080) + expect(response.answers.contacts.value).toEqual(["Dana Ruiz", "Priya Shah"]) + expect(response.answers.poNumber.value).toBeNull() + expect(response.answers.poNumber.nullProbability).toBeGreaterThan(0.5) + expect(response.usage?.inputTokens).toBeGreaterThan(0) + }), + ) +}) diff --git a/packages/ai/test/provider/media-entrypoints.test.ts b/packages/ai/test/provider/media-entrypoints.test.ts new file mode 100644 index 00000000000..8c8333b5c92 --- /dev/null +++ b/packages/ai/test/provider/media-entrypoints.test.ts @@ -0,0 +1,305 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { Decision, DecisionClient, Image, ImageClient, type DecisionModel, type ImageModel } from "../../src/effect.js" +import { it } from "../lib/effect.js" +import { dynamicResponse, observe, type Call } from "../lib/http.js" + +const shared = { headers: { "x-test": "yes" }, body: { extra: true } } + +// Every request is answered with a 400, so each case only checks what the entrypoint sent. +const record = (calls: Array) => + dynamicResponse((input) => observe(calls, input).pipe(Effect.as(input.respond("{}", { status: 400 })))) + +const sentImage = (model: ImageModel) => + Effect.gen(function* () { + const calls: Array = [] + yield* Image.generate({ model, prompt: "A red circle" }).pipe( + Effect.exit, + Effect.provide(ImageClient.layer.pipe(Layer.provide(record(calls)))), + ) + return calls + }) + +const sentDecision = (model: DecisionModel) => + Effect.gen(function* () { + const calls: Array = [] + yield* Decision.generate({ + model, + input: [{ type: "text", text: "The sky is red." }], + questions: [{ name: "red", type: "predicate", instructions: "Is the sky red?" }], + }).pipe(Effect.exit, Effect.provide(DecisionClient.layer.pipe(Layer.provide(record(calls))))) + return calls + }) + +interface Case { + readonly name: string + readonly load: () => Promise + readonly url: string + readonly auth: readonly [string, string] + readonly headers?: Record + readonly provider?: string + /** The model id is in the URL instead of the JSON body. */ + readonly modelInURL?: boolean + /** Cloudflare's Run API nests the System One body, and so the `body` setting, under `input`. */ + readonly bodyInInput?: boolean +} + +const expectRequest = (calls: ReadonlyArray, model: ImageModel | DecisionModel, entry: Case) => { + expect(calls).toHaveLength(1) + const call = calls[0] + expect(call.url).toBe(entry.url) + expect(call.headers.get(entry.auth[0])).toBe(entry.auth[1]) + expect(call.headers.get("x-test")).toBe("yes") + for (const [key, value] of Object.entries(entry.headers ?? {})) expect(call.headers.get(key)).toBe(value) + const body = JSON.parse(call.body) + expect((entry.bodyInInput ? body.input : body).extra).toBe(true) + if (!entry.modelInURL) expect(body.model).toBe(model.id) + if (entry.provider) expect(model.provider).toBe(entry.provider) +} + +const images: ReadonlyArray> = [ + { + name: "openai-compatible", + load: async () => { + const { model } = await import("@opencode/ai/providers/openai-compatible/images") + return model("qwen-image", { + ...shared, + apiKey: "regolo-key", + baseURL: "https://api.regolo.test/v1", + provider: "regolo-ai", + }) + }, + url: "https://api.regolo.test/v1/images/generations", + auth: ["authorization", "Bearer regolo-key"], + provider: "regolo-ai", + }, + { + name: "openai", + load: async () => { + const { model } = await import("@opencode/ai/providers/openai/images") + return model("gpt-image-2", { ...shared, apiKey: "openai-key", organization: "org-1" }) + }, + url: "https://api.openai.com/v1/images/generations", + auth: ["authorization", "Bearer openai-key"], + headers: { "openai-organization": "org-1" }, + }, + { + name: "openrouter", + load: async () => { + const { model } = await import("@opencode/ai/providers/openrouter/images") + return model("openai/gpt-image-2", { ...shared, apiKey: "openrouter-key" }) + }, + url: "https://openrouter.ai/api/v1/images/generations", + auth: ["authorization", "Bearer openrouter-key"], + provider: "openrouter", + }, + { + name: "vercel-ai-gateway", + load: async () => { + const { model } = await import("@opencode/ai/providers/vercel-ai-gateway/images") + return model("openai/gpt-image-2", { ...shared, apiKey: "vercel-key" }) + }, + url: "https://ai-gateway.vercel.sh/v1/images/generations", + auth: ["authorization", "Bearer vercel-key"], + provider: "vercel-ai-gateway", + }, + { + name: "digitalocean", + load: async () => { + const { model } = await import("@opencode/ai/providers/digitalocean/images") + return model("openai-gpt-image-1", { ...shared, apiKey: "do-key" }) + }, + url: "https://inference.do-ai.run/v1/images/generations", + auth: ["authorization", "Bearer do-key"], + provider: "digitalocean", + }, + { + name: "azure", + load: async () => { + const { model } = await import("@opencode/ai/providers/azure/images") + return model("gpt-image-2", { ...shared, apiKey: "azure-key", resourceName: "fixture" }) + }, + url: "https://fixture.openai.azure.com/openai/v1/images/generations?api-version=v1", + auth: ["api-key", "azure-key"], + headers: { authorization: null }, + provider: "azure", + }, + { + name: "xai", + load: async () => { + const { model } = await import("@opencode/ai/providers/xai/images") + return model("grok-imagine-image", { ...shared, apiKey: "xai-key" }) + }, + url: "https://api.x.ai/v1/images/generations", + auth: ["authorization", "Bearer xai-key"], + }, + { + name: "zai", + load: async () => { + const { model } = await import("@opencode/ai/providers/zai/images") + return model("glm-image", { ...shared, apiKey: "zai-key", baseURL: "https://open.bigmodel.test/api/paas/v4" }) + }, + url: "https://open.bigmodel.test/api/paas/v4/images/generations", + auth: ["authorization", "Bearer zai-key"], + }, + { + name: "alibaba", + load: async () => { + const { model } = await import("@opencode/ai/providers/alibaba/images") + return model("qwen-image-2.0", { + ...shared, + apiKey: "dashscope-key", + baseURL: "https://dashscope-intl.aliyuncs.com/api/v1", + }) + }, + url: "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation", + auth: ["authorization", "Bearer dashscope-key"], + }, + { + name: "google", + load: async () => { + const { model } = await import("@opencode/ai/providers/google/images") + return model("gemini-2.5-flash-image", { ...shared, apiKey: "google-key" }) + }, + url: "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent", + auth: ["x-goog-api-key", "google-key"], + modelInURL: true, + }, + { + name: "google-vertex", + load: async () => { + const { model } = await import("@opencode/ai/providers/google-vertex/images") + return model("gemini-2.5-flash-image", { ...shared, apiKey: "vertex-key" }) + }, + url: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-2.5-flash-image:generateContent", + auth: ["x-goog-api-key", "vertex-key"], + modelInURL: true, + }, + { + name: "cloudflare-workers-ai", + load: async () => { + const { model } = await import("@opencode/ai/providers/cloudflare-workers-ai/images") + return model("@cf/leonardo/lucid-origin", { ...shared, apiKey: "cloudflare-key", accountId: "account-1" }) + }, + url: "https://api.cloudflare.com/client/v4/accounts/account-1/ai/run/@cf/leonardo/lucid-origin", + auth: ["authorization", "Bearer cloudflare-key"], + modelInURL: true, + }, +] + +const decisions: ReadonlyArray> = [ + { + name: "typesafe-ai", + load: async () => { + const { model } = await import("@opencode/ai/providers/typesafe-ai/decisions") + return model("typesafe/jev", { + ...shared, + apiKey: "amd-key", + baseURL: "https://developer.amd.test/radeon/api/v1", + }) + }, + url: "https://developer.amd.test/radeon/api/v1/systemone", + auth: ["authorization", "Bearer amd-key"], + headers: { "typesafe-danger-zone-images": "true" }, + provider: "typesafe-ai", + }, + { + name: "opencode", + load: async () => { + const { model } = await import("@opencode/ai/providers/opencode/decisions") + return model("jev", { ...shared, apiKey: "zen-key", baseURL: "https://opencode.ai/inference/systemone/v1" }) + }, + url: "https://opencode.ai/inference/systemone/v1/systemone", + auth: ["authorization", "Bearer zen-key"], + headers: { "typesafe-danger-zone-images": "true" }, + provider: "opencode", + }, + { + name: "openrouter", + load: async () => { + const { model } = await import("@opencode/ai/providers/openrouter/decisions") + return model("cloudflare/clef-omni", { ...shared, apiKey: "openrouter-key" }) + }, + url: "https://openrouter.ai/api/v1/systemone", + auth: ["authorization", "Bearer openrouter-key"], + provider: "openrouter", + }, + { + name: "baseten", + load: async () => { + const { model } = await import("@opencode/ai/providers/baseten/decisions") + return model("decision-models/baseten-elephant-9b-latest", { ...shared, apiKey: "baseten-key" }) + }, + url: "https://inference.baseten.co/v1/systemone", + auth: ["authorization", "Bearer baseten-key"], + provider: "baseten", + }, + { + name: "digitalocean", + load: async () => { + const { model } = await import("@opencode/ai/providers/digitalocean/decisions") + return model("typesafe-jev", { ...shared, apiKey: "do-key" }) + }, + url: "https://inference.do-ai.run/v1/systemone", + auth: ["authorization", "Bearer do-key"], + provider: "digitalocean", + }, + { + name: "vercel-ai-gateway", + load: async () => { + const { model } = await import("@opencode/ai/providers/vercel-ai-gateway/decisions") + return model("typesafe/jev", { ...shared, apiKey: "vercel-key" }) + }, + url: "https://ai-gateway.vercel.sh/v1/decisions", + auth: ["authorization", "Bearer vercel-key"], + provider: "vercel-ai-gateway", + }, + { + name: "cloudflare-workers-ai", + load: async () => { + const { model } = await import("@opencode/ai/providers/cloudflare-workers-ai/decisions") + return model("@cf/cloudflare/clef-omni", { ...shared, apiKey: "cloudflare-key", accountId: "account-1" }) + }, + url: "https://api.cloudflare.com/client/v4/accounts/account-1/ai/run", + auth: ["authorization", "Bearer cloudflare-key"], + bodyInInput: true, + provider: "cloudflare-workers-ai", + }, + { + name: "cloudflare-ai-gateway", + load: async () => { + const { model } = await import("@opencode/ai/providers/cloudflare-ai-gateway/decisions") + return model("@cf/cloudflare/clef-omni", { + ...shared, + apiKey: "gateway-key", + accountId: "account-1", + gatewayId: "gateway-1", + }) + }, + url: "https://api.cloudflare.com/client/v4/accounts/account-1/ai/run", + auth: ["authorization", "Bearer gateway-key"], + headers: { "cf-aig-gateway-id": "gateway-1" }, + bodyInInput: true, + provider: "cloudflare-ai-gateway", + }, +] + +describe("image entrypoints", () => { + for (const entry of images) + it.effect(`providers/${entry.name}/images sends a configured request`, () => + Effect.gen(function* () { + const model = yield* Effect.promise(entry.load) + expectRequest(yield* sentImage(model), model, entry) + }), + ) +}) + +describe("decision entrypoints", () => { + for (const entry of decisions) + it.effect(`providers/${entry.name}/decisions sends a configured request`, () => + Effect.gen(function* () { + const model = yield* Effect.promise(entry.load) + expectRequest(yield* sentDecision(model), model, entry) + }), + ) +}) diff --git a/packages/ai/test/provider/openai-chat.test.ts b/packages/ai/test/provider/openai-chat.test.ts index b7262134f71..a06b2333b49 100644 --- a/packages/ai/test/provider/openai-chat.test.ts +++ b/packages/ai/test/provider/openai-chat.test.ts @@ -379,6 +379,22 @@ describe("OpenAI Chat route", () => { }), ) + it.effect("sends the cache TTL as a request option when no markers carry it", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + LLM.request({ + model: OpenAICompatible.configure({ baseURL: "https://api.compatible.test/v1", apiKey: "test" }).model( + "compatible-model", + ), + prompt: "Hello", + cache: { ttl: "1h" }, + }), + ) + + expect(prepared.body).toMatchObject({ prompt_cache_options: { ttl: "1h" } }) + }), + ) + it.effect("omits the prompt cache key without the compatibility flag", () => Effect.gen(function* () { const prepared = yield* compileRequest( diff --git a/packages/ai/test/provider/openai-responses.test.ts b/packages/ai/test/provider/openai-responses.test.ts index 58cd5484e92..66189712159 100644 --- a/packages/ai/test/provider/openai-responses.test.ts +++ b/packages/ai/test/provider/openai-responses.test.ts @@ -2018,6 +2018,26 @@ describe("OpenAI Responses route", () => { }), ) + it.effect("sends the cache TTL as prompt_cache_options, or prompt_cache_retention for 24h", () => + Effect.gen(function* () { + const model = OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }) + const options = yield* compileRequest( + LLM.request({ model: model.model("gpt-5.6"), prompt: "hi", cache: { ttl: "30m" } }), + ) + const retention = yield* compileRequest( + LLM.request({ model: model.model("gpt-5.5"), prompt: "hi", cache: { ttl: "24h" } }), + ) + const unset = yield* compileRequest(LLM.request({ model: model.model("gpt-5.6"), prompt: "hi" })) + + expect(options.body).toMatchObject({ prompt_cache_options: { ttl: "30m" } }) + expect(options.body).not.toHaveProperty("prompt_cache_retention") + expect(retention.body).toMatchObject({ prompt_cache_retention: "24h" }) + expect(retention.body).not.toHaveProperty("prompt_cache_options") + expect(unset.body).not.toHaveProperty("prompt_cache_options") + expect(unset.body).not.toHaveProperty("prompt_cache_retention") + }), + ) + it.effect("maps OpenAI provider options to Responses options", () => Effect.gen(function* () { const prepared = yield* compileRequest( diff --git a/packages/ai/test/provider/openrouter.test.ts b/packages/ai/test/provider/openrouter.test.ts index 4ee704cb771..22eb27c4e8f 100644 --- a/packages/ai/test/provider/openrouter.test.ts +++ b/packages/ai/test/provider/openrouter.test.ts @@ -177,7 +177,7 @@ describe("OpenRouter", () => { LLM.request({ model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"), system: [ - { type: "text", text: "Base agent", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3_600 }) }, + { type: "text", text: "Base agent", cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }, { type: "text", text: "Project instructions" }, ], tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }], @@ -223,7 +223,7 @@ describe("OpenRouter", () => { id: "call_1", name: "lookup", result: "Done", - cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3_600 }), + cache: new CacheHint({ type: "ephemeral", ttl: "1h" }), }), ], }), diff --git a/packages/ai/test/raw-events.test.ts b/packages/ai/test/raw-events.test.ts new file mode 100644 index 00000000000..5748eb7d3a2 --- /dev/null +++ b/packages/ai/test/raw-events.test.ts @@ -0,0 +1,75 @@ +import { describe, expect } from "bun:test" +import { Effect, Stream } from "effect" +import { LLM } from "../src/effect.js" +import { Auth, LLMClient } from "../src/route.js" +import { AnthropicMessages } from "../src/protocols/anthropic-messages.js" +import { it } from "./lib/effect.js" +import { fixedResponse } from "./lib/http.js" +import { sseEvents } from "./lib/sse.js" + +const model = AnthropicMessages.route + .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) + .model({ id: "claude-sonnet-4-5" }) + +const frames = [ + { type: "message_start", message: { usage: { input_tokens: 5 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "future_event", detail: "unknown to the protocol" }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } }, + { type: "message_stop" }, + { type: "ping" }, +] + +const layer = fixedResponse(sseEvents(...frames)) + +describe("raw provider events", () => { + it.effect("stream emits every frame before its own events only when requested", () => + Effect.gen(function* () { + const raw = Array.from( + yield* LLMClient.stream(LLM.request({ model, prompt: "Hi", includeRaw: true })).pipe( + Stream.runCollect, + Effect.provide(layer), + ), + ) + const plain = Array.from( + yield* LLMClient.stream(LLM.request({ model, prompt: "Hi" })).pipe(Stream.runCollect, Effect.provide(layer)), + ) + + expect(raw.filter((event) => event.type === "raw").map((event) => event.data)).toEqual(frames) + expect( + raw.map((event) => (event.type === "raw" ? `raw:${(event.data as { type: string }).type}` : event.type)), + ).toEqual([ + "raw:message_start", + "raw:content_block_start", + "step-start", + "text-start", + "raw:future_event", + "raw:content_block_delta", + "text-delta", + "raw:content_block_stop", + "text-end", + "raw:message_delta", + "raw:message_stop", + "step-finish", + "finish", + "raw:ping", + ]) + expect(raw.filter((event) => event.type !== "raw")).toEqual(plain) + expect(plain.some((event) => event.type === "raw")).toBe(false) + }), + ) + + it.effect("generate ignores raw events", () => + Effect.gen(function* () { + const withRaw = yield* LLMClient.generate(LLM.request({ model, prompt: "Hi", includeRaw: true })).pipe( + Effect.provide(layer), + ) + const plain = yield* LLMClient.generate(LLM.request({ model, prompt: "Hi" })).pipe(Effect.provide(layer)) + + expect(withRaw).toEqual(plain) + expect(withRaw.text).toBe("Hello") + }), + ) +}) diff --git a/packages/ai/test/testing.test.ts b/packages/ai/test/testing.test.ts index d87cc72e6a4..0beec864cc2 100644 --- a/packages/ai/test/testing.test.ts +++ b/packages/ai/test/testing.test.ts @@ -23,62 +23,8 @@ const request = LLM.request({ model: LanguageModel.make({ id: "fictional-model", provider: "fixture", route: OpenAIChat.route }), prompt: "Say hello", }) -const legacy = testEffect(TestLLM.layer()) const it = testEffect(TestLLM.testLayer()) -describe("TestLLM legacy client", () => { - legacy.effect("does not observe requests or consume responses until execution", () => - Effect.gen(function* () { - const llm = yield* TestLLM.Service - yield* llm.push(TestLLM.text("first", "first"), TestLLM.text("second", "second")) - - llm.client.stream(request) - llm.client.generate(request) - expect(llm.requests).toEqual([]) - - expect((yield* llm.client.generate(request)).text).toBe("first") - expect((yield* llm.client.generate(request)).text).toBe("second") - expect(llm.requests).toEqual([request, request]) - }), - ) - - legacy.effect("assigns and records a fresh response for each execution", () => - Effect.gen(function* () { - const llm = yield* TestLLM.Service - yield* llm.push( - TestLLM.text("first", "first"), - TestLLM.text("second", "second"), - TestLLM.text("third", "third"), - TestLLM.text("fourth", "fourth"), - ) - const stream = llm.client.stream(request) - const generate = llm.client.generate(request) - - expect(yield* Stream.runCollect(stream)).toEqual(TestLLM.text("first", "first")) - expect(yield* Stream.runCollect(stream)).toEqual(TestLLM.text("second", "second")) - expect((yield* generate).text).toBe("third") - expect((yield* generate).text).toBe("fourth") - expect(llm.requests).toEqual([request, request, request, request]) - }), - ) - - legacy.effect("keeps module-level controls and clientLayer on the same backing state", () => - Effect.gen(function* () { - const llm = yield* TestLLM.Service - const requests = llm.requests - yield* TestLLM.push(TestLLM.text("queued", "queued")) - yield* TestLLM.always(TestLLM.text("fallback", "fallback")) - expect((yield* LLMClient.generate(request).pipe(Effect.provide(TestLLM.clientLayer))).text).toBe("queued") - yield* TestLLM.wait(1) - expect(requests).toEqual([request]) - requests.length = 0 - expect((yield* llm.client.generate(request)).text).toBe("fallback") - expect(llm.requests).toBe(requests) - expect(requests).toEqual([request]) - }), - ) -}) - describe("TestLLM first-class client", () => { it.effect("returns scripted checkpoints only for trigger compaction", () => Effect.gen(function* () { diff --git a/packages/ai/test/tool-schema-projection.test.ts b/packages/ai/test/tool-schema-projection.test.ts index 5888c74edeb..018680d98d5 100644 --- a/packages/ai/test/tool-schema-projection.test.ts +++ b/packages/ai/test/tool-schema-projection.test.ts @@ -204,7 +204,20 @@ describe("tool schema projections", () => { linked: { $ref: "#/$defs/Linked", description: "drop me" }, tuple: { type: "array", items: [{ type: "string" }, { type: "number" }] }, prefixTuple: { type: "array", prefixItems: [{ type: "boolean" }, { type: "string" }] }, + closedTuple: { type: "array", prefixItems: [{ type: "string" }, { type: "number" }], items: false }, + restTuple: { type: "array", prefixItems: [{ type: "string" }], items: { type: "number" } }, + prefixItems: { type: "string" }, + unevaluatedItems: { type: "boolean" }, + items: { type: "array", items: { type: "string" } }, + cart: { + type: "object", + default: { items: ["a", "b"], $ref: "#/literal", count: 1 }, + const: { enum: ["literal"] }, + examples: [{ items: ["x", "y"] }], + }, }, + dependentRequired: { items: ["cart"] }, + dependencies: { items: ["cart"], prefixItems: { required: ["items"] } }, }), ).toEqual({ type: "object", @@ -212,7 +225,20 @@ describe("tool schema projections", () => { linked: { $ref: "#/$defs/Linked" }, tuple: { type: "array", items: { anyOf: [{ type: "string" }, { type: "number" }] } }, prefixTuple: { type: "array", items: { anyOf: [{ type: "boolean" }, { type: "string" }] } }, + closedTuple: { type: "array", items: { anyOf: [{ type: "string" }, { type: "number" }] } }, + restTuple: { type: "array", items: { anyOf: [{ type: "string" }, { type: "number" }] } }, + prefixItems: { type: "string" }, + unevaluatedItems: { type: "boolean" }, + items: { type: "array", items: { type: "string" } }, + cart: { + type: "object", + default: { items: ["a", "b"], $ref: "#/literal", count: 1 }, + const: { enum: ["literal"] }, + examples: [{ items: ["x", "y"] }], + }, }, + dependentRequired: { items: ["cart"] }, + dependencies: { items: ["cart"], prefixItems: { required: ["items"] } }, }) }) diff --git a/packages/ai/tsconfig.types.json b/packages/ai/tsconfig.types.json index bcd7878f6ba..b1e4110eef6 100644 --- a/packages/ai/tsconfig.types.json +++ b/packages/ai/tsconfig.types.json @@ -5,5 +5,5 @@ "noEmit": true, "rootDir": "." }, - "include": ["test/**/*.types.ts", "test/testing.test.ts", "test/provider/checkpoint.test.ts"] + "include": ["example/**/*.ts", "test/**/*.types.ts", "test/testing.test.ts", "test/provider/checkpoint.test.ts"] } diff --git a/packages/app/README.md b/packages/app/README.md index 3e10fc3893d..90951727d6d 100644 --- a/packages/app/README.md +++ b/packages/app/README.md @@ -75,7 +75,7 @@ The `deploy` GitHub Actions workflow uses SST to deploy the web app to `beta.ope `beta` branch in `anomalyco/opencode`. The `dev` and `production` stages do not deploy the web app. `beta` is the team's dogfooding branch: `dev` merged in by hand, plus commits pushed directly to it. Do not rebase or -force-push it. Each push also runs the `publish` workflow, which ships the same commit as the OpenCode Beta desktop app +force-push it. Each push also runs the `release` workflow, which ships the same commit as the OpenCode Beta desktop app (see `packages/desktop/README.md`). The beta SST stage deploys only the web app, using the `WebApp` StaticSiteV2 definition in `infra/webapp.ts`. It sets diff --git a/packages/app/component-tests/activity-chips.spec.ts b/packages/app/component-tests/activity-chips.spec.ts index 3add92d44ed..dcc7c882c8e 100644 --- a/packages/app/component-tests/activity-chips.spec.ts +++ b/packages/app/component-tests/activity-chips.spec.ts @@ -1,7 +1,9 @@ import { expect, story } from "../../stories/playwright/story" story("shows how long each background item has been running, ticking while open", async ({ mount, page }) => { + // Time moves only when the test advances it, so waiting for fonts cannot add a tick. await page.clock.install({ time: new Date("2026-10-19T12:00:00Z") }) + await page.clock.pauseAt(new Date("2026-10-19T12:00:00Z")) await mount("session-activity-chips--subagents-and-shells") await page.locator('[data-slot="session-activity-chip"]').click() @@ -9,6 +11,8 @@ story("shows how long each background item has been running, ticking while open" // The story starts its subagents 12 s and 65 s ago, and its shells 62 min and 341 s ago. await expect(elapsed).toHaveText(["12s", "1m 05s", "1h 02m", "5m 41s"]) + // A late Inter swap widens the panel; measure after fonts settle. + await page.evaluate(() => document.fonts.ready.then(() => undefined)) const width = await page.locator('[data-slot="session-activity-panel"]').evaluate((node) => node.clientWidth) await page.clock.runFor(1_000) diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 5bd24552dd0..c37bd337d81 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -472,7 +472,7 @@ story("grows suggestions while preserving visible timeline context", async ({ mo const boundary = component.locator('[data-slot="composer-suggestion-boundary-story"]') const suggestions = component.locator('[data-component="composer-suggestions"]') - await expect(suggestions).toHaveCSS("max-height", "166px") + await expect(suggestions).toHaveCSS("max-height", "164px") await expect(suggestions).toHaveCSS("scroll-padding-bottom", "18px") await expect.poll(() => suggestions.evaluate((element) => element.scrollHeight > element.clientHeight)).toBe(true) await expect @@ -497,12 +497,43 @@ story("grows suggestions while preserving visible timeline context", async ({ mo await boundary.evaluate((element) => { element.style.height = "400px" }) - await expect(suggestions).toHaveCSS("max-height", "306px") + await expect(suggestions).toHaveCSS("max-height", "304px") +}) + +story("keeps the @ menu and its last results open while the next search is pending", async ({ mount }) => { + const component = await mount("opencode-composer-flow--slow-file-search") + const input = component.getByRole("textbox", { name: "Prompt", exact: true }) + const menu = component.locator('[data-component="composer-suggestions"]') + const row = (id: string) => menu.locator(`[data-suggestion-id="${id}"]`) + const pending = (query: string) => component.getByRole("button", { name: `Return files for ${query}`, exact: true }) + + await input.pressSequentially("@r") + await pending("r").click() + await expect(row("file:r/plan.md")).toBeVisible() + await expect(row("agent:review")).toHaveAttribute("data-active", "") + const height = (await menu.boundingBox())!.height + + await input.pressSequentially("e") + await expect(pending("re")).toBeVisible() + await expect(row("file:r/plan.md")).toBeVisible() + expect((await menu.boundingBox())!.height).toBe(height) + + await pending("re").click() + await expect(row("file:re/plan.md")).toBeVisible() + await expect(row("file:r/plan.md")).toHaveCount(0) + await expect(row("agent:review")).toHaveAttribute("data-active", "") + + // Only a settled search with nothing to show empties the menu, and it stays open to say so. + await input.pressSequentially("z") + await expect(pending("rez")).toBeVisible() + await expect(row("file:re/plan.md")).toBeVisible() + await pending("rez").click() + await expect(menu.getByText("No matching items", { exact: true })).toBeVisible() }) story("ignores a detached suggestion boundary", async ({ mount }) => { const component = await mount("opencode-composer-flow--detached-command-suggestion-boundary") - await expect(component.locator('[data-component="composer-suggestions"]')).toHaveCSS("max-height", "306px") + await expect(component.locator('[data-component="composer-suggestions"]')).toHaveCSS("max-height", "304px") }) // ThemeProvider writes resolved token values into a