diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index cceccb784c09..ae0205d60da1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,4 +8,4 @@ packages/plugin/src/gui/ @Hona # 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/releasers +/.github/ @thdxr diff --git a/.github/release/cloudflare-token.sh b/.github/release/cloudflare-token.sh index bc8e59d80c40..478f0599cdf1 100755 --- a/.github/release/cloudflare-token.sh +++ b/.github/release/cloudflare-token.sh @@ -12,6 +12,10 @@ set +x url=${CLOUDFLARE_TOKEN_URL:-https://kjivkui2evldapbok5fhrrl6oy0fctkp.lambda-url.us-east-1.on.aws/} account=${CLOUDFLARE_ACCOUNT_ID:-15d29c8639fd3733b1b5486a2acfd968} +if [[ $# == 1 ]]; then + . "$(dirname "$0")/lib.sh" + account=$(stage_account "$1") +fi # One argv value, never a line in curl's config: a newline in an override must not be able to # inject curl options or move the AWS credentials into Basic auth. diff --git a/.github/release/deploy-data.sh b/.github/release/deploy-data.sh index 156db5a5c23e..48a5a6a03d14 100755 --- a/.github/release/deploy-data.sh +++ b/.github/release/deploy-data.sh @@ -32,7 +32,8 @@ done : "${CLOUDFLARE_API_TOKEN:?Set CLOUDFLARE_API_TOKEN}" # Pinned in targets/ and in the token issuer's config (anomalyco/secrets). -export CLOUDFLARE_ACCOUNT_ID=15d29c8639fd3733b1b5486a2acfd968 +CLOUDFLARE_ACCOUNT_ID=$(stage_account "$mode") +export CLOUDFLARE_ACCOUNT_ID unexpected=$(cd "$src" && find . ! -type d ! -type f -o -type f ! -path ./SHA256SUMS \ ! -path ./v0/config.json \ diff --git a/.github/release/deploy-files.sh b/.github/release/deploy-files.sh index a96353007808..0215545894ad 100755 --- a/.github/release/deploy-files.sh +++ b/.github/release/deploy-files.sh @@ -24,7 +24,8 @@ target="$release/targets/files/$mode/wrangler.json" : "${CLOUDFLARE_API_TOKEN:?Set CLOUDFLARE_API_TOKEN}" # Pinned in targets/ and in the token issuer's config (anomalyco/secrets). -export CLOUDFLARE_ACCOUNT_ID=15d29c8639fd3733b1b5486a2acfd968 +CLOUDFLARE_ACCOUNT_ID=$(stage_account "$mode") +export CLOUDFLARE_ACCOUNT_ID unexpected=$(cd "$src" && find . ! -type d ! -type f -o -type f ! -path ./SHA256SUMS ! -path ./index.js) [ -z "$unexpected" ] || die "Unexpected files in the files artifact: $unexpected" diff --git a/.github/release/deploy-legacy.sh b/.github/release/deploy-legacy.sh index 4fd7b684cae7..f64a0a46789f 100755 --- a/.github/release/deploy-legacy.sh +++ b/.github/release/deploy-legacy.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# deploy-legacy.sh : deploys the legacy +# deploy-legacy.sh [production-secrets.json]: deploys the legacy # Worker from a verified Build Output artifact (services/legacy/.cloudflare/output) # with the cf CLI pinned in cf/package-lock.json. # @@ -12,7 +12,6 @@ mode=$1 src=$(cd "$2" && pwd) -secrets=$(posix "$3") release=$(cd "$(dirname "$0")" && pwd) case "$mode" in @@ -24,7 +23,8 @@ target="$release/targets/legacy/$mode" : "${CLOUDFLARE_API_TOKEN:?Set CLOUDFLARE_API_TOKEN}" # Pinned in targets/ and in the token issuer's config (anomalyco/secrets). -export CLOUDFLARE_ACCOUNT_ID=15d29c8639fd3733b1b5486a2acfd968 +CLOUDFLARE_ACCOUNT_ID=$(stage_account "$mode") +export CLOUDFLARE_ACCOUNT_ID unexpected=$(cd "$src" && find . ! -type d ! -type f -o -type f ! -path ./SHA256SUMS \ ! -path ./v0/config.json \ @@ -36,8 +36,13 @@ unexpected=$(cd "$src" && find . ! -type d ! -type f -o -type f ! -path ./SHA256 expect_json "$src/v0/config.json" "$target/root.json" "The legacy Worker's root config" expect_json "$src/v0/workers/default/worker.config.json" "$target/worker.json" "The legacy Worker's config" -jq -e 'keys == ["GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY"] and all(.[]; type == "string" and length > 0)' \ - "$secrets" > /dev/null || die "The secrets file does not hold exactly GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY" +args=() +if [[ "$mode" == production ]]; then + secrets=$(posix "$3") + jq -e 'keys == ["GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY"] and all(.[]; type == "string" and length > 0)' \ + "$secrets" > /dev/null || die "The secrets file does not hold exactly GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY" + args=(--secrets-file "$secrets") +fi work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -51,4 +56,4 @@ cf="$release/cf/node_modules/.bin/cf" [ -x "$cf" ] || die "Install the pinned cf CLI first: npm ci --ignore-scripts in .github/release/cf" cd "$work" -"$cf" deploy --prebuilt --mode "$mode" --secrets-file "$secrets" +"$cf" deploy --prebuilt --mode "$mode" "${args[@]}" diff --git a/.github/release/deploy-site.sh b/.github/release/deploy-site.sh index 77d92d02f888..5b6c5ad2d45b 100755 --- a/.github/release/deploy-site.sh +++ b/.github/release/deploy-site.sh @@ -24,7 +24,8 @@ target="$release/targets/site/$mode" : "${CLOUDFLARE_API_TOKEN:?Set CLOUDFLARE_API_TOKEN}" # Pinned in targets/ and in the token issuer's config (anomalyco/secrets). -export CLOUDFLARE_ACCOUNT_ID=15d29c8639fd3733b1b5486a2acfd968 +CLOUDFLARE_ACCOUNT_ID=$(stage_account "$mode") +export CLOUDFLARE_ACCOUNT_ID unexpected=$(cd "$src" && find . ! -type d ! -type f -o -type f ! -path ./SHA256SUMS \ ! -path ./v0/config.json \ diff --git a/.github/release/import-certificate.sh b/.github/release/import-certificate.sh new file mode 100644 index 000000000000..dfd2f9caf603 --- /dev/null +++ b/.github/release/import-certificate.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 +cert="$RUNNER_TEMP/cert.p12" +trap 'rm -f "$cert"' EXIT +keychain_password=$(openssl rand -base64 32) +printf '%s' "$APPLE_SIGNING_CERTIFICATE" | base64 --decode > "$cert" +unset APPLE_SIGNING_CERTIFICATE +security create-keychain -p "$keychain_password" build.keychain +security set-keychain-settings -lut 21600 build.keychain +security unlock-keychain -p "$keychain_password" build.keychain +security import "$cert" -k build.keychain -P "" -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productsign +security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" build.keychain > /dev/null +security list-keychains -d user -s build.keychain $(security list-keychains -d user | tr -d '"') diff --git a/.github/release/lib.sh b/.github/release/lib.sh index ed4b74a4caaa..a7d06fffe9c5 100644 --- a/.github/release/lib.sh +++ b/.github/release/lib.sh @@ -23,6 +23,14 @@ dry_run() { [ "${OPENCODE_DRY_RUN:-false}" = true ] } +stage_account() { + case "$1" in + dev) echo d8e944f537ceef3f06a5bd3aec1d7a53 ;; + production) echo 15d29c8639fd3733b1b5486a2acfd968 ;; + *) die "Unknown Cloudflare stage: $1" ;; + esac +} + sha256() { if command -v sha256sum > /dev/null; then sha256sum "$@"; else shasum -a 256 "$@"; fi } diff --git a/.github/release/plan-release.sh b/.github/release/plan-release.sh index 62876f6f8c07..2034f8ec4582 100755 --- a/.github/release/plan-release.sh +++ b/.github/release/plan-release.sh @@ -7,7 +7,7 @@ # push or dispatch on beta -> beta 0.0.0-beta- desktop only # pull_request -> pr 0.0.0-pr- everything, dry run # -# Releasers are actors with the admin or maintain role on the repository (the releasers team has maintain). +# Stable releases are limited to the GitHub logins listed below (case-insensitive). . "$(dirname "$0")/lib.sh" versioned=false @@ -27,11 +27,9 @@ fi if [ "$channel" = latest ]; then actor=${GITHUB_TRIGGERING_ACTOR:-${GITHUB_ACTOR:-}} [ -n "$actor" ] || die "Stable releases can only be started by releasers; the triggering actor is unknown" - role=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$actor/permission" --jq .role_name) || role="" - case "$role" in - admin | maintain) ;; - *) die "Stable releases can only be started by releasers (admin or maintain on the repo); $actor has ${role:-no readable role}" ;; - esac + if ! (shopt -s nocasematch; [[ "$actor" = thdxr || "$actor" = Hona || "$actor" = rekram1-node ]]); then + die "$actor is not allowed to start stable releases" + fi fi if [ "$channel" = latest ] && [ -n "${INPUT_VERSION:-}" ]; then diff --git a/.github/release/publish-process-daemon.sh b/.github/release/publish-process-daemon.sh new file mode 100644 index 000000000000..2b4a0561345b --- /dev/null +++ b/.github/release/publish-process-daemon.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +. "$(dirname "$0")/lib.sh" + +version=${GITHUB_REF_NAME#process-daemon-v} +[[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.-]+)?$ ]] || die 'Invalid daemon version' +registry=https://registry.npmjs.org +# Validate every package before the first write. Publish the dispatcher last. +packages=(pty-darwin-{arm64,x64} pty-linux-{arm64,x64}-{gnu,musl} pty-win32-{arm64,x64} pty) +for package in "${packages[@]}"; do + file="$1/opencode-$package-$version.tgz" + tar -xOzf "$file" package/package.json | jq -es --arg name "@opencode/$package" --arg version "$version" ' + length == 1 and (.[0] | .name == $name and .version == $version and + ((.publishConfig // {}) | del(.access) == {}))' >/dev/null || die "Unexpected manifest for $package" +done +for package in "${packages[@]}"; do + if ! npm view --registry="$registry" "@opencode/$package@$version" version >/dev/null 2>&1; then + npm publish --registry="$registry" --ignore-scripts --access public --provenance "$1/opencode-$package-$version.tgz" + fi +done diff --git a/.github/release/tag-release.sh b/.github/release/tag-release.sh index 7100130d3355..a282b4e97f49 100755 --- a/.github/release/tag-release.sh +++ b/.github/release/tag-release.sh @@ -5,6 +5,16 @@ . "$(dirname "$0")/lib.sh" tag="v$OPENCODE_VERSION" +if ! dry_run; then + umask 077 + ssh_dir=$(mktemp -d) + trap 'rm -rf "$ssh_dir"' EXIT + printf '%s\n' "$RELEASE_TAG_KEY" > "$ssh_dir/key" + unset RELEASE_TAG_KEY + echo 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl' > "$ssh_dir/known_hosts" + export GIT_SSH_COMMAND="ssh -i $ssh_dir/key -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$ssh_dir/known_hosts" + git remote set-url origin git@github.com:anomalyco/opencode.git +fi # @opencode/pty is versioned separately, by process-daemon-v tags. git ls-files -z -- '*package.json' bun.lock ':!packages/process-daemon/**' | xargs -0 sed -i -E "s/\"version\": \"[^\"]+\"/\"version\": \"$OPENCODE_VERSION\"/g" @@ -37,5 +47,5 @@ if [ -n "$existing" ]; then echo "sha=$existing" >> "$GITHUB_OUTPUT" exit 0 fi -git push -q origin "HEAD:refs/tags/$tag" +if ! dry_run; then git push -q origin "HEAD:refs/tags/$tag"; fi echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" diff --git a/.github/release/targets/data/dev/default.json b/.github/release/targets/data/dev/default.json index ee773890be68..fd29e9c8d036 100644 --- a/.github/release/targets/data/dev/default.json +++ b/.github/release/targets/data/dev/default.json @@ -3,25 +3,25 @@ "compatibilityDate": "2026-07-25", "compatibilityFlags": ["nodejs_compat"], "triggers": [ - { "type": "fetch", "pattern": "dev.opencode.ai/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/en/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/zh/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/zht/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/ko/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/de/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/es/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/fr/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/it/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/da/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/ja/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/pl/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/ru/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/uk/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/ar/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/no/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/br/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/th/data*", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/tr/data*", "zone": "opencode.ai" } + { "type": "fetch", "pattern": "dev.opencode.ai/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/en/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/zh/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/zht/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/ko/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/de/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/es/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/fr/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/it/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/da/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/ja/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/pl/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/ru/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/uk/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/ar/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/no/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/br/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/th/data*", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/tr/data*", "zone": "dev.opencode.ai" } ], "observability": { "enabled": true }, "workersDev": false, diff --git a/.github/release/targets/data/dev/root.json b/.github/release/targets/data/dev/root.json index 20a9b8c10068..53faf94c4a7c 100644 --- a/.github/release/targets/data/dev/root.json +++ b/.github/release/targets/data/dev/root.json @@ -1,4 +1,4 @@ { - "accountId": "15d29c8639fd3733b1b5486a2acfd968", + "accountId": "d8e944f537ceef3f06a5bd3aec1d7a53", "buildContext": { "isPreview": false, "mode": "dev" } } diff --git a/.github/release/targets/data/dev/sync.json b/.github/release/targets/data/dev/sync.json index 83bb835c8ccb..ed16225a5c95 100644 --- a/.github/release/targets/data/dev/sync.json +++ b/.github/release/targets/data/dev/sync.json @@ -18,6 +18,7 @@ "exportName": "DataSyncWorkflow" }, "STAGE": { "type": "text", "value": "dev" }, + "R2_SQL_ACCOUNT_ID": { "type": "text", "value": "d8e944f537ceef3f06a5bd3aec1d7a53" }, "DATA_DATABASE_HOST": { "type": "secret" }, "DATA_DATABASE_USERNAME": { "type": "secret" }, "DATA_DATABASE_PASSWORD": { "type": "secret" }, diff --git a/.github/release/targets/files/dev/wrangler.json b/.github/release/targets/files/dev/wrangler.json index 5635c6e631a6..edc4853318e7 100644 --- a/.github/release/targets/files/dev/wrangler.json +++ b/.github/release/targets/files/dev/wrangler.json @@ -1,11 +1,12 @@ { "name": "opencode-dev-files", + "account_id": "d8e944f537ceef3f06a5bd3aec1d7a53", "main": "index.js", "no_bundle": true, "compatibility_date": "2026-08-01", "workers_dev": false, "preview_urls": false, "vars": { "STAGE": "dev" }, - "routes": [{ "pattern": "dev.opencode.ai/files/*", "zone_name": "opencode.ai" }], + "routes": [{ "pattern": "dev.opencode.ai/files/*", "zone_name": "dev.opencode.ai" }], "r2_buckets": [{ "binding": "FILES", "bucket_name": "opencode-dev-files" }] } diff --git a/.github/release/targets/legacy/dev/root.json b/.github/release/targets/legacy/dev/root.json index 20a9b8c10068..53faf94c4a7c 100644 --- a/.github/release/targets/legacy/dev/root.json +++ b/.github/release/targets/legacy/dev/root.json @@ -1,4 +1,4 @@ { - "accountId": "15d29c8639fd3733b1b5486a2acfd968", + "accountId": "d8e944f537ceef3f06a5bd3aec1d7a53", "buildContext": { "isPreview": false, "mode": "dev" } } diff --git a/.github/release/targets/legacy/dev/worker.json b/.github/release/targets/legacy/dev/worker.json index fd5f0fb9431c..f34a902c1a7c 100644 --- a/.github/release/targets/legacy/dev/worker.json +++ b/.github/release/targets/legacy/dev/worker.json @@ -3,14 +3,10 @@ "compatibilityDate": "2026-07-25", "compatibilityFlags": ["nodejs_compat"], "domains": ["dev.opncd.ai", "api.dev.opencode.ai"], - "logpush": true, + "logpush": false, "observability": { "enabled": true }, "workersDev": false, "previewUrls": false, - "env": { - "GITHUB_APP_ID": { "type": "secret" }, - "GITHUB_APP_PRIVATE_KEY": { "type": "secret" } - }, "manifest": { "type": "complete", "mainModule": "index.js", diff --git a/.github/release/targets/site/dev/root.json b/.github/release/targets/site/dev/root.json index 20a9b8c10068..53faf94c4a7c 100644 --- a/.github/release/targets/site/dev/root.json +++ b/.github/release/targets/site/dev/root.json @@ -1,4 +1,4 @@ { - "accountId": "15d29c8639fd3733b1b5486a2acfd968", + "accountId": "d8e944f537ceef3f06a5bd3aec1d7a53", "buildContext": { "isPreview": false, "mode": "dev" } } diff --git a/.github/release/targets/site/dev/worker.json b/.github/release/targets/site/dev/worker.json index 93a0ed61bc5a..f9b5fa324267 100644 --- a/.github/release/targets/site/dev/worker.json +++ b/.github/release/targets/site/dev/worker.json @@ -24,8 +24,8 @@ }, "domains": ["dev.opencode.ai", "docs.dev.opencode.ai"], "triggers": [ - { "type": "fetch", "pattern": "dev.opencode.ai", "zone": "opencode.ai" }, - { "type": "fetch", "pattern": "dev.opencode.ai/*", "zone": "opencode.ai" } + { "type": "fetch", "pattern": "dev.opencode.ai", "zone": "dev.opencode.ai" }, + { "type": "fetch", "pattern": "dev.opencode.ai/*", "zone": "dev.opencode.ai" } ], "observability": { "enabled": true }, "workersDev": false, diff --git a/.github/release/with-secrets.sh b/.github/release/with-secrets.sh new file mode 100644 index 000000000000..47511961e767 --- /dev/null +++ b/.github/release/with-secrets.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Fetch only this command's named secrets; keep credentials out of its environment. +. "$(dirname "$0")/lib.sh" +set +x +while [[ $# -gt 0 && $1 != -- ]]; do + name=${1%%=*} id=${1#*=} + [[ $name =~ ^[A-Z][A-Z0-9_]*$ && $id != "$1" && -n $id ]] || die 'Expected NAME=secret-id' + if ! dry_run; then + value=$(aws secretsmanager get-secret-value --region us-east-1 --secret-id "$id" --query SecretString --output text) + [[ -n $value && $value != None ]] || die "Empty secret: $id" + while IFS= read -r line; do + [[ -z $line ]] || printf '::add-mask::%s\n' "${line//%/%25}" + done <<< "$value" + export "$name=$value" + fi + shift +done +[[ ${1:-} == -- && $# -gt 1 ]] || die 'Expected -- command' +shift +unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN value +exec "$@" diff --git a/.github/workflows/bot-nix-hashes.yml b/.github/workflows/bot-nix-hashes.yml index bc6432c947a3..b85aca61ee31 100644 --- a/.github/workflows/bot-nix-hashes.yml +++ b/.github/workflows/bot-nix-hashes.yml @@ -47,7 +47,7 @@ jobs: - system: aarch64-linux runner: blacksmith-4vcpu-ubuntu-2404-arm - system: aarch64-darwin - runner: macos-latest + runner: blacksmith-6vcpu-macos-latest runs-on: ${{ matrix.runner }} steps: diff --git a/.github/workflows/deploy-files.yml b/.github/workflows/deploy-files.yml index bdd8a8ce0a15..7824f8f4c56a 100644 --- a/.github/workflows/deploy-files.yml +++ b/.github/workflows/deploy-files.yml @@ -106,7 +106,7 @@ jobs: # It is a step output, so only the Deploy step gets it. - name: Cloudflare token id: cloudflare-token - run: bash .github/release/cloudflare-token.sh + run: bash .github/release/cloudflare-token.sh "$GITHUB_REF_NAME" env: CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 4bcae5a50fde..0ee926abd610 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -99,7 +99,7 @@ jobs: # It is a step output, so only the Deploy step gets it. - name: Cloudflare token id: cloudflare-token - run: bash .github/release/cloudflare-token.sh + run: bash .github/release/cloudflare-token.sh "$GITHUB_REF_NAME" env: CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 5f7db94c2710..5f536276f7e6 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -96,7 +96,7 @@ jobs: # It is a step output, so only the Deploy step gets it. - name: Cloudflare token id: cloudflare-token - run: bash .github/release/cloudflare-token.sh + run: bash .github/release/cloudflare-token.sh "$GITHUB_REF_NAME" env: CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} @@ -109,11 +109,14 @@ jobs: # An explicit bash runs with pipefail, so a failed secret read fails the step. shell: bash run: | + if [[ "$STAGE" == dev ]]; then + exec bash .github/release/deploy-legacy.sh dev "$RUNNER_TEMP/in/legacy-dev" + fi umask 077 secrets="$RUNNER_TEMP/legacy-secrets.json" trap 'rm -f "$secrets"' EXIT for name in GITHUB_APP_ID GITHUB_APP_PRIVATE_KEY; do - aws secretsmanager get-secret-value --secret-id "opencode/$STAGE/$name" --output json | + aws secretsmanager get-secret-value --secret-id "opencode/production/$name" --output json | jq --arg name "$name" '{($name): .SecretString}' done | jq -s add > "$secrets" bash .github/release/deploy-legacy.sh "$STAGE" "$RUNNER_TEMP/in/legacy-$STAGE" "$secrets" @@ -185,7 +188,7 @@ jobs: - name: Cloudflare token id: cloudflare-token - run: bash .github/release/cloudflare-token.sh + run: bash .github/release/cloudflare-token.sh "$GITHUB_REF_NAME" env: CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} diff --git a/.github/workflows/release-process-daemon.yml b/.github/workflows/release-process-daemon.yml index 881865581945..7bd0acd91acd 100644 --- a/.github/workflows/release-process-daemon.yml +++ b/.github/workflows/release-process-daemon.yml @@ -167,7 +167,7 @@ jobs: target: aarch64-pc-windows-msvc arch: arm64 runs-on: ${{ matrix.runner }} - timeout-minutes: 45 + timeout-minutes: 60 defaults: run: shell: pwsh @@ -246,13 +246,11 @@ jobs: path: packages/process-daemon/dist/*.tar.gz if-no-files-found: error - release: + package: needs: [checks, build, build-windows] runs-on: ubuntu-22.04 - permissions: - contents: write - id-token: write - attestations: write + outputs: + digest: ${{ steps.upload.outputs.digest }} env: PROTOCOL_VERSION: ${{ needs.checks.outputs.protocol }} steps: @@ -261,8 +259,6 @@ jobs: with: node-version: "24" registry-url: https://registry.npmjs.org - - name: Install npm with trusted publishing support - run: npm install --global npm@^11.5.1 - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: packages/process-daemon/dist @@ -297,35 +293,68 @@ jobs: npm pack --pack-destination "$temporary" dist/npm/opencode-pty-linux-x64-gnu dist/npm/opencode-pty >/dev/null npm install --prefix "$temporary" --ignore-scripts --no-package-lock --no-audit --no-fund "$temporary"/*.tgz test "$("$temporary/node_modules/.bin/opencode-pty" --version)" = "opencode-pty $(node -p 'require("./npm/package.json").version') (protocol $PROTOCOL_VERSION)" + - name: Stage release files + run: | + mkdir -p "$RUNNER_TEMP/bundle/github" "$RUNNER_TEMP/bundle/npm" + cp dist/*.tar.gz dist/release-manifest.json dist/SHA256SUMS "$RUNNER_TEMP/bundle/github/" + for package in dist/npm/*; do + npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP/bundle/npm" "$(realpath "$package")" + done + # The upload action owns the outer SHA256SUMS; include the release checksums in it. + mv "$RUNNER_TEMP/bundle/github/SHA256SUMS" "$RUNNER_TEMP/bundle/github/checksums.txt" + - id: upload + uses: ./.github/release/upload + with: + name: process-daemon-bundle + path: ${{ runner.temp }}/bundle + + release: + needs: [checks, package] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/process-daemon-v') + runs-on: ubuntu-24.04 + environment: process-daemon-release + permissions: + contents: write + id-token: write + attestations: write + defaults: + run: + working-directory: . + env: + PROTOCOL_VERSION: ${{ needs.checks.outputs.protocol }} + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + sparse-checkout: /.github/release/ + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0; caching opt-in + with: + node-version: '24.11.0' + - uses: ./.github/release/download + with: + pattern: process-daemon-bundle + digests: process-daemon-bundle=${{ needs.package.outputs.digest }} + require-digests: 'true' - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - if: startsWith(github.ref, 'refs/tags/process-daemon-v') with: - subject-checksums: packages/process-daemon/dist/SHA256SUMS + subject-path: | + ${{ runner.temp }}/in/process-daemon-bundle/github/*.tar.gz + ${{ runner.temp }}/in/process-daemon-bundle/github/release-manifest.json # The monorepo's Latest release drives OpenCode's own update paths, so this release must never become # Latest. It is drafted first because immutable releases lock assets once published. - name: Publish release - if: startsWith(github.ref, 'refs/tags/process-daemon-v') env: GH_TOKEN: ${{ github.token }} run: | + cd "$RUNNER_TEMP/in/process-daemon-bundle/github" + mv checksums.txt SHA256SUMS version="${GITHUB_REF_NAME#process-daemon-v}" gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --draft --verify-tag --latest=false \ --title "process-daemon v$version" \ --notes "opencode-pty $version (protocol $PROTOCOL_VERSION) from packages/process-daemon, published to npm as @opencode/pty@$version." - gh release upload "$GITHUB_REF_NAME" dist/*.tar.gz dist/SHA256SUMS dist/release-manifest.json --clobber --repo "$GITHUB_REPOSITORY" + gh release upload "$GITHUB_REF_NAME" ./*.tar.gz SHA256SUMS release-manifest.json --clobber --repo "$GITHUB_REPOSITORY" gh release edit "$GITHUB_REF_NAME" --draft=false --latest=false --repo "$GITHUB_REPOSITORY" - name: Publish npm packages - if: startsWith(github.ref, 'refs/tags/process-daemon-v') - run: | - version="${GITHUB_REF_NAME#process-daemon-v}" - for package in dist/npm/opencode-pty-*; do - name="$(node -p 'require(process.argv[1]).name' "$(realpath "$package/package.json")")" - if ! npm view "$name@$version" version >/dev/null 2>&1; then - npm publish "$package" --access public --provenance - fi - done - name="@opencode/pty" - if ! npm view "$name@$version" version >/dev/null 2>&1; then - npm publish dist/npm/opencode-pty --access public --provenance - fi + run: bash .github/release/publish-process-daemon.sh "$RUNNER_TEMP/in/process-daemon-bundle/npm" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0d21fcfbc84f..615fe31cf006 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -113,33 +113,31 @@ jobs: outputs: sha: ${{ steps.tag.outputs.sha || github.sha }} steps: - # The tag is pushable only with the release deploy key, so without the release environment there is nothing - # to fetch and the checkout below falls back to the workflow token. - - name: Configure AWS credentials + # Fetch the deploy key only for the tag command; checkout uses its read-only token. + - id: aws + name: Configure AWS credentials if: needs.plan.outputs.channel == 'latest' && needs.plan.outputs.dry_run != 'true' uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: + with: &release-role + output-env-credentials: false + output-credentials: true role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release role-session-name: opencode-${{ github.run_id }} aws-region: us-east-1 - - name: Read release tag key - if: needs.plan.outputs.channel == 'latest' && needs.plan.outputs.dry_run != 'true' - uses: aws-actions/aws-secretsmanager-get-secrets@2297f9a879480a9e3af9b293ed15c70caf8e1c88 # v3.0.2 - with: - secret-ids: RELEASE_TAG_KEY,opencode/release/RELEASE_TAG_KEY - parse-json-secrets: false - - name: Check out if: needs.plan.outputs.channel == 'latest' uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 with: - ssh-key: ${{ env.RELEASE_TAG_KEY }} + persist-credentials: false - id: tag name: Tag if: needs.plan.outputs.channel == 'latest' - run: bash .github/release/tag-release.sh + run: bash .github/release/with-secrets.sh RELEASE_TAG_KEY=opencode/release/RELEASE_TAG_KEY -- bash .github/release/tag-release.sh env: + AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }} + AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }} + AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }} OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} # ---- Build: repository code; no environment, secrets or id-token -------------------------------------------- @@ -212,7 +210,7 @@ jobs: 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: darwin-arm64, host: blacksmith-6vcpu-macos-26 } - { target: windows-arm64, host: blacksmith-4vcpu-windows-2025 } - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } runs-on: ${{ matrix.host }} @@ -323,9 +321,9 @@ jobs: matrix: include: - target: darwin-x64 - host: ${{ (needs.plan.outputs.channel == 'dev' || needs.plan.outputs.channel == 'beta') && 'macos-26' || 'macos-26-intel' }} + host: ${{ (needs.plan.outputs.channel == 'dev' || needs.plan.outputs.channel == 'beta') && 'blacksmith-6vcpu-macos-26' || 'macos-26-intel' }} install: ${{ (needs.plan.outputs.channel == 'dev' || needs.plan.outputs.channel == 'beta') && '--os=darwin --cpu=*' || '--os=darwin --cpu=x64' }} - - { target: darwin-arm64, host: macos-26, install: --os=darwin --cpu=arm64 } + - { target: darwin-arm64, host: blacksmith-6vcpu-macos-26, install: --os=darwin --cpu=arm64 } # github-hosted: blacksmith lacks the ARM64 MSVC cross-compilation toolchain - target: windows-arm64 host: ${{ (needs.plan.outputs.channel == 'dev' || needs.plan.outputs.channel == 'beta') && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }} @@ -433,45 +431,33 @@ jobs: uses: ./.github/release/download with: pattern: "{build-npm,build-desktop-darwin-*}" - - name: Configure AWS credentials + - &configure-release-role + id: aws + name: Configure AWS credentials if: needs.plan.outputs.dry_run != 'true' uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release - role-session-name: opencode-${{ github.run_id }} - aws-region: us-east-1 - - name: Read signing secrets - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/aws-secretsmanager-get-secrets@2297f9a879480a9e3af9b293ed15c70caf8e1c88 # v3.0.2 - with: - secret-ids: | - APPLE_SIGNING_CERTIFICATE,shared/APPLE_SIGNING_CERTIFICATE - APPLE_NOTARY_KEY,shared/APPLE_NOTARY_KEY - parse-json-secrets: false + with: *release-role # The certificate has no password, which apple-actions/import-codesign-certs rejects. The sign scripts look up # the identity in build.keychain, and codesign finds the key through the user search list. - name: Import certificate if: needs.plan.outputs.dry_run != 'true' - run: | - cert="$RUNNER_TEMP/cert.p12" - keychain_password=$(openssl rand -base64 32) - printf '%s' "$APPLE_SIGNING_CERTIFICATE" | base64 --decode > "$cert" - security create-keychain -p "$keychain_password" build.keychain - security set-keychain-settings -lut 21600 build.keychain - security unlock-keychain -p "$keychain_password" build.keychain - security import "$cert" -k build.keychain -P "" -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productsign - security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" build.keychain > /dev/null - security list-keychains -d user -s build.keychain $(security list-keychains -d user | tr -d '"') - rm -f "$cert" + env: &aws-step + AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }} + AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }} + AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }} + run: bash .github/release/with-secrets.sh APPLE_SIGNING_CERTIFICATE=shared/APPLE_SIGNING_CERTIFICATE -- bash .github/release/import-certificate.sh - 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" \ + bash .github/release/with-secrets.sh APPLE_NOTARY_KEY=shared/APPLE_NOTARY_KEY -- bash .github/release/sign-desktop-macos.sh "$RUNNER_TEMP/out" \ "$RUNNER_TEMP"/in/build-desktop-darwin-*/opencode-desktop-mac-*.app.tar env: + AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }} + AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }} + AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }} APPLE_NOTARY_KEY_ID: ${{ vars.APPLE_NOTARY_KEY_ID }} APPLE_NOTARY_ISSUER_ID: ${{ vars.APPLE_NOTARY_ISSUER_ID }} - id: upload @@ -519,6 +505,7 @@ jobs: if: needs.plan.outputs.dry_run != 'true' uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0 with: + cache-dependencies: false endpoint: ${{ vars.AZURE_TRUSTED_SIGNING_ENDPOINT }} signing-account-name: ${{ vars.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} certificate-profile-name: ${{ vars.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }} @@ -651,18 +638,16 @@ jobs: steps: - *checkout-release - *download-signed-cli - - name: Configure AWS credentials - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release - role-session-name: opencode-${{ github.run_id }} - aws-region: us-east-1 - - name: Cloudflare token + - *configure-release-role + - &cloudflare-token + name: Cloudflare token id: cloudflare-token if: needs.plan.outputs.dry_run != 'true' run: bash .github/release/cloudflare-token.sh env: + AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }} + AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }} + AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }} CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} - name: Publish run: bash .github/release/publish-cli.sh "$RUNNER_TEMP/in/build-archives" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows" @@ -686,19 +671,8 @@ jobs: 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: Configure AWS credentials - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release - role-session-name: opencode-${{ github.run_id }} - aws-region: us-east-1 - - name: Cloudflare token - id: cloudflare-token - if: needs.plan.outputs.dry_run != 'true' - run: bash .github/release/cloudflare-token.sh - env: - CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} + - *configure-release-role + - *cloudflare-token - name: Publish run: | bash .github/release/publish-desktop.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-desktop-windows-installer" \ @@ -737,21 +711,10 @@ jobs: steps: - *checkout-release - *download-signed-cli - - name: Configure AWS credentials - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release - role-session-name: opencode-${{ github.run_id }} - aws-region: us-east-1 - - name: Read publish secrets - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/aws-secretsmanager-get-secrets@2297f9a879480a9e3af9b293ed15c70caf8e1c88 # v3.0.2 - with: - secret-ids: HOMEBREW_TAP_DEPLOY_KEY,shared/HOMEBREW_TAP_DEPLOY_KEY - parse-json-secrets: false + - *configure-release-role - name: Publish - run: bash .github/release/publish-homebrew.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/build-archives" + env: *aws-step + run: bash .github/release/with-secrets.sh HOMEBREW_TAP_DEPLOY_KEY=shared/HOMEBREW_TAP_DEPLOY_KEY -- bash .github/release/publish-homebrew.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/build-archives" # The AUR package installs the published npm tarballs, so it follows the npm publish. publish-aur: @@ -766,21 +729,10 @@ jobs: steps: - *checkout-release - *download-signed-cli - - name: Configure AWS credentials - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release - role-session-name: opencode-${{ github.run_id }} - aws-region: us-east-1 - - name: Read publish secrets - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/aws-secretsmanager-get-secrets@2297f9a879480a9e3af9b293ed15c70caf8e1c88 # v3.0.2 - with: - secret-ids: AUR_KEY,shared/AUR_SSH_KEY - parse-json-secrets: false + - *configure-release-role - name: Publish - run: bash .github/release/publish-aur.sh "$RUNNER_TEMP/in/build-npm" + env: *aws-step + run: bash .github/release/with-secrets.sh AUR_KEY=shared/AUR_SSH_KEY -- bash .github/release/publish-aur.sh "$RUNNER_TEMP/in/build-npm" # WinGet manifests as data. Submission to microsoft/winget-pkgs stays paused until the packages are accepted. publish-winget: @@ -838,22 +790,13 @@ jobs: env: *env steps: - *checkout-release - - name: Configure AWS credentials - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 - with: - role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release - role-session-name: opencode-${{ github.run_id }} - aws-region: us-east-1 - - name: Read publish secrets - if: needs.plan.outputs.dry_run != 'true' - uses: aws-actions/aws-secretsmanager-get-secrets@2297f9a879480a9e3af9b293ed15c70caf8e1c88 # v3.0.2 - with: - secret-ids: DISCORD_WEBHOOK,opencode/release/DISCORD_WEBHOOK - parse-json-secrets: false + - *configure-release-role - name: Publish - run: bash .github/release/publish-discord.sh + run: bash .github/release/with-secrets.sh DISCORD_WEBHOOK=opencode/release/DISCORD_WEBHOOK -- bash .github/release/publish-discord.sh env: + AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }} + AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }} + AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }} 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. diff --git a/AGENTS.md b/AGENTS.md index 6d25b039c53c..28a3364e2d82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -234,7 +234,7 @@ const table = sqliteTable("session", { - The budget can ask instead of degrading, through the `budget` permission: `allow` degrades as before, `ask` asks once per request while past the budget, `deny` ends every request that goes past it. An authorized run keeps its model and tools; a refused one ends in the same step without tools as the ceiling, carrying the reason given. - That gate reads the level, not the step that crossed: an agent past its budget is past it on every later step. Only a rule naming `budget` decides it, never a ruleset's catch-all, which is about tools and which several built-in agents set to deny. It never asks on a step that already ends the run, because a question a yes cannot change only makes a run configured to stop wait for somebody. - A model resolved as small must still be able to call tools, and must differ from the session model in provider as well as id. The same id on another provider is a different route, different credentials and different billing. -- A subagent reported as done must say what it left running. Spawning with `background: true` detaches, and the detached task's answer goes to the subagent's own Session, so a caller told only "completed" would act on a result that is missing a piece. +- A subagent's report must say what it left running. Subagents always run in the background and report to their caller each time they go idle, but work they detached keeps running past that report, so a caller told only "completed" would act on a result that is missing a piece. ## Configuration Compatibility diff --git a/bun.lock b/bun.lock index a61adea3a4f3..6288394976f0 100644 --- a/bun.lock +++ b/bun.lock @@ -118,7 +118,7 @@ "@effect/platform-node": "catalog:", "@opencode/client": "workspace:*", "@opencode/plugin": "workspace:*", - "@opencode/pty": "0.5.0", + "@opencode/pty": "0.5.2", "@opencode/schema": "workspace:*", "@opencode/server": "workspace:*", "@opencode/tui": "workspace:*", @@ -227,7 +227,7 @@ "@opencode/codemode": "workspace:*", "@opencode/plugin": "workspace:*", "@opencode/plugin-browser": "workspace:*", - "@opencode/pty": "0.5.0", + "@opencode/pty": "0.5.2", "@opencode/schema": "workspace:*", "@opencode/util": "workspace:*", "@parcel/watcher": "2.5.1", @@ -238,7 +238,7 @@ "drizzle-orm": "catalog:", "effect": "catalog:", "fuzzysort": "3.1.0", - "gitlab-ai-provider": "6.23.1", + "gitlab-ai-provider": "6.24.0", "gray-matter": "4.0.3", "htmlparser2": "8.0.2", "http-proxy-agent": "7.0.2", @@ -666,7 +666,7 @@ "devDependencies": { "@opencode/client": "workspace:*", "@opencode/plugin": "workspace:*", - "@opencode/pty": "0.5.0", + "@opencode/pty": "0.5.2", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", "@typescript/native": "catalog:", @@ -1025,7 +1025,7 @@ "@effect/platform-node-shared": "4.1.0", "@effect/sql-sqlite-bun": "4.1.0", "@effect/sql-sqlite-node": "4.1.0", - "@hona/strobe": "0.28.0", + "@hona/strobe": "0.31.0", "@kobalte/core": "0.13.13", "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", @@ -1567,19 +1567,19 @@ "@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="], - "@hona/strobe": ["@hona/strobe@0.28.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.28.0", "@hona/strobe-darwin-x64": "0.28.0", "@hona/strobe-linux-arm64": "0.28.0", "@hona/strobe-linux-x64": "0.28.0", "@hona/strobe-win32-arm64": "0.28.0", "@hona/strobe-win32-x64": "0.28.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-5JzZqIMxeiLR5encQ1e+tCZl8zlkN+QGHAga/e+WOm2rk9m1Ep4bDy0oWUiPynhha45X9luOlJxoxs+8T5bJXg=="], + "@hona/strobe": ["@hona/strobe@0.31.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.31.0", "@hona/strobe-darwin-x64": "0.31.0", "@hona/strobe-linux-arm64": "0.31.0", "@hona/strobe-linux-x64": "0.31.0", "@hona/strobe-win32-arm64": "0.31.0", "@hona/strobe-win32-x64": "0.31.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-6fd7JLZTa8NPsRxHNAomd0jtpZUQWUEHhcKPwJ5hlTdQVtxjReZLg2pyEfrOb/YeVXgIallTKckWN3U6XuXFWQ=="], - "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.28.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zv10Kv1eYtJC8aVxcqOFdwxkBNQ4JWbo95+7dHxboFhf+zR6h4foV2VEmaSpHb59vSPFn29/OTTpkQD8UVg9pA=="], + "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.31.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-FAOQ1SjUFH/MHTF4DQa3FSs5LANt1wiH+XAhvKUwg4lta/gICWX7cNwej41cpUFcJtakEmhiGim1jB+AQAu7/A=="], - "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.28.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-8EsxZu6i/HfwUhfGqPdbyvPuK4PMHV23R6fVk0s60CB72VSsstl92PMY5REtEOE6nDysF1azsPs/myUVFzDlKw=="], + "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.31.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-kexHXnetb+wh9k0M9pICBXc0pstzc6J01rnynfbxK+AcM0VOQ0cYzDJ7dJ4ixOJAfXMWZYvwviHpp9qb16vAxQ=="], - "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.28.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-n/C0mRzvNcVUntBmCUes7j21N0Y25sGCgy/r53D/WZStysn/QVfOzCWtkkPjZ09TJ8MDY4bIOk7WPdV5s/fMgA=="], + "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.31.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-lUv3N326+mD4qkkcwB7pnVcWCdS+unG6dqxT3YfrIuhfzchJdAqjXlODZ9f8kEv2/TuKZjZO8UyVSbdUXJi9jg=="], - "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.28.0", "", { "os": "linux", "cpu": "x64" }, "sha512-G+z9vgn0OwF/K3tKx3QGpAI+GML1O2XJUGjorIYLQ0wmgi6G6FnKCb8Zk/hcKTdUxp5VNsElibPsd7JEGfrQvA=="], + "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.31.0", "", { "os": "linux", "cpu": "x64" }, "sha512-rmpfK8no/ZF3+QuLc7bUGF3EjNuF1d9nXt9OHczVnO+RLB4kWkBSFYVNS9G1MZIF4M/nkfnGG7z7ouIKLBOg0w=="], - "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.28.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-rHPNY0+XO+3dTaZO9r0gKWoWPr4aHNhZC6KNX5kIvJbJ2/QuEUyEJmzFkvSlx68ixl5rbg3lBGB2tO7YNOvotg=="], + "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.31.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1vTucrWfULAOsqBN03K3s5OehHCwM5jaRn/ziCU84oF88fKZPtqLFBC0f+KaNs3pWyxxdbq8tEIb9hJ37xtjDw=="], - "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.28.0", "", { "os": "win32", "cpu": "x64" }, "sha512-kZJ9l/lZ7zneU2NVj7p1WmSifVrWwRQFzIOw3MfEjaC1TqGD2+w0JFCNuzYCp7j8irtRC/OM7W5/9fLjGy/kxQ=="], + "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.31.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ldVK/CW1PKP1fYr9+c1n+M6ZdcRFAHhTIGjKlkS/jpA9SDvR68bLTvVHZUIg1L9Db63WMMQNXDsElcJ9Fx8unA=="], "@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="], @@ -1833,23 +1833,23 @@ "@opencode/protocol": ["@opencode/protocol@workspace:packages/protocol"], - "@opencode/pty": ["@opencode/pty@0.5.0", "", { "optionalDependencies": { "@opencode/pty-darwin-arm64": "0.5.0", "@opencode/pty-darwin-x64": "0.5.0", "@opencode/pty-linux-arm64-gnu": "0.5.0", "@opencode/pty-linux-arm64-musl": "0.5.0", "@opencode/pty-linux-x64-gnu": "0.5.0", "@opencode/pty-linux-x64-musl": "0.5.0", "@opencode/pty-win32-arm64": "0.5.0", "@opencode/pty-win32-x64": "0.5.0" }, "bin": { "opencode-pty": "bin/opencode-pty.js" } }, "sha512-2U0RfT5U1lp1BcegXLoSBYfBx9sBNw3uJ/pao4UWdNV6UDfmDNGzdc8m4K1Q4ByBkXhbh8hexa0JS7HZ0vSsgg=="], + "@opencode/pty": ["@opencode/pty@0.5.2", "", { "optionalDependencies": { "@opencode/pty-darwin-arm64": "0.5.2", "@opencode/pty-darwin-x64": "0.5.2", "@opencode/pty-linux-arm64-gnu": "0.5.2", "@opencode/pty-linux-arm64-musl": "0.5.2", "@opencode/pty-linux-x64-gnu": "0.5.2", "@opencode/pty-linux-x64-musl": "0.5.2", "@opencode/pty-win32-arm64": "0.5.2", "@opencode/pty-win32-x64": "0.5.2" }, "bin": { "opencode-pty": "bin/opencode-pty.js" } }, "sha512-SZrzOFZDQHvPndC+ZfDYB52qY/RFxeW0OmKeosSlm4I7tmdDxtvUYN/vy8yynh8678bL+1efbQGxhKa1nz0DCA=="], - "@opencode/pty-darwin-arm64": ["@opencode/pty-darwin-arm64@0.5.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-D+L/TnNUc35airWTBlLussnuDbZpKPQ2/uBHVkcycw6KrLYDb4hVoUJn8N5PXmLTnhmU64B4MUsdH9JoOZIi8w=="], + "@opencode/pty-darwin-arm64": ["@opencode/pty-darwin-arm64@0.5.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CxlLA/+ruVwt+QGOQEnBxiIImgpYU9EdW7bjvA0m+qSDOrFc0hAHOD13Suq3B2JJQxSsj7IM3XicQqmJfqe32Q=="], - "@opencode/pty-darwin-x64": ["@opencode/pty-darwin-x64@0.5.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-/JMtOIAY9WWszsauWnCwjl2Qr8PBihS94tLsxa8prZBVhbbpOzcFslQsqR8JnJ1gAVlYINxEVS79+QQPQ4NC9g=="], + "@opencode/pty-darwin-x64": ["@opencode/pty-darwin-x64@0.5.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-xn4W7y8D+93WM+5+VAwTsPJjw/U9TTEZJQdtIQqFwcCgPCQUylMGu4/xhFbyMllzSycZyysJuhV6CHq/J798zw=="], - "@opencode/pty-linux-arm64-gnu": ["@opencode/pty-linux-arm64-gnu@0.5.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-vNiHKopfKrX6vj8OmDXYxZ+5JEZwf5djDzt3LOqeYuwStQRX2rxcl2/zjrvd5i8rAJw30RpJ+PTdS1t08vqtLA=="], + "@opencode/pty-linux-arm64-gnu": ["@opencode/pty-linux-arm64-gnu@0.5.2", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-0Kg1477t9VYHLkaOStiDuoC8S3qHH92ZY/QEgNSOavgkCAAbSEU0NrkIBhEi3Gnw5+ElvfgVcLzEwcM5cfiYAA=="], - "@opencode/pty-linux-arm64-musl": ["@opencode/pty-linux-arm64-musl@0.5.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-aW3lNGjit3FNAfpEskJgvTrtE2Lfnukpn8KmUVPUBN/EbRhT56h/N3ghzHYc5jIExETy06Xpy9i2xZxZQy0McQ=="], + "@opencode/pty-linux-arm64-musl": ["@opencode/pty-linux-arm64-musl@0.5.2", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-ZNk4nBooiVCvkB8cCfwn2nDV5OQHdFk/MfRQzBfwk28LakM1YC4lSwZPzY0McvFVjUILie9UEKntHRzgPaDBcA=="], - "@opencode/pty-linux-x64-gnu": ["@opencode/pty-linux-x64-gnu@0.5.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-XaMnBSh1QvJmcYKSOtx1fVvldZ+x212zAHaq8ovyafufqp6/Xl3AuqPCXwPFnycW2PfbUDwfZ7dBCXThQtOt3Q=="], + "@opencode/pty-linux-x64-gnu": ["@opencode/pty-linux-x64-gnu@0.5.2", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-iLEq9nWOKfm9iWqDGlhqcx+SSLFqBz3toX83n/W+MSlxWg5048HzlGd/3RxY04sxmI6dlg/Ygz3KqP3bCgfusg=="], - "@opencode/pty-linux-x64-musl": ["@opencode/pty-linux-x64-musl@0.5.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-30LVc91GrJP8YD6chLic4+5nMsLz3hCYu2cxPQczSKyRWMyBjuwvCf040UzlRAQiGllp8KBb7nYa8SCtq2/49Q=="], + "@opencode/pty-linux-x64-musl": ["@opencode/pty-linux-x64-musl@0.5.2", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-jBIw7oimeoTXoHH4yvtVFoPZGU1Rx+kdTVU8HVFGwCDNmeP4hI+R7QhF/pEsKZxzykTskR5x9u5ciiVJ5WEnMg=="], - "@opencode/pty-win32-arm64": ["@opencode/pty-win32-arm64@0.5.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-BYVSytysZvXmIQcP9VbbXbOV417RLW/BATiAK8MMbHBF6fzqQlpAMTi4cQmWJKOlHgrREKeMBw786qZ8BES3Vg=="], + "@opencode/pty-win32-arm64": ["@opencode/pty-win32-arm64@0.5.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-giPMQUcSyoe2z6wQN6MKhRgu4rVv/xqscX8qOVt2lu7yfRNfviPFVY0qFPGOcu1L3e+DT5VrIo2QZeRBeV1Bdw=="], - "@opencode/pty-win32-x64": ["@opencode/pty-win32-x64@0.5.0", "", { "os": "win32", "cpu": "x64" }, "sha512-42OEc6vvlL/gXAairdWf4DLX6juPrpOycES9sp3iE3UfQ5KsRsuQ6F3HFFmSBkiZ/yUhJtKoJdJbquBTNEL+Ow=="], + "@opencode/pty-win32-x64": ["@opencode/pty-win32-x64@0.5.2", "", { "os": "win32", "cpu": "x64" }, "sha512-hXdQWx+gHhQMRovDS3Fm0n4LuvSgLxRqEdicpVQzjjCTPYBMSBysWYRheQ2ydZlP0GCQ2Ymoi0dixgAHTYHO8A=="], "@opencode/schema": ["@opencode/schema@workspace:packages/schema"], @@ -3153,7 +3153,7 @@ "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], - "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=="], + "gitlab-ai-provider": ["gitlab-ai-provider@6.24.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", "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-O3clsZqSOcgFM8IztQVz7OSnKJoSG5yI0Uo3oWpgPusGy0VT7e40lZQDE0blN/FzzJnsV9JlDz+CIQ/El0z//Q=="], "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/package.json b/package.json index edaefaad6004..c395f684705d 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "@effect/sql-sqlite-node": "4.1.0", "@npmcli/arborist": "9.4.0", "@types/bun": "1.4.3", - "@hona/strobe": "0.28.0", + "@hona/strobe": "0.31.0", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@opentui/core": "0.8.4", diff --git a/packages/ai/package.json b/packages/ai/package.json index fc81f06bcd7d..77acee5df1a2 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -77,6 +77,7 @@ "./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/decisions": "./src/providers/google/decisions.ts", "./providers/google/embeddings": "./src/providers/google/embeddings.ts", "./providers/google/images": "./src/providers/google/images.ts", "./providers/google/interactions": "./src/providers/google/interactions.ts", @@ -141,6 +142,7 @@ "./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-decisions": "./src/protocols/google-decisions.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", diff --git a/packages/ai/src/protocols/google-decisions.ts b/packages/ai/src/protocols/google-decisions.ts new file mode 100644 index 000000000000..fcf7e3e79cb5 --- /dev/null +++ b/packages/ai/src/protocols/google-decisions.ts @@ -0,0 +1,179 @@ +import { Effect, Schema } from "effect" +import { DecisionResponse, DecisionUsage, type DecisionPart, type DecisionRequest } from "../decision.js" +import type { Media } from "../media.js" +import { DecisionRoute } from "../route/decision.js" +import { Endpoint } from "../route/endpoint.js" +import { MediaProtocol } from "../route/media-protocol.js" +import { + AIError, + ProviderID, + UnsupportedOperationError, + mergeJsonRecords, + type ProviderOptions, +} from "../schema/index.js" +import { encodeJson } from "../utils/json.js" +import { JsonObject, knownString, ProviderShared } from "./shared.js" +import { SystemOne } from "./system-one.js" +import { MediaInput } from "./utils/media-input.js" + +const ID = "google-decisions" +const NAME = "Google Decisions" +export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta" + +const Options = Schema.Struct({ + /** Token budget for every image and video input; `ultra_high` applies to images only. */ + mediaResolution: Schema.optional(knownString<"low" | "medium" | "high" | "ultra_high">()), +}) +/** Known fields map to their wire names; anything else is sent as given. */ +export type OptionsInput = ProviderOptions & typeof Options.Encoded + +const Usage = Schema.StructWithRest( + Schema.Struct({ + total_input_tokens: Schema.optional(Schema.Number), + total_output_tokens: Schema.optional(Schema.Number), + total_tokens: Schema.optional(Schema.Number), + }), + [JsonObject], +) +const Response = Schema.Struct({ + answers: Schema.Record(Schema.String, SystemOne.Answer), + usage: Schema.optional(Usage), +}) + +const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options)) + +const fromRequest = Effect.fn("GoogleDecisions.fromRequest")(function* (request: DecisionRequest) { + const options = yield* decodeOptions(request.providerOptions ?? {}) + const { mediaResolution: _, ...native } = request.providerOptions ?? {} + return { + ...mergeJsonRecords(native, request.http?.body), + model: request.model.id, + input: separateText( + yield* Effect.forEach(request.input, (part) => inputPart(request, part, options.mediaResolution)), + ), + questions: { + ...(yield* SystemOne.encodeQuestions(request.questions)), + // Google names System One's predicate criteria `true_description` and `false_description`. + ...Object.fromEntries( + request.questions.flatMap((question) => + question.type === "predicate" && question.criteria !== undefined + ? [ + [ + question.name, + { + type: "noul", + instructions: question.instructions, + criteria: { + ...(question.criteria.true === undefined ? {} : { true_description: question.criteria.true }), + ...(question.criteria.false === undefined ? {} : { false_description: question.criteria.false }), + }, + }, + ], + ] + : [], + ), + ), + }, + } +}) + +const inputPart = ( + request: DecisionRequest, + part: DecisionPart, + resolution: string | undefined, +): Effect.Effect, AIError> => { + if (part.type === "text") return Effect.succeed({ type: "text", text: part.text }) + // Google reads every text block as text; JSON is serialized so its keys are never parsed as content blocks. + if (part.type === "json") return Effect.succeed({ type: "text", text: encodeJson(part.value) }) + return mediaPart(request, part.media, resolution) +} + +// Google joins adjacent text blocks with no separator, so each one after another starts on a new line. +const separateText = (blocks: ReadonlyArray>) => + blocks.map((block, index) => + block.type === "text" && blocks[index - 1]?.type === "text" ? { ...block, text: `\n${block.text}` } : block, + ) + +const mediaPart = (request: DecisionRequest, asset: Media.Asset, resolution: string | undefined) => { + const type = + asset.kind === "image" || asset.kind === "audio" || asset.kind === "video" + ? asset.kind + : asset.mediaType.toLowerCase() === "application/pdf" + ? "document" + : undefined + if (type === undefined) + return Effect.fail( + new AIError({ + reason: new UnsupportedOperationError({ + operation: "decision.media", + provider: request.model.provider, + route: request.model.route.id, + message: `${NAME} takes images, audio, video and PDFs; got ${asset.mediaType}`, + }), + }), + ) + const block = { + type, + mime_type: asset.mediaType.toLowerCase(), + // `ultra_high` is image-only, so video keeps Google's default for it. + ...(resolution !== undefined && (type === "image" || (type === "video" && resolution !== "ultra_high")) + ? { resolution } + : {}), + } + const inline = asset.inline() + if (inline) return Effect.succeed({ ...block, data: inline.base64 }) + // Google fetches URLs itself, so one that needs our download credentials can't be forwarded. + if (asset.source.type === "url" && /^https:\/\//i.test(asset.source.url) && asset.headers === undefined) + return Effect.succeed({ ...block, uri: asset.source.url }) + const file = MediaInput.refID(asset, ProviderID.make("google")) + if (file !== undefined) return Effect.succeed({ ...block, uri: file }) + return Effect.fail( + ProviderShared.invalidRequest( + `${NAME} accepts inline media, public HTTPS URLs and Google Files API URIs; materialize ${asset.source.type} media first`, + ), + ) +} + +const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "google" }).decodeJson(Response) + +export const protocol = DecisionRoute.protocol({ + id: ID, + name: NAME, + body: { from: fromRequest }, + response: { + decode: Effect.fn("GoogleDecisions.decodeResponse")(function* (response, context) { + const output = yield* decodeDocument(response) + const data = output.value + const answers = data.answers + const names = context.request.questions.map((question) => question.name) + if (Object.keys(answers).length !== names.length || !names.every((name) => Object.hasOwn(answers, name))) + return yield* output.invalid(`${NAME} answers do not match the requested questions`) + return new DecisionResponse({ + answers: context.request.questions.map((question) => SystemOne.toAnswer(question, answers[question.name])), + usage: + data.usage === undefined + ? undefined + : new DecisionUsage({ + inputTokens: data.usage.total_input_tokens, + outputTokens: data.usage.total_output_tokens, + totalTokens: ProviderShared.totalTokens( + data.usage.total_input_tokens, + data.usage.total_output_tokens, + data.usage.total_tokens, + ), + }), + providerMetadata: + data.usage === undefined ? undefined : { [context.providerMetadataKey]: { usage: data.usage } }, + }) + }), + }, +}) + +export const route = DecisionRoute.make({ + id: ID, + provider: "google", + protocol, + endpoint: Endpoint.path("/decisions", { baseURL: DEFAULT_BASE_URL }), +}) + +export * as GoogleDecisions from "./google-decisions.js" diff --git a/packages/ai/src/protocols/index.ts b/packages/ai/src/protocols/index.ts index 14baffe0a299..25e92a8d3cf3 100644 --- a/packages/ai/src/protocols/index.ts +++ b/packages/ai/src/protocols/index.ts @@ -3,6 +3,7 @@ export * as BedrockConverse from "./bedrock-converse.js" export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js" export * as CohereChat from "./cohere-chat.js" export * as Gemini from "./gemini.js" +export * as GoogleDecisions from "./google-decisions.js" export * as GoogleEmbedContent from "./google-embed-content.js" export * as GoogleInteractions from "./google-interactions.js" export * as GoogleVertexPredictEmbeddings from "./google-vertex-predict-embeddings.js" diff --git a/packages/ai/src/protocols/system-one.ts b/packages/ai/src/protocols/system-one.ts index 10bb6a60696a..007d50cc4590 100644 --- a/packages/ai/src/protocols/system-one.ts +++ b/packages/ai/src/protocols/system-one.ts @@ -38,6 +38,8 @@ const Answer = Schema.Union([ probabilities: Schema.Record(Schema.String, Probability), confidence: Probability, }), + // OpenRouter's and OpenCode Zen's answer for a question the upstream model declined. + Schema.Struct({ type: Schema.Literal("refusal"), message: Schema.optional(Schema.String) }), ]).pipe(Schema.toTaggedUnion("type")) const NativeUsage = Schema.StructWithRest( Schema.Struct({ @@ -94,7 +96,7 @@ const encodeQuestions = (questions: ReadonlyArray) => if (new Set(keys).size !== keys.length) return Effect.fail( ProviderShared.invalidRequest( - `System One choice options are strings; "${question.name}" has a boolean and a string with the same text`, + `Decision choice options are sent as string keys; "${question.name}" has a boolean and a string with the same text`, ), ) return Effect.succeed([ @@ -122,7 +124,8 @@ const placeMedia = Effect.fnUntraced(function* (request: DecisionRequest, mediaI }) const media = parts.flatMap((part) => (part.type === "media" ? [part.media] : [])) if (media.length === 0) return { state: state(parts.map(plain)) } - if (mediaInput === "state") return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) } + if (mediaInput === "state") + return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported, true)) } // Chat-style content in one user message: text and JSON as text parts, media as in `state`. if (mediaInput === "state.messages") return { @@ -132,7 +135,7 @@ const placeMedia = Effect.fnUntraced(function* (request: DecisionRequest, mediaI role: "user", content: yield* Effect.forEach(parts, (part) => part.type === "media" - ? stateItem(part, unsupported) + ? stateItem(part, unsupported, false) : Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) }), ), }, @@ -184,23 +187,42 @@ const plain = (part: DecisionPart) => { return undefined } +/** A media part as a Chat Completions content part; `files` sends other media, such as PDFs, as `file` parts. */ const stateItem = ( part: DecisionPart, unsupported: (asset: Media.Asset, accepted: string) => AIError, + files: boolean, ): Effect.Effect => { if (part.type !== "media") return Effect.succeed(plain(part)) const asset = part.media - if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video") + if (!files && asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video") return Effect.fail(unsupported(asset, "images, audio and video")) return ProviderShared.requireInlineMedia(NAME, asset).pipe( Effect.map((inline) => { if (asset.kind === "image") return { type: "image_url", image_url: { url: inline.dataUrl } } if (asset.kind === "video") return { type: "video_url", video_url: { url: inline.dataUrl } } - return { type: "input_audio", input_audio: { data: inline.base64, format: inline.mime.slice("audio/".length) } } + if (asset.kind === "audio") { + const format = inline.mime.slice("audio/".length).toLowerCase() + return { type: "input_audio", input_audio: { data: inline.base64, format: audioFormats[format] ?? format } } + } + return { + type: "file", + file: { file_data: inline.dataUrl, ...(part.filename === undefined ? {} : { filename: part.filename }) }, + } }), ) } +/** OpenRouter's `input_audio` format names for MIME subtypes that aren't one themselves. */ +const audioFormats: Readonly> = { + "x-wav": "wav", + wave: "wav", + "vnd.wave": "wav", + "x-m4a": "m4a", + "x-aiff": "aiff", + "x-flac": "flac", +} + /** Map System One's answers, keyed by question name, back to the request's question order. */ export const toResponse = ( data: Response, @@ -237,6 +259,13 @@ export const toResponse = ( } const toAnswer = (question: DecisionQuestion, answer: typeof Answer.Type): DecisionAnswer => { + if (answer.type === "refusal") + return { + name: question.name, + type: "error", + reason: "refusal", + ...(answer.message === undefined ? {} : { message: answer.message }), + } if (answer.type === "noul") return { name: question.name, type: "predicate", probability: answer.noul } if (answer.type === "choice") { const choices = question.type === "choice" ? question.choices : [] @@ -294,4 +323,13 @@ export const route = DecisionRoute.make({ endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }), }) -export const SystemOne = { Response, encodeBody, toResponse, protocol, route } as const +export const SystemOne = { + Answer, + Response, + encodeBody, + encodeQuestions, + toAnswer, + toResponse, + protocol, + route, +} as const diff --git a/packages/ai/src/provider-error.ts b/packages/ai/src/provider-error.ts index ff7edbc18921..609980b72b8b 100644 --- a/packages/ai/src/provider-error.ts +++ b/packages/ai/src/provider-error.ts @@ -131,6 +131,12 @@ const CONTENT_POLICY_CODES = new Set([ "refusal", "datainspectionfailed", "moderation_blocked", + // Gemini Decisions rejects blocked input with these `error.code` strings on a 400. + "safety", + "prohibited_content", + "blocklist", + "image_safety", + "content_blocked", ]) // OpenCode Zen replaces upstream codes outside its allow-list but keeps the original // as a `[code]` label at the start of the rewritten message. diff --git a/packages/ai/src/providers/google.ts b/packages/ai/src/providers/google.ts index 145e8ce52415..48ac098ec32c 100644 --- a/packages/ai/src/providers/google.ts +++ b/packages/ai/src/providers/google.ts @@ -8,6 +8,7 @@ import { GoogleEmbedContent, type OptionsInput as GoogleEmbeddingOptionsInput, } from "../protocols/google-embed-content.js" +import { GoogleDecisions } from "../protocols/google-decisions.js" import { GoogleInteractions } from "../protocols/google-interactions.js" import { GoogleImages } from "../protocols/google-images.js" import { GoogleSpeech } from "../protocols/google-speech.js" @@ -23,6 +24,7 @@ export type { GoogleVideoOptions } from "../protocols/google-video.js" export type GeminiOptionsInput = Gemini.OptionsInput export type GeminiProviderOptionsInput = Gemini.ProviderOptionsInput export type GoogleInteractionsOptionsInput = GoogleInteractions.OptionsInput +export type GoogleDecisionsOptionsInput = GoogleDecisions.OptionsInput export const id = ProviderID.make("google") @@ -77,6 +79,10 @@ export const configure = (input: Config = {}) => { transcription: (modelID: string | ModelID) => GoogleTranscription.model({ ...media, id: modelID }), embedding: (modelID: string | ModelID, providerOptions?: ProviderOptions) => embeddingRoute.model({ id: modelID, providerOptions }), + decision: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + GoogleDecisions.route + .with({ endpoint: { baseURL: media.baseURL }, auth: media.auth, headers: media.headers, http: media.http }) + .model({ id: modelID, providerOptions }), configure, } } @@ -92,6 +98,10 @@ export const embeddingModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).embedding(modelID, input.providerOptions) } +export const decisionModel = (modelID: string, settings?: Settings) => { + const input = toConfig(settings) + return configure(input).decision(modelID, input.providerOptions) +} export const image = provider.image export const embedding = provider.embedding @@ -100,3 +110,4 @@ export const interactions = provider.interactions export const video = provider.video export const speech = provider.speech export const transcription = provider.transcription +export const decision = provider.decision diff --git a/packages/ai/src/providers/google/decisions.ts b/packages/ai/src/providers/google/decisions.ts new file mode 100644 index 000000000000..9299a86ead1b --- /dev/null +++ b/packages/ai/src/providers/google/decisions.ts @@ -0,0 +1,2 @@ +export { decisionModel as model } from "../google.js" +export type { Settings } from "../google.js" diff --git a/packages/ai/test/decision.test.ts b/packages/ai/test/decision.test.ts index 8b84c828e891..54fa1dcd0821 100644 --- a/packages/ai/test/decision.test.ts +++ b/packages/ai/test/decision.test.ts @@ -5,6 +5,7 @@ import { ai, DecisionClient, DecisionUsage, Media } from "../src/effect.js" import { Baseten, CloudflareWorkersAI, + Google, OpenAI, OpenCode, OpenRouter, @@ -291,6 +292,67 @@ describe("Decision", () => { ), ) + it.effect("sends PDFs as file parts and audio by its OpenRouter format name in the OpenRouter state", () => + ai.decision + .generate({ + model: OpenRouter.configure({ apiKey: "openrouter-key", baseURL: "https://openrouter.test/api/v1" }).decision( + "google/gemini-decision-1", + ), + input: [ + { type: "media", media: Media.base64("JVBE", "application/pdf"), filename: "invoice.pdf" }, + { type: "media", media: Media.base64("AAAA", "audio/x-wav") }, + ], + questions: [{ name: "refund", type: "predicate", instructions: "Is this a refund request?" }], + }) + .pipe( + Effect.provide( + client((input) => { + expect(JSON.parse(input.text).state).toEqual([ + { type: "file", file: { file_data: "data:application/pdf;base64,JVBE", filename: "invoice.pdf" } }, + { type: "input_audio", input_audio: { data: "AAAA", format: "wav" } }, + ]) + return Effect.succeed( + json(input, { model: "google/gemini-decision-1", answers: { refund: { type: "noul", noul: 0.9 } } }), + ) + }), + ), + ), + ) + + it.effect("returns a System One host's refusals as per-question errors", () => + ai.decision + .generate({ + model: OpenRouter.configure({ apiKey: "openrouter-key", baseURL: "https://openrouter.test/api/v1" }).decision( + "openai/gpt-6-luna-decisions", + ), + input: [{ type: "text", text: "hello" }], + questions: [ + { name: "greeting", type: "predicate", instructions: "Is this a greeting?" }, + { name: "unsafe", type: "predicate", instructions: "Something the model declines" }, + ], + }) + .pipe( + Effect.tap((response) => + Effect.sync(() => + expect(response.answers).toEqual([ + { name: "greeting", type: "predicate", probability: 0.99 }, + { name: "unsafe", type: "error", reason: "refusal" }, + ]), + ), + ), + Effect.provide( + client((input) => + Effect.succeed( + json(input, { + model: "openai/gpt-6-luna-decisions", + answers: { greeting: { type: "noul", noul: 0.99 }, unsafe: { type: "refusal" } }, + }), + ), + ), + ), + ), + ) + it.effect("puts media in a user message inside the Baseten state", () => ai.decision .generate({ @@ -487,6 +549,179 @@ describe("Decision", () => { }).pipe(Effect.provide(offline)), ) + it.effect("decides through Google Decisions with every media kind", () => + ai.decision + .generate({ + model: Google.configure({ + apiKey: "google-key", + baseURL: "https://google.test/v1beta", + http: { query: { trace: "1" } }, + }).decision("gemini-decision-1"), + input: [ + { type: "text", text: "Ticket:" }, + { type: "json", value: { ticket: "Please refund the duplicate charge." } }, + { type: "media", media: png }, + { type: "media", media: Media.base64("AAAA", "audio/wav") }, + { type: "media", media: Media.url("https://assets.test/clip.mp4", { mediaType: "video/mp4" }) }, + { type: "media", media: Media.base64("JVBERi0=", "application/pdf") }, + { type: "media", media: Media.ref("google", "https://google.test/v1beta/files/abc", "image/png") }, + ], + questions: [ + ...questions.slice(0, 2), + { ...questions[2], criteria: { true: "They want money back.", false: "Anything else." } }, + ], + providerOptions: { mediaResolution: "low", labels: { team: "support" } }, + }) + .pipe( + Effect.tap((response) => + Effect.sync(() => { + expect(response.answers).toEqual(expectedAnswers) + expect(response.usage).toEqual(new DecisionUsage({ inputTokens: 147, outputTokens: 0, totalTokens: 147 })) + expect(response.providerMetadata?.google?.usage).toEqual({ + total_input_tokens: 147, + input_tokens_by_modality: [{ modality: "text", tokens: 147 }], + total_output_tokens: 0, + total_tokens: 147, + }) + }), + ), + Effect.provide( + client((input) => { + expect(input.request.url).toBe("https://google.test/v1beta/decisions?trace=1") + expect(input.request.headers["x-goog-api-key"]).toBe("google-key") + expect(JSON.parse(input.text)).toEqual({ + labels: { team: "support" }, + model: "gemini-decision-1", + input: [ + { type: "text", text: "Ticket:" }, + { type: "text", text: '\n{"ticket":"Please refund the duplicate charge."}' }, + { type: "image", mime_type: "image/png", resolution: "low", data: "AQID" }, + { type: "audio", mime_type: "audio/wav", data: "AAAA" }, + { type: "video", mime_type: "video/mp4", resolution: "low", uri: "https://assets.test/clip.mp4" }, + { type: "document", mime_type: "application/pdf", data: "JVBERi0=" }, + { + type: "image", + mime_type: "image/png", + resolution: "low", + uri: "https://google.test/v1beta/files/abc", + }, + ], + questions: { + department: { + type: "choice", + instructions: "Which team should handle this?", + criteria: { billing: "Payments and refunds", technical: null }, + }, + urgency: { + type: "score", + instructions: "How urgent is this?", + criteria: ["Can wait", "Needs attention: Same day", "Blocking"], + }, + refund: { + type: "noul", + instructions: "Is the customer asking for a refund?", + criteria: { true_description: "They want money back.", false_description: "Anything else." }, + }, + }, + }) + return Effect.succeed( + json(input, { + answers: { ...systemOneAnswers, refund: { type: "noul", noul: 0.97, confidence: 0.97 } }, + usage: { + total_input_tokens: 147, + input_tokens_by_modality: [{ modality: "text", tokens: 147 }], + total_output_tokens: 0, + total_tokens: 147, + }, + }), + ) + }), + ), + ), + ) + + it.effect("sends an ultra_high resolution to Google Decisions images but not video", () => + ai.decision + .generate({ + model: Google.configure({ apiKey: "google-key" }).decision("gemini-decision-1"), + input: [ + { type: "media", media: png }, + { type: "media", media: Media.url("https://assets.test/clip.mp4", { mediaType: "video/mp4" }) }, + ], + questions: [{ name: "match", type: "predicate", instructions: "Does the clip match the image?" }], + providerOptions: { mediaResolution: "ultra_high" }, + }) + .pipe( + Effect.provide( + client((input) => { + expect(JSON.parse(input.text).input).toEqual([ + { type: "image", mime_type: "image/png", resolution: "ultra_high", data: "AQID" }, + { type: "video", mime_type: "video/mp4", uri: "https://assets.test/clip.mp4" }, + ]) + return Effect.succeed(json(input, { answers: { match: { type: "noul", noul: 0.5, confidence: 0.5 } } })) + }), + ), + ), + ) + + it.effect("reports Google Decisions safety blocks as content policy errors", () => + Effect.gen(function* () { + const error = yield* ai.decision + .generate({ + model: Google.configure({ apiKey: "google-key" }).decision("gemini-decision-1"), + input: [{ type: "text", text: "blocked" }], + questions: [{ name: "safe", type: "predicate", instructions: "Is this safe?" }], + }) + .pipe(Effect.flip) + expect(error.reason._tag).toBe("ContentPolicy") + }).pipe( + Effect.provide( + client((input) => + Effect.succeed( + json( + input, + { + error: { + code: "safety", + message: + "Request blocked due to safety violations (harmful content). Please modify your input and retry.", + }, + }, + { status: 400 }, + ), + ), + ), + ), + ), + ) + + it.effect("rejects media Google Decisions can't read before network I/O", () => + Effect.gen(function* () { + const model = Google.configure({ apiKey: "google-key" }).decision("gemini-decision-1") + const question = [{ name: "readable", type: "predicate", instructions: "Is it readable?" }] as const + const csv = yield* ai.decision + .generate({ model, input: [{ type: "media", media: Media.base64("YSxi", "text/csv") }], questions: question }) + .pipe(Effect.flip) + expect(csv.reason._tag).toBe("UnsupportedOperation") + const files = yield* ai.decision + .generate({ + model, + input: [{ type: "media", media: Media.ref("openai", "file-abc", "image/png") }], + questions: question, + }) + .pipe(Effect.flip) + expect(files.reason._tag).toBe("InvalidRequest") + const http = yield* ai.decision + .generate({ + model, + input: [{ type: "media", media: Media.url("http://assets.test/a.png", { mediaType: "image/png" }) }], + questions: question, + }) + .pipe(Effect.flip) + expect(http.reason._tag).toBe("InvalidRequest") + }).pipe(Effect.provide(offline)), + ) + it.effect("decides through Vercel AI Gateway's OpenAI Decisions endpoint", () => ai.decision .generate({ diff --git a/packages/ai/test/fixtures/recordings/google-decision/decides-choice-score-and-predicate-questions.json b/packages/ai/test/fixtures/recordings/google-decision/decides-choice-score-and-predicate-questions.json new file mode 100644 index 000000000000..c325a558c04e --- /dev/null +++ b/packages/ai/test/fixtures/recordings/google-decision/decides-choice-score-and-predicate-questions.json @@ -0,0 +1,33 @@ +{ + "version": 1, + "metadata": { + "model": "gemini-decision-1", + "tags": [ + "prefix:google-decision", + "provider:google", + "protocol:google-decisions" + ], + "name": "google-decision/decides-choice-score-and-predicate-questions", + "recordedAt": "2026-11-11T18:28:08.454Z" + }, + "interactions": [ + { + "transport": "http", + "request": { + "method": "POST", + "url": "https://generativelanguage.googleapis.com/v1beta/decisions", + "headers": { + "content-type": "application/json" + }, + "body": "{\"model\":\"gemini-decision-1\",\"input\":[{\"type\":\"text\",\"text\":\"I was charged twice for the same invoice. Please refund the duplicate payment today.\"}],\"questions\":{\"department\":{\"type\":\"choice\",\"instructions\":\"Which team should handle this support request?\",\"criteria\":{\"billing\":\"Payments, invoices, refunds, or failed charges\",\"technical\":\"Bugs, outages, or integrations\",\"sales\":\"Pricing, upgrades, or new accounts\"}},\"urgency\":{\"type\":\"score\",\"instructions\":\"How urgent is this support request?\",\"criteria\":[\"Can wait for normal support\",\"Needs prompt attention\",\"Actively blocking revenue\"]},\"refund\":{\"type\":\"noul\",\"instructions\":\"Is the customer asking for a refund?\"}}}" + }, + "response": { + "status": 200, + "headers": { + "content-type": "application/json" + }, + "body": "{\"answers\":{\"department\":{\"confidence\":0.9978076976696219,\"choice\":\"billing\",\"probabilities\":{\"billing\":0.9978076976696219,\"sales\":0.000687029007305657,\"technical\":0.001505273323072618},\"type\":\"choice\"},\"refund\":{\"confidence\":0.99,\"noul\":0.99,\"type\":\"noul\"},\"urgency\":{\"confidence\":0.5717345111874732,\"score\":1.1772012843064368,\"probabilities\":{\"1\":0.5717345111874732,\"0\":0.1255321022530451,\"2\":0.3027333865594818},\"legend\":{\"1\":\"Needs prompt attention\",\"2\":\"Actively blocking revenue\",\"0\":\"Can wait for normal support\"},\"type\":\"score\"}},\"usage\":{\"total_tokens\":242,\"total_input_tokens\":242,\"input_tokens_by_modality\":[{\"modality\":\"text\",\"tokens\":242}],\"total_output_tokens\":0}}" + } + } + ] +} diff --git a/packages/ai/test/provider/decision.recorded.test.ts b/packages/ai/test/provider/decision.recorded.test.ts index 396bbbb9eeb4..0f03aebfbe8e 100644 --- a/packages/ai/test/provider/decision.recorded.test.ts +++ b/packages/ai/test/provider/decision.recorded.test.ts @@ -6,6 +6,7 @@ import { CloudflareAIGateway, CloudflareWorkersAI, DigitalOcean, + Google, OpenAI, OpenCode, OpenRouter, @@ -71,6 +72,14 @@ const openai = recordedTests({ metadata: { model: "gpt-6-luna" }, }) +const google = recordedTests({ + prefix: "google-decision", + provider: "google", + protocol: "google-decisions", + requires: ["GOOGLE_API_KEY"], + metadata: { model: "gemini-decision-1" }, +}) + const cloudflareOptions = { redact: { url: (url: string) => url.replace(/\/client\/v4\/accounts\/[^/]+\//, "/client/v4/accounts/{account}/") }, } @@ -136,6 +145,17 @@ describe("Decision recorded", () => { ), ) + google.effect("decides choice score and predicate questions", () => + assertDecision( + Google.configure({ apiKey: process.env.GOOGLE_API_KEY ?? "fixture" }).decision("gemini-decision-1"), + ).pipe( + Effect.map((response) => { + expect(response.usage?.outputTokens).toBe(0) + expect(response.providerMetadata?.google?.usage).toMatchObject({ input_tokens_by_modality: expect.any(Array) }) + }), + ), + ) + cloudflareWorkersAI.effect("decides choice score and predicate questions", () => assertDecision( CloudflareWorkersAI.configure({ diff --git a/packages/ai/test/provider/media-entrypoints.test.ts b/packages/ai/test/provider/media-entrypoints.test.ts index 063be80f7e5e..fd4212b37d80 100644 --- a/packages/ai/test/provider/media-entrypoints.test.ts +++ b/packages/ai/test/provider/media-entrypoints.test.ts @@ -299,6 +299,16 @@ const decisions: ReadonlyArray> = [ auth: ["authorization", "Bearer do-key"], provider: "digitalocean", }, + { + name: "google", + load: async () => { + const { model } = await import("@opencode/ai/providers/google/decisions") + return model("gemini-decision-eap", { ...shared, apiKey: "google-key" }) + }, + url: "https://generativelanguage.googleapis.com/v1beta/decisions", + auth: ["x-goog-api-key", "google-key"], + provider: "google", + }, { name: "vercel-ai-gateway", load: async () => { diff --git a/packages/app/e2e/regression/subagent-child-navigation.spec.ts b/packages/app/e2e/regression/subagent-child-navigation.spec.ts index c60b60acfdef..d6a3ca90c776 100644 --- a/packages/app/e2e/regression/subagent-child-navigation.spec.ts +++ b/packages/app/e2e/regression/subagent-child-navigation.spec.ts @@ -78,7 +78,7 @@ test("keeps the parent title anchored when opening a subagent", async ({ page }) } }) -test("navigates from a running subagent card and hides background controls in the child", async ({ page }) => { +test("navigates from a running subagent card without a background control", async ({ page }) => { const runningChildID = "ses_running_child" await setupTimeline(page, { settings: { timelineDetail: { ...timelinePresets[2].value, subagents: { placement: "separate" } } }, @@ -95,11 +95,12 @@ test("navigates from a running subagent card and hides background controls in th id: "call_subagent", name: "subagent", state: { - status: "running", + status: "completed", input: { description: "Inspect code" }, metadata: { status: "running", sessionID: runningChildID }, + content: [{ type: "text", text: "The subagent is working in the background." }], }, - time: { created: 2 }, + time: { created: 2, completed: 3 }, }, ], time: { created: 2 }, @@ -109,7 +110,7 @@ test("navigates from a running subagent card and hides background controls in th sessionStatus: { [sessionID]: { type: "busy" }, [runningChildID]: { type: "busy" } }, }) const hint = page.getByRole("button", { name: /move running work to the background/i }) - await expect(hint).toBeVisible() + await expect(hint).toHaveCount(0) await page.locator('[data-component="task-tool-card"]').click() await expect(page).toHaveURL(new RegExp(`/session/${runningChildID}$`)) await expect(hint).toHaveCount(0) diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 54f3e0dbc8e9..fa7e6cc4108b 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1040,7 +1040,7 @@ test("grows a streaming row without a ResizeObserver loop error", async ({ page }) test.describe("background shortcut", () => { - test("offers a standalone running subagent to the background with Ctrl+B", async ({ page }) => { + test("does not offer a running subagent to the background", async ({ page }) => { await setupTimeline(page, { settings: { timelineDetail: { ...detailed, subagents: { placement: "separate" } } }, sessionMessages: [user, runningSubagent()], @@ -1050,19 +1050,8 @@ test.describe("background shortcut", () => { await expect(card).not.toContainText("(background)") await expect(page.getByText("Called `subagent`", { exact: false })).toHaveCount(0) await expect(page.locator('[data-component="background-tool-control"]')).toHaveCount(0) - const hint = backgroundHint(page) - await expect(hint).toBeVisible() + await expect(backgroundHint(page)).toHaveCount(0) await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0) - await expect - .poll(async () => { - const [cardBox, hintBox] = await Promise.all([card.boundingBox(), hint.boundingBox()]) - - if (!cardBox || !hintBox) return undefined - - return { aligned: Math.abs(cardBox.x - hintBox.x) < 2, ordered: cardBox.y < hintBox.y } - }) - .toEqual({ aligned: true, ordered: true }) - await expectBackgroundRequest(page) }) for (const name of ["read", "shell"] as const) { diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index d7f2f560bed4..6fb9d989c706 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -661,8 +661,6 @@ export const dict = { "session.timeline.status.waitingApproval": "Waiting for approval", "session.timeline.status.waitingAnswer": "Waiting for your answer", "session.timeline.status.waitingShell": "Waiting for shell", - "session.timeline.status.waitingAgent": "Waiting for subagent", - "session.timeline.status.waitingAgents": "Waiting for subagents", "session.timeline.status.working": "Working", "session.running.stop.subagent": "Interrupt subagent", "session.running.stop.shell": "Kill shell command", @@ -826,6 +824,11 @@ export const dict = { "sidebar.recent.section.recent": "Recent", "sidebar.recent.empty": "No recent sessions", "sidebar.recent.pin": "Pin", + "sidebar.recent.mute": "Mute", + "sidebar.recent.muted": "Muted", + "sidebar.recent.unmute": "Unmute", + "sidebar.recent.hide": "Hide", + "sidebar.recent.unhide": "Unhide", "sidebar.recent.unpin": "Unpin", "sidebar.recent.moveUp": "Move up", "sidebar.recent.moveDown": "Move down", diff --git a/packages/app/src/runtime/plugin/host-apis.tsx b/packages/app/src/runtime/plugin/host-apis.tsx index 60b62226f6e1..bda8e4152bbf 100644 --- a/packages/app/src/runtime/plugin/host-apis.tsx +++ b/packages/app/src/runtime/plugin/host-apis.tsx @@ -1118,6 +1118,18 @@ export function createPluginAttachment(apis: HostApis) { const result = { notification: false, sound: false } const session = options.session + if (session) { + await global.sessionPreferences.ready.promise + + const root = global.serverCtx(ServerConnection.Key.make(session.server))?.data.session.root(session.id) ?? session.id + + if ( + global.sessionPreferences.muted(session.server, session.id) || + global.sessionPreferences.muted(session.server, root) + ) + return result + } + await Promise.allSettled([ allowed.sound && global.notifications.sound(key, () => { diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index dfccc1419335..832a67739b53 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -33,6 +33,7 @@ import { createSessionMessageHandoffs } from "@/session/handoff" import { createServerNotificationState } from "@/shell/notifications/notification" import { createNotificationCoordinator } from "@/shell/notifications/coordinator" import { useCurrentRoute } from "@/shell/state/layout" +import { createSessionPreferences } from "@/shell/state/session-preferences" import { useTabs } from "@/shell/tabs/tabs" import { Persist, persisted } from "@/runtime/persistence/storage" import { createDesktopData } from "./data" @@ -52,6 +53,7 @@ export const { use: useGlobal, provider: GlobalProvider } = createSimpleContext( init: () => { const server = useServers() const models = createGlobalModels() + const sessionPreferences = createSessionPreferences() const notificationCoordinator = createNotificationCoordinator() const owner = getOwner() @@ -79,6 +81,7 @@ export const { use: useGlobal, provider: GlobalProvider } = createSimpleContext( () => server.local(effect.conn), server.projects.forServer(effect.key), notificationCoordinator, + sessionPreferences, ), dispose, }), @@ -124,6 +127,7 @@ export const { use: useGlobal, provider: GlobalProvider } = createSimpleContext( retry: serverHealth.retry, }, models, + sessionPreferences, /** Runs each keyed sound and system notification once across windows; notifications only while none has focus. */ notifications: notificationCoordinator, /** The live controller of a server, or undefined while it is unlisted or rejects our credentials. Reactive. */ @@ -198,6 +202,7 @@ function createServerController( isLocal: Accessor, projects: ReturnType, notificationCoordinator: ReturnType, + sessionPreferences: ReturnType, ) { const language = useLanguage() const settings = useSettings() @@ -254,7 +259,17 @@ function createServerController( const sync = createServerSyncContext(sdk, data) const autoApprove = createPermissionAutoApprover({ sdk, data }) - const notification = createServerNotificationState({ sdk, data, key: connKey, coordinator: notificationCoordinator }) + onCleanup(data.on("session.deleted", (event) => sessionPreferences.forget(connKey, event.data.sessionID))) + + const notification = createServerNotificationState({ + sdk, + data, + key: connKey, + coordinator: notificationCoordinator, + muted: (id) => sessionPreferences.muted(connKey, id), + preferencesLoaded: sessionPreferences.ready.promise, + }) + // Owned by the server, so a first prompt's handoff outlives the draft that sent it. const handoff = createSessionMessageHandoffs({ sdk, data }) diff --git a/packages/app/src/session/composer/activity-chips.css b/packages/app/src/session/composer/activity-chips.css index a7deefe854fc..7fb5a2f705a7 100644 --- a/packages/app/src/session/composer/activity-chips.css +++ b/packages/app/src/session/composer/activity-chips.css @@ -95,11 +95,11 @@ } /* A row whose Stop is in flight keeps showing its loader until the work leaves the list or the Stop settles. */ - [data-component="menu-v2-item"][data-stoppable]:is( - :hover, - [data-highlighted], - :has([data-slot="session-activity-stop"][aria-disabled="true"]) - ) { + [data-component="menu-v2-item"]:is( + :hover, + [data-highlighted], + :has([data-slot="session-activity-stop"][aria-disabled="true"]) + ) { [data-slot="session-activity-stop"] { visibility: visible; } @@ -126,8 +126,7 @@ } [data-slot="session-activity-stop"], - [data-component="menu-v2-item"][data-stoppable]:is(:hover, [data-highlighted]) - [data-slot="session-activity-elapsed"] { + [data-component="menu-v2-item"]:is(:hover, [data-highlighted]) [data-slot="session-activity-elapsed"] { visibility: visible; } } diff --git a/packages/app/src/session/composer/activity-chips.stories.tsx b/packages/app/src/session/composer/activity-chips.stories.tsx index 902b5ee7c10a..c65b17ab7dc3 100644 --- a/packages/app/src/session/composer/activity-chips.stories.tsx +++ b/packages/app/src/session/composer/activity-chips.stories.tsx @@ -6,6 +6,7 @@ import { STORY_TIME, editThenTestDocument, largeCompletedDocument, + subagentReport, } from "@opencode/session-ui/storybook" import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { createEffect, createMemo, on, onCleanup, onMount } from "solid-js" @@ -85,7 +86,7 @@ function Preview(props: PreviewArgs) { ) } -// Each stage lists the work still running; finished work stays in the timeline as completed calls. +// Each stage lists the work still running; finished subagents report back in the timeline. const stages = [ { started: 0, finished: 0, shells: 0, finishedShells: 0 }, { started: 1, finished: 0, shells: 0, finishedShells: 0 }, @@ -109,20 +110,17 @@ function liveDocument(stage: Stage): SessionDocument { type: "tool", id: `tool_${value.id}`, name: "subagent", - state: - index < stage.finished - ? { - status: "completed", - input: { agent: value.agent, description: value.description, prompt: value.description }, - content: [{ type: "text", text: "No issues found." }], - metadata: { sessionID: value.id, status: "completed" }, - } - : { - status: "running", - input: { agent: value.agent, description: value.description, prompt: value.description }, - metadata: { sessionID: value.id }, - }, - time: { created: STORY_TIME + 301_000 + index * 1_000, ran: STORY_TIME + 301_100 + index * 1_000 }, + state: { + status: "completed", + input: { agent: value.agent, description: value.description, prompt: value.description }, + content: [{ type: "text", text: "The subagent is working in the background." }], + metadata: { sessionID: value.id, status: "running" }, + }, + time: { + created: STORY_TIME + 301_000 + index * 1_000, + ran: STORY_TIME + 301_100 + index * 1_000, + completed: STORY_TIME + 301_200 + index * 1_000, + }, }), ), ...shells.slice(0, stage.shells).map( @@ -162,14 +160,30 @@ function liveDocument(stage: Stage): SessionDocument { text: "I'll delegate the audit to subagents and keep the dev server and tests running in the background.", }, ...tools, - ...(done - ? [{ type: "text" as const, text: "Both audits passed and the background commands have exited." }] - : []), ], - time: { created: STORY_TIME + 300_500, completed: done ? STORY_TIME + 310_000 : undefined }, + time: { created: STORY_TIME + 300_500, completed: stage.finished ? STORY_TIME + 306_000 : undefined }, }, + ...subagents.slice(0, stage.finished).map((value, index) => + subagentReport(`msg_report_${value.id}`, STORY_TIME + 307_000 + index * 1_000, { + childID: value.id, + agent: value.agent, + description: value.description, + state: "completed", + body: "No issues found.", + }), + ), ] + if (done) + messages.push({ + id: "msg_activity_summary", + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: [{ type: "text", text: "Both audits passed and the background commands have exited." }], + time: { created: STORY_TIME + 309_000, completed: STORY_TIME + 310_000 }, + }) + return { sessionID: CURRENT_SESSION_ID, messages, status: done ? { type: "idle" } : { type: "busy" }, diffs: [] } } @@ -206,7 +220,7 @@ function LiveActivity() { .slice(stage().finishedShells, stage().shells) .map((_, index) => shellItem(index + stage().finishedShells)), onOpen: (item) => { - // The app opens the shell's tool call, or the group holding it, and centers it in the timeline. + // The preview has no child route, so show the launch in its timeline. const part = document.querySelector( `[data-slot="story-timeline"] [data-timeline-part-ids*="tool_${item.target}"]`, ) diff --git a/packages/app/src/session/composer/activity-chips.tsx b/packages/app/src/session/composer/activity-chips.tsx index 28da74e09e5e..3c7442a22b43 100644 --- a/packages/app/src/session/composer/activity-chips.tsx +++ b/packages/app/src/session/composer/activity-chips.tsx @@ -16,14 +16,12 @@ import "./activity-chips.css" export type SessionActivityItem = { key: string - type: "subagent" | "shell" label?: string agent?: string - sessionID?: string target: string // When the work started running, from the server's record of it. started: number -} +} & ({ type: "subagent"; sessionID: string } | { type: "shell" }) type DurationKey = | "ui.message.duration.seconds" @@ -58,7 +56,7 @@ export function SessionActivityChips(props: { output: (input: ShellOutputInput) => Promise ended: Parameters[0]["ended"] } - onOpen: (item: SessionActivityItem) => void + onOpen: (item: Extract) => void onStop: (item: SessionActivityItem) => Promise // The menu closed with nothing left running, so the capsule and its trigger are gone; focus goes to the composer. onEmpty: () => void @@ -106,16 +104,12 @@ export function SessionActivityChips(props: { const alignment = useComposerLaneAlignment() - // A subagent can only be interrupted once its child session exists. - const stoppable = (item: SessionActivityItem) => item.type === "shell" || !!item.sessionID - const row = (item: SessionActivityItem) => ({ - "data-stoppable": stoppable(item) || undefined, // A shell opens its own panel in place; a subagent opens where it runs. closeOnSelect: item.type !== "shell", onSelect: () => (item.type === "shell" ? panel.open(item) : props.onOpen(item)), onKeyDown: (event: KeyboardEvent) => { - if ((event.key !== "Delete" && event.key !== "Backspace") || !stoppable(item)) return + if (event.key !== "Delete" && event.key !== "Backspace") return event.preventDefault() panel.stop(item) @@ -135,7 +129,7 @@ export function SessionActivityChips(props: { onCleanup(() => clearInterval(timer)) }) - // The run time and the stop button share the row's end; hovering a stoppable row swaps one for the other. + // The run time and the stop button share the row's end; hovering a row swaps one for the other. const end = (item: SessionActivityItem) => ( {formatElapsed(now() - item.started, language.t)} - {stop(item)} - - ) - - const stop = (item: SessionActivityItem) => ( - {/* The row selects on press, so the stop button keeps its pointer events to itself. */} - + ) const label = () => language.activitySummary(counts()) diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index d1432a66e1f9..e534adf59f2e 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -420,7 +420,6 @@ export function ActiveSessionComposerRegion(props: { screen: SessionScreen model: SessionComposerController suggestionBoundary: () => HTMLElement | undefined - onReveal: (target: string) => void }) { const location = useWorkspaceLocation() const data = useData() @@ -448,14 +447,16 @@ export function ActiveSessionComposerRegion(props: { }, ) - // Subagents count while their session runs, or while their blocking call waits for its child session. const subagents = createMemo(() => - props.model.region.state.background.subagents().map((task) => ({ - ...task, - agent: task.agent ?? (task.sessionID ? data.session.get(task.sessionID)?.agent : undefined), - key: task.id, - target: task.partID ?? task.id, - })), + props.model.region.state.background + .tasks() + .filter((task) => task.type === "subagent") + .map((task) => ({ + ...task, + agent: task.agent ?? data.session.get(task.sessionID)?.agent, + key: task.id, + target: task.id, + })), ) const shells = createMemo(() => @@ -479,24 +480,14 @@ export function ActiveSessionComposerRegion(props: { ?.flatMap((entry) => (entry.type === "document" && entry.info.experimental ? [entry.info.experimental] : [])) .at(-1)?.todo === true - const open = (item: SessionActivityItem) => { - const current = props.session.identity.params.id - - if (!current) return - - if (item.sessionID) return openRoute(current, item.sessionID) - - // A starting subagent call has no session yet, so it lives in this timeline. - props.onReveal(item.target) - } - const stop = (item: SessionActivityItem) => { - const request = item.sessionID - ? server.api.session.interrupt({ sessionID: item.sessionID }) - : server.api.shell.remove({ - id: item.target, - location: { directory: data.shell.get(item.target)?.location.directory ?? location().directory }, - }) + const request = + item.type === "subagent" + ? server.api.session.interrupt({ sessionID: item.sessionID }) + : server.api.shell.remove({ + id: item.target, + location: { directory: data.shell.get(item.target)?.location.directory ?? location().directory }, + }) return request.then( () => true, @@ -587,7 +578,11 @@ export function ActiveSessionComposerRegion(props: { subagents={subagents()} shells={shells()} shell={shell} - onOpen={open} + onOpen={(item) => { + const current = props.session.identity.params.id + + if (current) openRoute(current, item.sessionID) + }} onStop={stop} onEmpty={props.model.region.focusPrompt} /> diff --git a/packages/app/src/session/composer/shell-panel-machine.test.ts b/packages/app/src/session/composer/shell-panel-machine.test.ts index b0655206ae28..8aff80249fdb 100644 --- a/packages/app/src/session/composer/shell-panel-machine.test.ts +++ b/packages/app/src/session/composer/shell-panel-machine.test.ts @@ -69,13 +69,19 @@ test("a row's Stop sends once until it settles, and a stop that never settles gi ).toContainEqual(expect.objectContaining({ type: "stop.run", item: server })) }) -test("a subagent row stops only once its child session exists", () => { - const starting: SessionActivityItem = { key: "call_1", type: "subagent", target: "call_1", started: 1 } - const child: SessionActivityItem = { ...starting, key: "call_2", target: "call_2", sessionID: "ses_child" } - const running = work([], [starting, child]) +test("a subagent row can stop its child while it is listed", () => { + const child: SessionActivityItem = { + key: "ses_child", + type: "subagent", + target: "ses_child", + sessionID: "ses_child", + started: 1, + } + + const running = work([], [child]) const listed = replay([{ type: "menu.toggled", open: true, work: running }]).state - expect(transitionShellPanel(listed, { type: "stop.requested", item: starting, work: running }).state).toBe(listed) + expect(transitionShellPanel(listed, { type: "stop.requested", item: child, work: work([]) }).state).toBe(listed) expect(transitionShellPanel(listed, { type: "stop.requested", item: child, work: running }).effects).toContainEqual( expect.objectContaining({ type: "stop.run", item: child }), ) diff --git a/packages/app/src/session/composer/shell-panel-machine.ts b/packages/app/src/session/composer/shell-panel-machine.ts index 1c5595f426a1..cc39629fbec8 100644 --- a/packages/app/src/session/composer/shell-panel-machine.ts +++ b/packages/app/src/session/composer/shell-panel-machine.ts @@ -310,11 +310,10 @@ function running(work: ShellPanelWork, item: SessionActivityItem) { return work.shells.some((shell) => shell.key === item.key) } -// A subagent can only be interrupted once its child session exists. function stoppable(work: ShellPanelWork, item: SessionActivityItem) { if (item.type === "shell") return running(work, item) - return !!item.sessionID && work.subagents.some((subagent) => subagent.key === item.key) + return work.subagents.some((subagent) => subagent.key === item.key) } function count(work: ShellPanelWork) { diff --git a/packages/app/src/session/requests/background.ts b/packages/app/src/session/requests/background.ts index 1f3057814503..c5af37f9f747 100644 --- a/packages/app/src/session/requests/background.ts +++ b/packages/app/src/session/requests/background.ts @@ -9,20 +9,17 @@ import { Option, Schema } from "effect" import { createMemo } from "solid-js" // `started` is when the work began running: the latest call's run time, the child session's creation, or the shell's -// start. A subagent's `partID` names the call that still blocks the run. +// start. type Subagent = { id: string type: "subagent" - sessionID: string | undefined - partID: string | undefined - label: string | undefined + sessionID: string + label: string agent?: string started: number } -type Task = - | (Omit & { label: string }) - | { id: string; type: "shell"; label: string; started: number } +type Task = Subagent | { id: string; type: "shell"; label: string; started: number } const decodeString = Schema.decodeUnknownOption(Schema.String) @@ -62,18 +59,15 @@ export function createSessionBackground(input: { calls, blocking: assistant?.content.flatMap((part) => { - if (part.type !== "tool" || part.state.status !== "running") return [] - - if (part.name !== "shell" && part.name !== "subagent") return [] - const shell = part.name === "shell" + if (part.type !== "tool" || part.state.status !== "running" || part.name !== "shell") return [] return [ { - type: shell ? ("shell" as const) : ("subagent" as const), + type: "shell" as const, partID: part.id, - id: text(shell ? part.state.metadata.shellID : part.state.metadata.sessionID), - label: text(shell ? part.state.input.command : part.state.input.description), - agent: shell ? undefined : text(part.state.input.agent), + id: text(part.state.metadata.shellID), + label: text(part.state.input.command), + agent: undefined, started: part.time.ran ?? part.time.created, }, ] @@ -83,8 +77,8 @@ export function createSessionBackground(input: { const blocking = createMemo(() => history().blocking) - // Like the TUI, a subagent runs exactly while its session, or any session below it, is running. A blocking call - // stands in only until its child session is known. + // Like the TUI, a subagent runs exactly while its session, or any session below it, is running. Subagents always run + // in the background, so every running descendant is background work. const subagents = createMemo(() => { const id = input.sessionID() @@ -106,13 +100,8 @@ export function createSessionBackground(input: { return false } - // A call names its child once the child exists; until the call reports it, the child's title is its description. - const calls = current.blocking.flatMap((item) => (item.type === "subagent" ? [item] : [])) - - const child = (item: (typeof calls)[number], info: SessionInfo) => - item.id ? info.id === item.id : !!item.label && info.parentID === id && info.title === item.label - - const running = sessions.flatMap((info): Subagent[] => { + // The latest call for a child names it; its own session decides whether it still runs. + return sessions.flatMap((info): Subagent[] => { if (input.status(info.id) !== "running" || !descends(info.id)) return [] const latest = current.calls.get(info.id) @@ -121,36 +110,15 @@ export function createSessionBackground(input: { id: info.id, type: "subagent", sessionID: info.id, - partID: calls.find((item) => child(item, info))?.partID, label: latest?.label ?? info.title ?? info.id, agent: latest?.agent, started: latest?.started ?? info.time.created, }, ] }) - - const pending = calls.flatMap((item): Subagent[] => - sessions.some((info) => child(item, info)) - ? [] - : [ - { - id: item.id ?? item.partID, - type: "subagent", - sessionID: item.id, - partID: item.partID, - label: item.label, - agent: item.agent, - started: item.started, - }, - ], - ) - - // Work that blocks the run comes before work already in the background. - return [...pending, ...running.filter((task) => task.partID), ...running.filter((task) => !task.partID)] }) - // Background work: running subagents whose call no longer blocks the run, and the session's live shells outside - // its blocking calls. + // Background work: every running subagent, and the session's live shells outside its blocking calls. const tasks = createMemo((): Task[] => { const id = input.sessionID() @@ -170,11 +138,8 @@ export function createSessionBackground(input: { return [{ id: shell.id, type: "shell" as const, label: shell.command, started: shell.time.started }] }) - return [ - ...subagents().flatMap((task) => (task.partID ? [] : [{ ...task, label: task.label ?? task.id }])), - ...shells, - ] + return [...subagents(), ...shells] }) - return { blocking, subagents, tasks } + return { blocking, tasks } } diff --git a/packages/app/src/session/requests/model.ts b/packages/app/src/session/requests/model.ts index 5e8415038c3d..765ef4476f83 100644 --- a/packages/app/src/session/requests/model.ts +++ b/packages/app/src/session/requests/model.ts @@ -168,7 +168,6 @@ export function createSessionRequestModel() { // Moving to the background and the plugins' background list stay with the primary session's own work. const blocking = createMemo(() => (primary() ? running.blocking() : [])) - const subagents = createMemo(() => (primary() ? running.subagents() : [])) const tasks = createMemo(() => (primary() ? running.tasks() : [])) const moveToBackground = async () => { @@ -268,7 +267,6 @@ export function createSessionRequestModel() { permissionResponding, background: { blocking, - subagents, tasks, move: moveToBackground, steer, diff --git a/packages/app/src/session/requests/steer-background.ts b/packages/app/src/session/requests/steer-background.ts index 03b6690e2376..5914e887037a 100644 --- a/packages/app/src/session/requests/steer-background.ts +++ b/packages/app/src/session/requests/steer-background.ts @@ -1,5 +1,6 @@ /** - * A steer moves the run's blocking shells and subagents to the background, so the agent reads it at its next step. + * A steer moves the run's blocking shells to the background, so the agent reads it at its next step. Subagents always + * run in the background already, so a steer never moves them. * The move reads the blocking work once the steer is admitted, so work that started during admission moves too. * Nothing is claimed: the server moves each job once and ignores repeated moves, so overlapping steers, a failed * move, or one that ran before a job started never leave work for a later steer to skip. diff --git a/packages/app/src/session/screen.tsx b/packages/app/src/session/screen.tsx index 34c609512de1..814ed52302fc 100644 --- a/packages/app/src/session/screen.tsx +++ b/packages/app/src/session/screen.tsx @@ -313,7 +313,6 @@ function SessionScreenContent(props: { setVisibleRef={timeline.view.setVisibleRef} anchor={timeline.view.anchor} setRevealMessage={timeline.view.setRevealMessage} - setRevealPart={timeline.view.setRevealPart} reveal={timeline.view.reveal} setScrollToEnd={timeline.view.setScrollToEnd} setPage={timeline.view.setPage} @@ -439,7 +438,6 @@ function SessionScreenContent(props: { screen={props.screen} model={model} suggestionBoundary={timeline.visible} - onReveal={timeline.actions.revealPart} /> )} diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts index 92e80d2645db..f236a1ead25e 100644 --- a/packages/app/src/session/timeline/interaction.ts +++ b/packages/app/src/session/timeline/interaction.ts @@ -68,8 +68,6 @@ export function createSessionTimelineInteraction(session: SessionModel, visible: // The active timeline's navigation, registered by its virtualizer. let revealMessage = (_id: string, _partID?: string) => {} - let revealPart = (_target: string) => false - let scrollToEnd = (_behavior?: ScrollBehavior) => {} let page = (_direction: 1 | -1) => {} @@ -425,11 +423,6 @@ export function createSessionTimelineInteraction(session: SessionModel, visible: cursor.dispatch(SCROLL_MOVED_EVENT) revealMessage(id, partID) }, - revealPart: (target: string) => { - cursor.dispatch(SCROLL_MOVED_EVENT) - - return revealPart(target) - }, resume, setActiveMessage, }, @@ -460,9 +453,6 @@ export function createSessionTimelineInteraction(session: SessionModel, visible: setRevealMessage: (reveal: (id: string, partID?: string) => void) => { revealMessage = reveal }, - setRevealPart: (reveal: (target: string) => boolean) => { - revealPart = reveal - }, // The tool call the route opened the session on, attempted once per history entry. reveal: { pending: () => routeRevealTarget(untrack(revealState)), diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index d7b72eddfda7..8f498fe8ea6a 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -41,7 +41,7 @@ import { SessionHeaderSpacer } from "@/session/header/session-header" import { SessionHeaderGap } from "@/session/header/drag-area" import { SessionWorkingIndicator } from "@/session/header/session-working-indicator" -type BlockingTask = { type: "shell" | "subagent"; partID: string; id?: string; label?: string; started: number } +type BlockingTask = { type: "shell"; partID: string; id?: string; label?: string; started: number } type SessionBackground = { blocking: Accessor @@ -95,7 +95,6 @@ type MessageTimelineProps = { setVisibleRef?: (el: HTMLDivElement | undefined) => void anchor: (id: string) => string setRevealMessage?: (fn: (id: string, partID?: string) => void) => void - setRevealPart?: (fn: (target: string) => boolean) => void setScrollToEnd?: (fn: (behavior?: ScrollBehavior) => void) => void setPage?: (fn: (direction: 1 | -1) => void) => void reveal?: TimelineRouteReveal @@ -264,7 +263,6 @@ function MessageTimelineView( ) }, setRevealMessage: props.setRevealMessage, - setRevealPart: props.setRevealPart, setScrollToEnd: props.setScrollToEnd, setPage: props.setPage, reveal: props.reveal, @@ -351,7 +349,7 @@ function MessageTimelineView( .findLast((ref) => blocking.has(ref.partID))?.partID }) - // The New timeline's button to move work to the background waits until the shell or subagent has run for a moment, + // The New timeline's button to move work to the background waits until the shell has run for a moment, // so a quick command does not flash it. The wait counts from when the call started, so a call already running when // the timeline opens shows it at once. const [settledBlockingPartID, setSettledBlockingPartID] = createSignal() @@ -444,7 +442,7 @@ function MessageTimelineView( if (content.state.status === "streaming" || content.state.status === "running") return true const taskID = content.state.metadata?.[content.name === "subagent" ? "sessionID" : "shellID"] - return background.has(content.id) || (Predicate.isString(taskID) && background.has(taskID)) + return Predicate.isString(taskID) && background.has(taskID) }) }) }) diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx index 949406f7041d..50b824dad105 100644 --- a/packages/app/src/session/timeline/virtualizer.tsx +++ b/packages/app/src/session/timeline/virtualizer.tsx @@ -122,7 +122,6 @@ type Input = { disclosure: Readonly>, ) => boolean setRevealMessage?: (fn: (id: string, partID?: string) => void) => void - setRevealPart?: (fn: (target: string) => boolean) => void setScrollToEnd?: (fn: (behavior?: ScrollBehavior) => void) => void /** Pages the timeline for keys pressed outside it, such as PageUp in the composer. */ setPage?: (fn: (direction: 1 | -1) => void) => void @@ -644,7 +643,6 @@ export function createTimelineVirtualizer(input: Input) { reportOffset?.(root.scrollTop, false) dispatchCold(CHECK_REQUESTED) }) - input.setRevealPart?.(revealPart) input.setRevealMessage?.((id, partID) => { if (!active()) return @@ -1242,7 +1240,6 @@ export function createTimelineVirtualizer(input: Input) { if (active()) { input.setScrollRef(undefined) input.setRevealMessage?.(() => {}) - input.setRevealPart?.(() => false) input.setScrollToEnd?.(() => {}) input.setPage?.(() => {}) } diff --git a/packages/app/src/shell/commands/dialog.tsx b/packages/app/src/shell/commands/dialog.tsx index 743035bfc204..6c0e40890b9d 100644 --- a/packages/app/src/shell/commands/dialog.tsx +++ b/packages/app/src/shell/commands/dialog.tsx @@ -1,5 +1,6 @@ import { getDirectory, getFilename } from "@opencode/util/path" import { FileIcon } from "@opencode/ui/file-icon" +import { Button } from "@opencode/ui/button" import { Dialog, DialogBody } from "@opencode/ui/dialog" import { Keybind } from "@opencode/ui/keybind" import { Tooltip } from "@opencode/ui/tooltip" @@ -69,6 +70,7 @@ export function CommandPaletteView(props: { close: () => void /** The row whose selection is still in progress, such as an archived session being restored. */ busyEntryID?: string + unhide?: (entry: CommandPaletteEntry) => (() => void) | undefined }) { const language = useLanguage() const tabs = useTabs() @@ -110,15 +112,30 @@ export function CommandPaletteView(props: { onSelect={props.select} onClose={props.close} > - {(item, row) => ( - - )} + {(item, row) => { + const entry = () => ( + + ) + + return ( + + {(unhide) => ( +
+ {entry()} + +
+ )} +
+ ) + }} diff --git a/packages/app/src/shell/commands/session-search.tsx b/packages/app/src/shell/commands/session-search.tsx index b3e68f69433d..f0b142bd31d1 100644 --- a/packages/app/src/shell/commands/session-search.tsx +++ b/packages/app/src/shell/commands/session-search.tsx @@ -160,6 +160,17 @@ export function DialogSessionSearch(props: { archived?: boolean }) { select={select} close={() => dialog.close(layer?.id)} busyEntryID={selectSessionRestoreEntryID(searchState())} + unhide={(entry) => { + const server = entry.server + const id = entry.sessionID + + if (!server || !id || !global.sessionPreferences.hidden(server, id)) return + + return () => { + global.sessionPreferences.update("hidden", server, id, false) + dialog.close(layer?.id) + } + }} /> ) } diff --git a/packages/app/src/shell/notifications/notification.tsx b/packages/app/src/shell/notifications/notification.tsx index c9c703818bb1..9ac59c8205e4 100644 --- a/packages/app/src/shell/notifications/notification.tsx +++ b/packages/app/src/shell/notifications/notification.tsx @@ -79,6 +79,8 @@ export function createServerNotificationState(input: { data: Data key: ServerConnection.Key coordinator: ReturnType + muted: (sessionID: string) => boolean + preferencesLoaded?: Promise }) { const platform = usePlatform() const settings = useSettings() @@ -294,6 +296,7 @@ export function createServerNotificationState(input: { // Loading the session keeps a background completion visible in the server-derived unread state. const lookup = async (sessionID: string) => { + if (input.preferencesLoaded) await input.preferencesLoaded const session = input.data.session.get(sessionID) if (session) return session @@ -309,7 +312,7 @@ export function createServerNotificationState(input: { if (hasRunningChild(input.data, sessionID)) return void lookup(sessionID).then((session) => { - if (disposed.value) return + if (disposed.value || input.muted(sessionID)) return if (!session) return @@ -333,7 +336,7 @@ export function createServerNotificationState(input: { const handleSessionError = (sessionID: string, eventID: string) => { void lookup(sessionID).then((session) => { - if (disposed.value) return + if (disposed.value || input.muted(sessionID)) return if (session?.parentID) return @@ -369,7 +372,7 @@ export function createServerNotificationState(input: { const category = kind === "question" || kind === "mcp-elicitation" ? "questions" : "permissions" const pending = () => { - if (disposed.value) return false + if (disposed.value || input.muted(sessionID) || input.muted(input.data.session.root(sessionID))) return false if (kind !== "permission") return input.data.session.form.list(sessionID)?.some((form) => form.id === requestID) diff --git a/packages/app/src/shell/state/session-preferences.ts b/packages/app/src/shell/state/session-preferences.ts new file mode 100644 index 000000000000..19cad471bcb5 --- /dev/null +++ b/packages/app/src/shell/state/session-preferences.ts @@ -0,0 +1,62 @@ +import { Schema } from "effect" +import { createMemo } from "solid-js" +import { Persistence } from "@/runtime/persistence/schema" +import { Persist, persisted } from "@/runtime/persistence/storage" +import { useServers } from "@/runtime/server/registry" +import { + recentSessionEndpoints, + recentSessionKey, + removePin, + splitRecentSessionKey, +} from "@/shell/titlebar/recent-sessions-model" + +const Preferences = Persistence.struct({ + hidden: Persistence.array(Schema.String), + muted: Persistence.array(Schema.String), +}) + +export function createSessionPreferences() { + const servers = useServers() + const endpoints = createMemo(() => recentSessionEndpoints(servers.list, servers.ownUrl())) + + const [state, set, , ready] = persisted({ ...Persist.global("session.preferences"), sync: true }, Preferences, { + hidden: [], + muted: [], + }) + + const key = (server: string, id: string) => recentSessionKey(endpoints().get(server) ?? server, id) + + const identities = (stored: readonly string[]) => + new Set(stored.map((value) => { + const session = splitRecentSessionKey(value) + + return session ? key(session.server, session.sessionID) : value + })) + + const keys = { + hidden: createMemo(() => identities(state.hidden)), + muted: createMemo(() => identities(state.muted)), + } + + const update = (kind: keyof typeof keys, server: string, id: string, enabled: boolean) => { + const apply = () => { + if (keys[kind]().has(key(server, id)) === enabled) return + const value = recentSessionKey(server, id) + set(kind, (current) => (enabled ? [...current, value] : removePin(current, value, endpoints()))) + } + + if (ready()) return apply() + void ready.promise?.then(apply) + } + + return { + ready, + hidden: (server: string, id: string) => keys.hidden().has(key(server, id)), + muted: (server: string, id: string) => keys.muted().has(key(server, id)), + update, + forget(server: string, id: string) { + update("hidden", server, id, false) + update("muted", server, id, false) + }, + } +} diff --git a/packages/app/src/shell/titlebar/recent-sessions-model.test.ts b/packages/app/src/shell/titlebar/recent-sessions-model.test.ts index 6ce261aaaf0d..9fc8e5fcc09c 100644 --- a/packages/app/src/shell/titlebar/recent-sessions-model.test.ts +++ b/packages/app/src/shell/titlebar/recent-sessions-model.test.ts @@ -13,6 +13,7 @@ import { partitionRecentSessions, recentSessionEndpoints, recentSessionKey, + recentRowUnread, removePin, reorderPins, sortRecentSessions, @@ -39,6 +40,33 @@ const item = (server: string, value: SessionInfo): RecentSession => ({ session: value, }) +test("hiding filters hydrated pins and recent rows only on their server", () => { + const pin = item("local", session("pinned", 1)) + const recent = item("local", session("recent", 2)) + const remote = item("remote", recent.session) + + const input = { + items: [recent, remote], + pins: [pin.key], + endpoints: new Map(), + open: new Set(), + archived: () => false, + resolvePin: () => pin, + } + + expect(partitionRecentSessions({ ...input, hidden: (server) => server === "local" })).toEqual({ + pinned: [], + recent: [remote], + }) + expect(partitionRecentSessions(input).pinned).toEqual([pin]) +}) + +test("muting hides the unread dot until unmuted", () => { + expect(recentRowUnread(true, false, true)).toBe(false) + expect(recentRowUnread(true, false, false)).toBe(true) + expect(recentRowUnread(true, true, false)).toBe(false) +}) + test("pin keys round trip server keys that contain the separator's neighbours", () => { const key = recentSessionKey("http://server.example:4096", "ses_1") diff --git a/packages/app/src/shell/titlebar/recent-sessions-model.ts b/packages/app/src/shell/titlebar/recent-sessions-model.ts index f5b0f4522372..a3e23742c208 100644 --- a/packages/app/src/shell/titlebar/recent-sessions-model.ts +++ b/packages/app/src/shell/titlebar/recent-sessions-model.ts @@ -353,6 +353,7 @@ export function mergeRecentSessions( * one that is not loaded yet resolves through `resolvePin`. */ export function partitionRecentSessions(input: { + hidden?: (server: string, id: string) => boolean items: readonly RecentSession[] pins: readonly string[] endpoints: ReadonlyMap @@ -373,6 +374,8 @@ export function partitionRecentSessions(input: { if (!item || item.session.time.archived !== undefined) return [] + if (input.hidden?.(item.server, item.session.id)) return [] + const id = identity(item) if (pinnedSessions.has(id)) return [] @@ -386,6 +389,7 @@ export function partitionRecentSessions(input: { // Opening a row should reuse an existing tab. Otherwise prefer a stable route regardless of fetch order. for (const item of input.items) { + if (input.hidden?.(item.server, item.session.id)) continue const id = identity(item) if (pinnedKeys.has(item.key) || pinnedSessions.has(id)) continue @@ -405,3 +409,7 @@ export function partitionRecentSessions(input: { return { pinned, recent: sortRecentSessions([...recent.values()]) } } + +export function recentRowUnread(unread: boolean, loading: boolean, muted: boolean) { + return unread && !loading && !muted +} diff --git a/packages/app/src/shell/titlebar/recent-sessions.tsx b/packages/app/src/shell/titlebar/recent-sessions.tsx index 21dfb9e0658c..82301499aaac 100644 --- a/packages/app/src/shell/titlebar/recent-sessions.tsx +++ b/packages/app/src/shell/titlebar/recent-sessions.tsx @@ -37,6 +37,7 @@ import { recentPageFailed, recentPageHasMore, recentPageLoaded, + recentRowUnread, recentSessionEndpoints, recentSessionKey, removePin, @@ -178,6 +179,7 @@ export function RecentSessions() { batch(() => { item.ctx.data.session.forget(sessionID) forget(item.server, sessionID) + global.sessionPreferences.forget(item.server, sessionID) setHydration(produce((cache) => void delete cache[key])) removePinKey(key) }) @@ -485,6 +487,7 @@ export function RecentSessions() { open: openSessions(), resolvePin: (key) => hydratedItems().get(key), archived, + hidden: global.sessionPreferences.hidden, }), ) @@ -638,6 +641,7 @@ export function RecentSessions() { removePinKey(item.key) forget(item.server, current.id) + global.sessionPreferences.forget(item.server, current.id) }) void startTransition(() => { tabs.select(tabs.addSessionTab({ server: ServerConnection.Key.make(item.server), sessionId: current.id })) @@ -723,6 +727,7 @@ export function RecentSessions() { .then(() => { forget(item.server, item.session.id) removePinKey(item.key) + ids.forEach((id) => global.sessionPreferences.forget(item.server, id)) notifySessionTabsRemoved({ server: ServerConnection.Key.make(item.server), directory: item.session.location.directory, @@ -931,7 +936,8 @@ function RecentSessionTab(props: RecentSessionTabProps & { dragging?: boolean }) ) // A busy session shows its progress indicator instead of the unread dot. - const unread = createMemo(() => status.unread() && !status.loading()) + const muted = () => global.sessionPreferences.muted(server(), item().session.id) + const unread = createMemo(() => recentRowUnread(status.unread(), status.loading(), muted())) createEffect(() => props.onUnreadChange(unread())) @@ -962,6 +968,12 @@ function RecentSessionTab(props: RecentSessionTabProps & { dragging?: boolean }) {language.t("sidebar.recent.moveDown")} + global.sessionPreferences.update("muted", server(), item().session.id, !muted())}> + {language.t(muted() ? "sidebar.recent.unmute" : "sidebar.recent.mute")} + + global.sessionPreferences.update("hidden", server(), item().session.id, true)}> + {language.t("sidebar.recent.hide")} + {language.t("common.rename")} {language.t("common.archive")} @@ -977,6 +989,7 @@ function RecentSessionTab(props: RecentSessionTabProps & { dragging?: boolean }) server={server()} session={item().session} preparing={false} + label={muted() ? language.t("sidebar.recent.muted") : undefined} unread={unread()} attention={status.attention()} loading={status.loading()} diff --git a/packages/app/src/voice/tools.ts b/packages/app/src/voice/tools.ts index f7eaa4a37f09..dde30e6b5b89 100644 --- a/packages/app/src/voice/tools.ts +++ b/packages/app/src/voice/tools.ts @@ -195,7 +195,7 @@ export class VoiceTools { const explained = this.explained.get(sessionID) const full = explained === undefined || Date.now() - explained > headerLapse - // Like a typed steer, move blocking shells and subagents to the background so the agent reads it next. Tried + // Like a typed steer, move blocking shells to the background so the agent reads it next. Tried // once and briefly: the steer goes either way, and an idle session makes it a no-op. if (delivery === "steer") await api.session diff --git a/packages/app/test-browser/server-notification-state.test.ts b/packages/app/test-browser/server-notification-state.test.ts index 31ffef10c9ac..fb74b1c1e863 100644 --- a/packages/app/test-browser/server-notification-state.test.ts +++ b/packages/app/test-browser/server-notification-state.test.ts @@ -49,9 +49,9 @@ const preferences = { } // Each test fakes only the parts of the SDK, data store and coordinator that the notification state reads. -const createState = (input: { sdk: object; data: object; coordinator: object }) => +const createState = (input: { sdk: object; data: object; coordinator: object; muted?: (id: string) => boolean }) => // SAFETY: the fakes cover every member the notification state reaches in that test. - createServerNotificationState({ key: server, ...input } as never) + createServerNotificationState({ key: server, muted: () => false, ...input } as never) beforeAll(async () => { // Fakes replace only the hooks this test controls. Spreading the real module keeps every other export, such as @@ -142,6 +142,7 @@ test.each( "resolved", "auto approve", "root tab", + "muted root", "no tab", "disposed", ].map((scenario) => ({ ...request, scenario })), @@ -170,6 +171,7 @@ test.each( const dispose = createRoot((dispose) => { createState({ + muted: (id) => options.scenario === "muted root" && id === "root", sdk: { scope: ServerScope.local, connection: { status: () => "connected" }, @@ -237,7 +239,7 @@ test.each( await Promise.all(deliveries.map((run) => run())) const suppressed = - ["resolved", "disposed", "no tab"].includes(options.scenario) || + ["resolved", "disposed", "no tab", "muted root"].includes(options.scenario) || (options.scenario === "auto approve" && options.kind === "permission") expect(alerts).toEqual(!suppressed && options.scenario !== "notifications disabled" ? [options.title] : []) diff --git a/packages/app/test-browser/session-background.test.ts b/packages/app/test-browser/session-background.test.ts index be520f8d900f..1c0289c909c0 100644 --- a/packages/app/test-browser/session-background.test.ts +++ b/packages/app/test-browser/session-background.test.ts @@ -93,7 +93,6 @@ describe("createSessionBackground", () => { expect(background.tasks().map((task) => task.id)).toEqual(["stuck", "noticed"]) setStore("status", { stuck: "idle", noticed: "idle" }) expect(background.tasks()).toEqual([]) - expect(background.subagents()).toEqual([]) dispose() }) }) @@ -103,21 +102,17 @@ describe("createSessionBackground", () => { const background = createSessionBackground({ sessionID: () => "root", messages: () => [], - sessions: () => [ - session("child"), - session("grandchild", "child"), - session("other-child", "other"), - ], + sessions: () => [session("child"), session("grandchild", "child"), session("other-child", "other")], status: () => "running", shells: () => [], }) - expect(background.subagents().map((task) => task.id)).toEqual(["child", "grandchild"]) + expect(background.tasks().map((task) => task.id)).toEqual(["child", "grandchild"]) dispose() }) }) - test("shows a blocking call until its child session is known, then follows the child's status", () => { + test("ignores a legacy blocking subagent call and counts its running child", () => { createRoot((dispose) => { const [store, setStore] = createStore<{ messages: ReturnType[] @@ -126,10 +121,14 @@ describe("createSessionBackground", () => { }>({ messages: [ assistant("current", [ - tool("call", "subagent", {}, { description: "Inspect", agent: "explore" }, "running", { - created: 5, - ran: 6, - }), + tool( + "call", + "subagent", + { status: "running", sessionID: "child" }, + { description: "Inspect", agent: "explore" }, + "running", + { created: 5, ran: 6 }, + ), ]), ], sessions: [], @@ -144,27 +143,24 @@ describe("createSessionBackground", () => { shells: () => [], }) - const pending = { - id: "call", + // Subagents always run in the background, so a leftover running call blocks nothing. + expect(background.blocking()).toEqual([]) + expect(background.tasks()).toEqual([]) + + setStore("sessions", [session("child")]) + expect(background.tasks()).toEqual([]) + setStore("status", "child", "running") + + const task = { + id: "child", type: "subagent", - sessionID: undefined, - partID: "call", + sessionID: "child", label: "Inspect", agent: "explore", started: 6, } - expect(background.subagents()).toEqual([pending]) - setStore("messages", 0, "content", 0, "state", "metadata", { sessionID: "child" }) - expect(background.subagents()).toEqual([{ ...pending, id: "child", sessionID: "child" }]) - setStore("sessions", [session("child")]) - expect(background.subagents()).toEqual([]) - setStore("status", "child", "running") - expect(background.subagents()).toEqual([{ ...pending, id: "child", sessionID: "child" }]) - // Blocking work is not background work. - expect(background.tasks()).toEqual([]) - setStore("messages", 0, "time", "completed", 7) - expect(background.blocking()).toEqual([]) - expect(background.tasks()).toEqual([{ ...pending, id: "child", sessionID: "child", partID: undefined }]) + + expect(background.tasks()).toEqual([task]) dispose() }) }) @@ -212,11 +208,10 @@ describe("createSessionBackground", () => { id: "live-child", type: "subagent", sessionID: "live-child", - partID: undefined, label: "live-child", started: 40, }, - { id: "child", type: "subagent", sessionID: "child", partID: undefined, label: "renamed", started: 0 }, + { id: "child", type: "subagent", sessionID: "child", label: "renamed", started: 0 }, { id: "shell", type: "shell", label: "updated command", started: 0 }, ]) expect(background.blocking()).toBe(blocking) diff --git a/packages/cli/package.json b/packages/cli/package.json index 25b69405d63f..c4ab68a394d2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -32,7 +32,7 @@ "@effect/platform-node": "catalog:", "@opencode/client": "workspace:*", "@opencode/plugin": "workspace:*", - "@opencode/pty": "0.5.0", + "@opencode/pty": "0.5.2", "@opencode/schema": "workspace:*", "@opencode/server": "workspace:*", "@opencode/tui": "workspace:*", diff --git a/packages/cli/src/acp/translate.ts b/packages/cli/src/acp/translate.ts index c6960b4cc296..f85be8cc561b 100644 --- a/packages/cli/src/acp/translate.ts +++ b/packages/cli/src/acp/translate.ts @@ -25,7 +25,7 @@ export type Terminal = "succeeded" | "failed" | "interrupted" export type TurnContext = { readonly sessionID: Session.ID readonly cwd: string - readonly start: TurnStart + readonly start?: TurnStart readonly childUpdates: boolean readonly compaction: boolean } @@ -44,12 +44,14 @@ type RetryStatus = { readonly error: SessionError.Error } +type Child = ACPChild.Session & { readonly turnID?: string } + export type TurnState = { readonly started: boolean readonly tools: ReadonlyMap readonly retries: ReadonlyMap readonly compactions: ACPCompaction.Tracked - readonly children: ReadonlyMap + readonly children: ReadonlyMap readonly openChildren: ReadonlySet readonly asks: ReadonlySet readonly finish?: SessionMessage.Assistant["finish"] @@ -69,9 +71,9 @@ export type Output = readonly _tag: "PermissionAsk" readonly event: PermissionEvent readonly tool?: Tool - readonly child?: ACPChild.Session + readonly child?: Child } - | { readonly _tag: "FormAsk"; readonly form: FormEvent["data"]["form"]; readonly child?: ACPChild.Session } + | { readonly _tag: "FormAsk"; readonly form: FormEvent["data"]["form"]; readonly child?: Child } | { readonly _tag: "AskSettled"; readonly id: string } export type Folded = { @@ -95,20 +97,21 @@ export function fold(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): const sessionID = sessionIDFromEvent(event) const child = sessionID ? state.children.get(sessionID) : undefined + const openChild = child && state.openChildren.has(child.id) ? child : undefined - if (event.type === "permission.asked" && (event.data.sessionID === ctx.sessionID || child)) { + if (event.type === "permission.asked" && (event.data.sessionID === ctx.sessionID || openChild)) { const tool = event.data.source?.id ? state.tools.get(toolKey(event.data.sessionID, event.data.source.id)) : undefined return { state: { ...state, asks: new Set(state.asks).add(event.data.id) }, - outputs: [{ _tag: "PermissionAsk", event, tool, child }], + outputs: [{ _tag: "PermissionAsk", event, tool, child: openChild }], } } - if (event.type === "form.created" && (event.data.form.sessionID === ctx.sessionID || child)) { + if (event.type === "form.created" && (event.data.form.sessionID === ctx.sessionID || openChild)) { return { state: { ...state, asks: new Set(state.asks).add(event.data.form.id) }, - outputs: [{ _tag: "FormAsk", form: event.data.form, child }], + outputs: [{ _tag: "FormAsk", form: event.data.form, child: openChild }], } } const settledID = @@ -123,15 +126,18 @@ export function fold(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): return { state: { ...state, asks }, outputs: [{ _tag: "AskSettled", id: settledID }] } } if (!sessionID || (sessionID !== ctx.sessionID && !child)) return { state, outputs: [] } - if (event.type === "session.inbox.delivered" && event.data.inboxID === ctx.start.id) + if ( + sessionID === ctx.sessionID && + event.type === "session.inbox.delivered" && + (!ctx.start || event.data.inboxID === ctx.start.id) + ) return { state: { ...state, started: true }, outputs: [] } - if (!state.started) return { state, outputs: [] } + if (!child && !state.started) return { state, outputs: [] } return child ? childEvent(state, event, ctx, child) : rootEvent(state, event, ctx) } -export function fromTrackedChild(state: TurnState, event: OpenCodeEvent) { - const sessionID = event.type === "session.created" ? event.data.parentID : sessionIDFromEvent(event) - return sessionID !== undefined && state.children.has(sessionID) +export function projectChild(ctx: TurnContext, child: Child) { + return !ctx.childUpdates && ctx.start !== undefined && child.turnID === ctx.start.id } export function failure(state: TurnState) { @@ -202,7 +208,13 @@ function childCreated(state: TurnState, event: CreatedEvent, ctx: TurnContext): if (!parentID) return { state, outputs: [] } const parent = parentID === ctx.sessionID ? undefined : state.children.get(parentID) if (!parent && parentID !== ctx.sessionID) return { state, outputs: [] } - const child = { id: event.data.sessionID, parentID, depth: parent ? parent.depth + 1 : 1, title: event.data.title } + const child: Child = { + id: event.data.sessionID, + parentID, + depth: parent ? parent.depth + 1 : 1, + title: event.data.title, + turnID: parent ? parent.turnID : ctx.start?.id, + } return { state: { ...state, @@ -224,20 +236,27 @@ function rootEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): Fo return { state: { ...recorded, stepError: event.data.error }, outputs: [] } } case "session.execution.succeeded": - return { state, outputs: [], terminal: "succeeded" } + return { state: { ...state, started: Boolean(ctx.start) }, outputs: [], terminal: "succeeded" } case "session.execution.interrupted": - return { state, outputs: [], terminal: "interrupted" } + return { state: { ...state, started: Boolean(ctx.start) }, outputs: [], terminal: "interrupted" } case "session.execution.failed": - return { state: { ...state, executionError: event.data.error }, outputs: [], terminal: "failed" } + return { + state: { ...state, started: Boolean(ctx.start), executionError: event.data.error }, + outputs: [], + terminal: "failed", + } default: return sessionEvent(state, event, ctx, undefined) } } -function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, child: ACPChild.Session): Folded { +function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, child: Child): Folded { switch (event.type) { case "session.execution.started": - return { state, outputs: childStatus(ctx, child, { type: "status", status: "running" }) } + return { + state: { ...state, openChildren: new Set(state.openChildren).add(child.id) }, + outputs: childStatus(ctx, child, { type: "status", status: "running" }), + } case "session.execution.succeeded": return childEnded(state, ctx, child, { type: "status", status: "completed" }) case "session.execution.interrupted": @@ -249,12 +268,7 @@ function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, ch } } -function sessionEvent( - state: TurnState, - event: OpenCodeEvent, - ctx: TurnContext, - child: ACPChild.Session | undefined, -): Folded { +function sessionEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, child: Child | undefined): Folded { const sessionID = child?.id ?? ctx.sessionID const send = (update: SessionUpdate) => route(ctx, child, update) switch (event.type) { @@ -415,11 +429,11 @@ function newTool(sessionID: string, id: string, name = "tool"): Tool { return { sessionID, id, name, input: {}, metadata: {} } } -function route(ctx: TurnContext, child: ACPChild.Session | undefined, update: SessionUpdate): Output[] { +function route(ctx: TurnContext, child: Child | undefined, update: SessionUpdate): Output[] { if (!child) return [{ _tag: "SessionUpdate", update }] const projected = ACPChild.project(update, child) if (ctx.childUpdates) return childStatus(ctx, child, { type: "update", update: projected }) - return [{ _tag: "SessionUpdate", update: projected }] + return projectChild(ctx, child) ? [{ _tag: "SessionUpdate", update: projected }] : [] } function childStatus(ctx: TurnContext, child: ACPChild.Session, event: ACPChild.Event): Output[] { diff --git a/packages/cli/src/acp/turn.ts b/packages/cli/src/acp/turn.ts index f43d82eb2264..7e5637b584a4 100644 --- a/packages/cli/src/acp/turn.ts +++ b/packages/cli/src/acp/turn.ts @@ -21,7 +21,7 @@ import { findModel, type ACPCatalog } from "./catalog" import { ACPChild } from "./child" import { ACPClient } from "./client" import { currentModel } from "./config-option" -import type { ACPConnection } from "./connection" +import { ACPConnection } from "./connection" import { ACPElicitation } from "./elicitation" import { ACPError } from "./error" import { ACPPermission } from "./permission" @@ -60,7 +60,11 @@ type Turn = { readonly state: Ref.Ref readonly subscription: Subscription readonly cancelled: Deferred.Deferred - readonly background: boolean +} + +type Background = { + readonly state: Ref.Ref + readonly fiber?: Fiber.Fiber } export const make = Effect.fnUntraced(function* (input: { @@ -73,8 +77,24 @@ export const make = Effect.fnUntraced(function* (input: { const scope = yield* Effect.scope const drainTimeout = yield* CancelDrainTimeout const turns = yield* FiberMap.make() + const backgrounds = new WeakMap() - const open = Effect.fnUntraced(function* (ctx: ACPTranslate.TurnContext, state: Ref.Ref) { + const open = Effect.fnUntraced(function* ( + attached: Attached, + ctx: ACPTranslate.TurnContext, + state: Ref.Ref, + ) { + const previous = backgrounds.get(attached) + if (previous) { + backgrounds.delete(attached) + if (previous.fiber) yield* Fiber.interrupt(previous.fiber) + const inherited = yield* Ref.get(previous.state) + yield* Ref.set(state, { + ...ACPTranslate.initial, + children: inherited.children, + openChildren: inherited.openChildren, + }) + } // Parented to the service scope; the session scope may already be closed. const subscriptionScope = yield* Scope.fork(scope) const subscription: Subscription = { @@ -93,7 +113,7 @@ export const make = Effect.fnUntraced(function* (input: { Effect.forever, Effect.forkIn(subscriptionScope), ) - return { ctx, state, subscription, cancelled: yield* Deferred.make(), background: false } satisfies Turn + return { ctx, state, subscription, cancelled: yield* Deferred.make() } satisfies Turn }) const take = (subscription: Subscription) => @@ -141,7 +161,6 @@ export const make = Effect.fnUntraced(function* (input: { const interpret = (turn: Turn, output: ACPTranslate.Output) => { switch (output._tag) { case "SessionUpdate": - if (turn.background) return Effect.void return ACPPermission.withCompletedDiffs(output.update, output.diff, turn.ctx.cwd).pipe( Effect.flatMap((update) => input.connection.sessionUpdate({ sessionId: turn.ctx.sessionID, update })), ) @@ -185,7 +204,7 @@ export const make = Effect.fnUntraced(function* (input: { requestedSchema, clientSessionID: turn.ctx.sessionID, child: output.child, - toolCallSent: !turn.background && (!output.child || !turn.ctx.childUpdates), + toolCallSent: !output.child || ACPTranslate.projectChild(turn.ctx, output.child), } yield* queueAsk(turn, output.form.id, ACPElicitation.ask(elicitation), "cancel", (outcome) => ACPElicitation.respond(elicitation, outcome), @@ -203,10 +222,7 @@ export const make = Effect.fnUntraced(function* (input: { const advance = Effect.fnUntraced(function* (turn: Turn) { const event = yield* take(turn.subscription) const folded = yield* Ref.modify(turn.state, (current) => { - const next = - turn.background && !ACPTranslate.fromTrackedChild(current, event) - ? { state: current, outputs: [] } - : ACPTranslate.fold(current, event, turn.ctx) + const next = ACPTranslate.fold(current, event, turn.ctx) return [next, next.state] }) yield* Effect.forEach(folded.outputs, (output) => interpret(turn, output), { discard: true }) @@ -226,7 +242,7 @@ export const make = Effect.fnUntraced(function* (input: { const followChildren = Effect.fnUntraced(function* (turn: Turn) { while (true) { const folded = yield* advance(turn) - if (folded.state.openChildren.size === 0) return yield* asksSettled(turn.subscription) + if (folded.terminal && folded.state.openChildren.size === 0) return yield* asksSettled(turn.subscription) } }) @@ -312,13 +328,22 @@ export const make = Effect.fnUntraced(function* (input: { const close = Scope.close(turn.subscription.scope, Exit.void) if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* close const state = yield* Ref.get(turn.state) - if (state.openChildren.size === 0) return yield* close - // Children outlive a cancelled turn, so their asks still reach the client. - const background = followChildren({ - ...turn, - state: yield* Ref.make(state), - cancelled: yield* Deferred.make(), - background: true, + if (state.openChildren.size === 0) { + if (state.children.size > 0) backgrounds.set(attached, { state: turn.state }) + return yield* close + } + const responded = yield* ACPConnection.Responded + const nextState = yield* Ref.make({ ...state, started: false }) + const cancelled = yield* Deferred.make() + // Children outlive a cancelled turn, so their asks and report-triggered turns still reach the client. + const background = Effect.withFiber((fiber) => { + backgrounds.set(attached, { state: nextState, fiber }) + return Effect.exit(responded).pipe( + Effect.andThen( + followChildren({ ...turn, ctx: { ...turn.ctx, start: undefined }, state: nextState, cancelled }), + ), + Effect.interruptible, + ) }).pipe(Effect.ignore, Effect.ensuring(close), Effect.withSpan("cli.acp.turn.background")) yield* input.sessions.fork(attached, background).pipe(Effect.catchTag("ACPSessionNotFoundError", () => close)) }) @@ -368,6 +393,7 @@ export const make = Effect.fnUntraced(function* (input: { const state = yield* Ref.make(ACPTranslate.initial) const exit = yield* Effect.acquireUseRelease( open( + attached, { sessionID: attached.id, cwd: attached.cwd, diff --git a/packages/cli/test/acp/background-turn.subprocess.test.ts b/packages/cli/test/acp/background-turn.subprocess.test.ts new file mode 100644 index 000000000000..5894004c437d --- /dev/null +++ b/packages/cli/test/acp/background-turn.subprocess.test.ts @@ -0,0 +1,48 @@ +import type { PromptResponse } from "@agentclientprotocol/sdk" +import { expect, test } from "bun:test" +import { Schema } from "effect" +import { createAcpFixture, expectOk, initialize, newSession, toolCallStream } from "./subprocess" + +const modelRequest = Schema.decodeUnknownSync(Schema.Struct({ messages: Schema.Array(Schema.Unknown) })) + +test("streams the parent's response to a subagent report after end_turn", async () => { + const child = Promise.withResolvers() + const resumed = Promise.withResolvers() + await using fixture = await createAcpFixture({ + respond(request) { + const last = JSON.stringify(modelRequest(request).messages.at(-1)) + if (last.includes("("session/prompt", { + sessionId, + prompt: [{ type: "text", text: "run the child" }], + }), + ) + expect(response.stopReason).toBe("end_turn") + child.resolve("child result") + await resumed.promise + const message = await acp.waitForMessage( + (message) => message.method === "session/update" && JSON.stringify(message.params).includes("parent reaction"), + "the resumed parent's agent_message_chunk", + ) + expect(message.params).toMatchObject({ + sessionId, + update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "parent reaction" } }, + }) +}, 60_000) diff --git a/packages/cli/test/acp/subprocess.ts b/packages/cli/test/acp/subprocess.ts index dee0ee22c6af..9ca913371f83 100644 --- a/packages/cli/test/acp/subprocess.ts +++ b/packages/cli/test/acp/subprocess.ts @@ -37,6 +37,7 @@ type AcpProcess = { readonly pid: number readonly exited: Promise readonly request: (method: string, params?: unknown) => Promise> + readonly waitForMessage: (predicate: Waiter["predicate"], description: string) => Promise readonly close: () => Promise readonly stderr: () => string readonly [Symbol.asyncDispose]: () => Promise @@ -294,6 +295,7 @@ function spawnAcp(input: { readonly env: Record }): pid: child.pid, exited: child.exited, request, + waitForMessage: (predicate, description) => take(predicate, 10_000, description), async close() { if (!inputClosed) { inputClosed = true diff --git a/packages/cli/test/acp/turn.test.ts b/packages/cli/test/acp/turn.test.ts index 54bfa5a8aa75..b56e3f3b4946 100644 --- a/packages/cli/test/acp/turn.test.ts +++ b/packages/cli/test/acp/turn.test.ts @@ -136,6 +136,63 @@ describe("acp turn events over the wire", () => { }, ) + test("streams resumed parent turns after background children report across prompts", async () => { + await using acp = await startSession({ + permission: () => ({ outcome: { outcome: "selected", optionId: "once" } }), + onPrompt: ({ sessionID, id, text }) => { + if (text === "launch") + return turn( + sessionID, + id, + childCreated("ses_first", sessionID, "First"), + childCreated("ses_second", sessionID, "Second"), + ) + if (text === "followup") + return turn(sessionID, id, durableEvent("session.execution.started", { sessionID: "ses_first" })) + return turn( + sessionID, + id, + textDelta("ses_second", "msg_child_2", "older child during chat"), + textDelta(sessionID, "msg_chat", "chat reply"), + ) + }, + }) + const sessionID = acp.sessionId + + expect((await acp.prompt(sessionID, "launch")).stopReason).toBe("end_turn") + acp.server.send( + textDelta("ses_first", "msg_child", "child only"), + succeeded("ses_first"), + ...turn(sessionID, "msg_report_1", textDelta(sessionID, "msg_reaction_1", "first reaction")), + textDelta(sessionID, "msg_stale", "stale"), + ) + await acp.waitForUpdate(({ update }) => JSON.stringify(update).includes("first reaction")) + + expect((await acp.prompt(sessionID, "chat")).stopReason).toBe("end_turn") + acp.server.send( + permissionAsked("ses_second", "perm_second", { action: "read" }), + succeeded("ses_second"), + ...turn(sessionID, "msg_report_2", textDelta(sessionID, "msg_reaction_2", "second reaction")), + ) + await acp.waitForUpdate(({ update }) => JSON.stringify(update).includes("second reaction")) + await acp.until(() => acp.server.replies.length === 1, "second child permission reply") + + expect((await acp.prompt(sessionID, "followup")).stopReason).toBe("end_turn") + acp.server.send( + succeeded("ses_first"), + ...turn(sessionID, "msg_report_3", textDelta(sessionID, "msg_reaction_3", "followup reaction")), + ) + await acp.waitForUpdate(({ update }) => JSON.stringify(update).includes("followup reaction")) + + expect(acp.server.replies).toEqual([{ sessionID: "ses_second", requestID: "perm_second", decision: "once" }]) + expect(turnUpdates(acp.updates).map(({ update }) => update)).toMatchObject([ + { messageId: "msg_reaction_1", content: { text: "first reaction" } }, + { messageId: "msg_chat", content: { text: "chat reply" } }, + { messageId: "msg_reaction_2", content: { text: "second reaction" } }, + { messageId: "msg_reaction_3", content: { text: "followup reaction" } }, + ]) + }) + test("cancels unsupported session forms so execution can continue", async () => { await using acp = await startSession({ onPrompt: ({ sessionID, id }) => [ diff --git a/packages/cli/test/run/noninteractive.test.ts b/packages/cli/test/run/noninteractive.test.ts index f6ee2eb9ca91..9061888df427 100644 --- a/packages/cli/test/run/noninteractive.test.ts +++ b/packages/cli/test/run/noninteractive.test.ts @@ -670,6 +670,47 @@ describe("runNonInteractivePrompt", () => { expect(lists).toEqual([]) }) + test("waits for a subagent's report and the parent turn it triggers before exiting", async () => { + const lists: ExperimentalJobListOutput[] = [[subagentJob], []] + const output = await capture({ + format: "json", + jobs: () => lists.shift() ?? [], + messages: (messageID) => [ + idleMessage("failed", "msg_report_idle"), + { id: messageID, type: "user", text: "hello", time: { created: 1 } }, + ], + turn: (id) => [ + prompted(id), + settled(), + { + id: "evt_report_text", + created: 2, + type: "session.text.ended", + durable: { aggregateID: "ses_1", seq: 2, version: 1 }, + data: { sessionID: "ses_1", assistantMessageID: "msg_report_answer", ordinal: 0, text: "Report handled." }, + }, + { + id: "evt_report_failed", + created: 3, + type: "session.execution.failed", + durable: { aggregateID: "ses_1", seq: 3, version: 1 }, + data: { sessionID: "ses_1", error: { type: "unknown", message: "report turn failed" } }, + }, + ], + }) + const events = jsonLines(output.stdout) + expect(events.find((event) => event.type === "background_wait")).toMatchObject({ + jobs: [{ id: "ses_child", kind: "subagent" }], + }) + expect(output.stdout).toContain("Report handled.") + // The first turn succeeded; the report-triggered turn decides the exit code. + expect(output.exitCode).toBe(1) + expect(events.find((event) => event.type === "error")).toMatchObject({ + error: { message: "Execution failed" }, + }) + expect(lists).toEqual([]) + }) + test("a recovered step failure exits 0, reports its retry once, and still waits for background work", async () => { const lists: ExperimentalJobListOutput[] = [[shellJob("sh_train", "python train.py")], []] const retry = { attempt: 1, error: { type: "provider.transport", message: "Recovered transport error" } } diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index a6e4e63ad04f..f65ec052c2b3 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -2165,6 +2165,7 @@ export type EventSubscribeInput = { | "vcs.branch.updated" | "mcp.status.changed" | "mcp.resources.changed" + | "experimental.mcp.event" | `${"rpc."}${string}` > | undefined diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index d2fa18fb39e1..87b848cb2604 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2121,6 +2121,24 @@ export type McpResourcesChanged = { data: { server: string } } +export type ExperimentalMcpEvent = { + id: EventID + created: number + metadata?: { [x: string]: any } + type: "experimental.mcp.event" + location?: LocationRef + data: { + id: string + server: string + name: string + eventId: string + timestamp: string + data: JsonValue + cursor: string | null + truncated?: boolean | undefined + } +} + export type SessionToolSuccess = { id: EventID created: number @@ -2969,6 +2987,7 @@ export type V2Event = | VcsBranchUpdated | McpStatusChanged | McpResourcesChanged + | ExperimentalMcpEvent | V2EventRpc | V2EventServerConnected @@ -4467,6 +4486,7 @@ export type EventSubscribeInput = { | "vcs.branch.updated" | "mcp.status.changed" | "mcp.resources.changed" + | "experimental.mcp.event" | `${"rpc."}${string}` > | undefined diff --git a/packages/core/package.json b/packages/core/package.json index df233a19cb46..b85d38e81edd 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -104,7 +104,7 @@ "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/core": "2.4.0", "@modelcontextprotocol/server": "2.4.0", - "@opencode/pty": "0.5.0", + "@opencode/pty": "0.5.2", "@opencode/ai": "workspace:*", "@opencode/codemode": "workspace:*", "@opencode/plugin": "workspace:*", @@ -119,7 +119,7 @@ "drizzle-orm": "catalog:", "effect": "catalog:", "fuzzysort": "3.1.0", - "gitlab-ai-provider": "6.23.1", + "gitlab-ai-provider": "6.24.0", "gray-matter": "4.0.3", "htmlparser2": "8.0.2", "http-proxy-agent": "7.0.2", diff --git a/packages/core/src/config/plugin/command.ts b/packages/core/src/config/plugin/command.ts index 2eaa0115b86d..ab2a59f782d2 100644 --- a/packages/core/src/config/plugin/command.ts +++ b/packages/core/src/config/plugin/command.ts @@ -93,7 +93,7 @@ export const Plugin = define({ agent: selected.id, description: command.description ?? name, } - yield* subagents.start(recovery, { background: true }) + yield* subagents.start(recovery) return } if (agent !== undefined) { diff --git a/packages/core/src/instructions/index.ts b/packages/core/src/instructions/index.ts index 918dd0e1fefb..962aab7bedd8 100644 --- a/packages/core/src/instructions/index.ts +++ b/packages/core/src/instructions/index.ts @@ -3,6 +3,7 @@ export * as Instructions from "./index.js" import { createHash } from "crypto" import { Instruction } from "@opencode/schema/instruction" import { Data, Effect, Option, Schema } from "effect" +import { canonicalJson } from "../util/canonical-json.js" export const Key = Instruction.Key export type Key = Instruction.Key @@ -202,7 +203,7 @@ export function renderUpdate( } export function hash(value: Schema.Json) { - return Hash.make(createHash("sha256").update(canonical(value)).digest("hex")) + return Hash.make(createHash("sha256").update(canonicalJson(value)).digest("hex")) } export function applyHashDelta(values: Values, delta: Delta): Values { @@ -280,16 +281,6 @@ function isRemoved(value: unknown): value is Removed { return value === removed } -function canonical(value: Schema.Json): string { - if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]` - if (value !== null && typeof value === "object") - return `{${Object.entries(value) - .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) - .map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`) - .join(",")}}` - return JSON.stringify(value) -} - function requireText(key: Key, kind: string, text: string) { if (text.length === 0) throw new Error(`Instruction source ${key} rendered an empty ${kind}`) return text diff --git a/packages/core/src/job.ts b/packages/core/src/job.ts index 1491ed22de6d..94252e3fa6d1 100644 --- a/packages/core/src/job.ts +++ b/packages/core/src/job.ts @@ -38,7 +38,6 @@ export type Background = typeof Background.Type export type Status = Background["status"] export type SubagentReportState = - | { readonly mode: "foreground" } | { readonly mode: "background" readonly notificationID: SessionMessage.ID @@ -107,7 +106,7 @@ type BackgroundResult = { backgrounded?: Deferred.Deferred } -type StartResult = { info: Info } | { info: Info; job: Active } | { info: Info; backgrounded: Deferred.Deferred } +type StartResult = { info: Info } | { info: Info; job: Active } type BlockWait = { done: Deferred.Deferred @@ -363,14 +362,7 @@ export const make = Effect.gen(function* () { const existing = jobs.get(input.id) // A settling generation is already reporting; new work starts a fresh generation. if (existing?.info.status === "running" && !existing.settling) { - if (!input.background || existing.isBackgrounded) return [{ info: snapshot(existing) }, jobs] - // Joining live work after its start must register the durable marker before a fast - // drain can settle and classify the period as foreground. - const updated = yield* markBackground(existing) - return [ - { info: snapshot(updated), backgrounded: existing.backgrounded }, - new Map(jobs).set(input.id, updated), - ] + return [{ info: snapshot(existing) }, jobs] } const scope = yield* Scope.fork(state.scope, "parallel") // Closing the registry interrupts the work without settling it; interrupt its observers too. @@ -406,7 +398,6 @@ export const make = Effect.gen(function* () { return [{ info: snapshot(job), job }, new Map(jobs).set(input.id, job)] }), ) - if ("backgrounded" in result) yield* Deferred.succeed(result.backgrounded, result.info) if ("job" in result) yield* restore(input.run).pipe( Effect.exit, @@ -498,8 +489,6 @@ export const make = Effect.gen(function* () { const job = jobs.get(id) // Recoverable work may finish before the caller backgrounds it. if (!job || (job.info.status !== "running" && !job.recovery)) return [{}, jobs] - // A settling generation already reported as foreground; a late Ctrl+B must not revive it. - if (job.settling) return [{}, jobs] if (job.isBackgrounded) return [{ info: snapshot(job) }, jobs] const next = yield* markBackground(job) return [{ info: snapshot(next), backgrounded: job.backgrounded }, new Map(jobs).set(id, next)] @@ -519,7 +508,6 @@ export const make = Effect.gen(function* () { const next = new Map(jobs) for (const [id, job] of jobs) { if (job.info.status !== "running") continue - if (job.settling) continue if (job.isBackgrounded) continue if (input.type !== undefined && job.info.type !== input.type) continue if (!job.blockingSessions.has(input.sessionID)) continue @@ -649,7 +637,9 @@ export const make = Effect.gen(function* () { return yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [SubagentReportState, Map] => { const job = jobs.get(id) // A generation reports at most once, even when an earlier attempt only observed a cancel. - if (!job || job.reported) return [{ mode: "none" }, jobs] + if (!job?.isBackgrounded || job.reported || !job.info.notificationID || job.recovery?.kind !== "subagent") { + return [{ mode: "none" }, jobs] + } const live = job.info.status === "running" && !job.settling // A cancel within this busy period already consumed the live entry, but it still belongs // here. A creation-tick interruption never bound a generation, so any cancel matches. @@ -662,8 +652,6 @@ export const make = Effect.gen(function* () { ...(job.info.status === "running" ? { settling: true } : {}), } const next = new Map(jobs).set(id, updated) - if (!job.isBackgrounded) return [{ mode: "foreground" }, next] - if (!job.info.notificationID || job.recovery?.kind !== "subagent") return [{ mode: "none" }, next] return [ { mode: "background", diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index c79cf8b61ca3..9553f00f353e 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -34,6 +34,9 @@ import { ConfigMCP } from "@opencode/schema/config/mcp" import type { Session } from "@opencode/schema/session" import { isRecord } from "@opencode/util/record" import { McpStdio } from "./stdio.js" +import { EventStreamRejectedError, EventStreamTerminatedError } from "./event-errors.js" + +export { EventStreamRejectedError, EventStreamTerminatedError } const DEFAULT_STARTUP_TIMEOUT = 30_000 const DEFAULT_CATALOG_TIMEOUT = 30_000 @@ -82,7 +85,7 @@ const EventType = Schema.Struct({ payloadSchema: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), }) export type EventType = typeof EventType.Type -const EventError = Schema.Struct({ code: Schema.Number, message: Schema.String, data: Schema.optional(Schema.Unknown) }) +const EventError = Schema.Struct({ code: Schema.Number, message: Schema.String, data: Schema.optional(Schema.Json) }) export type EventError = typeof EventError.Type // An absent cursor means null: the event type has no replay. const Cursor = Schema.optional(Schema.NullOr(Schema.String)) @@ -99,7 +102,7 @@ const EventNotification = Schema.toStandardSchemaV1( eventId: Schema.String, name: Schema.String, timestamp: Schema.String, - data: Schema.Unknown, + data: Schema.Json, cursor: Cursor, ...Subscribed, }), @@ -119,7 +122,7 @@ export type EventMessage = readonly eventId: string readonly name: string readonly timestamp: string - readonly data: unknown + readonly data: Schema.Json readonly cursor: string | null } /** Nothing matched; the server has checked up to `cursor`. */ @@ -127,19 +130,9 @@ export type EventMessage = /** A recoverable failure, such as one failed upstream fetch; the stream stays open. */ | { readonly type: "error"; readonly error: EventError } -/** - * The server ended the subscription, as when access was revoked or the event type was removed or changed. - * Experimental: MCP Events is a draft extension; may change without compatibility guarantees. - */ -export class EventStreamTerminatedError extends Schema.TaggedError()( - "MCP.EventStreamTerminatedError", - { - server: Schema.String, - code: Schema.Number, - message: Schema.String, - data: Schema.optional(Schema.Unknown), - }, -) {} +// JSON-RPC errors that mean an `events/stream` request can never succeed as sent: unknown method, bad arguments, and +// the events extension's NotFound, Forbidden and Unsupported. +const EVENT_STREAM_REJECTED = new Set([-32601, -32602, -32023, -32024, -32026]) export type { GetPromptResult, Prompt, ReadResourceResult, Resource } export type ResourceTemplate = ResourceTemplateType @@ -267,8 +260,9 @@ export interface Events { readonly list: () => Effect.Effect, Error> /** * Push delivery (`events/stream`) from `cursor`, or from now. Ends when the server closes the stream. Fails with - * EventStreamTerminatedError when the server ends the subscription, and with another error when the stream breaks - * or falls silent for a minute, after which it can be opened again from the last cursor. Interrupting it cancels it. + * EventStreamRejectedError when the server refuses the subscription, EventStreamTerminatedError when it ends it, + * and with another error when the stream breaks or falls silent for a minute, after which it can be opened again + * from the last cursor. Interrupting it cancels it. */ readonly stream: (input: { readonly name: string @@ -593,15 +587,23 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { }), ) // Interrupting the request cancels the stream; the server closing it resolves the request. - yield* request("stream MCP events", (signal) => - client.request({ method: "events/stream", params: input }, StreamResult, { - signal, - // Heartbeats, not a request timeout, tell a quiet stream from a dead one; see below. - timeout: Infinity, - // Routes the stream's notifications, which can arrive before the request settles. - onRequestId: (id) => streams.set(String(id), queue), - }), - ).pipe( + yield* Effect.tryPromise({ + try: (signal) => + client.request({ method: "events/stream", params: input }, StreamResult, { + signal, + // Heartbeats, not a request timeout, tell a quiet stream from a dead one; see below. + timeout: Infinity, + // Routes the stream's notifications, which can arrive before the request settles. + onRequestId: (id) => streams.set(String(id), queue), + }), + catch: (error) => + error instanceof ProtocolError && EVENT_STREAM_REJECTED.has(error.code) + ? new EventStreamRejectedError({ server, code: error.code, message: error.message }) + : failure(error), + }).pipe( + Effect.tapError((error) => + Effect.logWarning("failed to stream MCP events", { server, error: error.message }), + ), Effect.matchEffect({ onFailure: (error) => Queue.fail(queue, error), onSuccess: () => Queue.end(queue), diff --git a/packages/core/src/mcp/event-errors.ts b/packages/core/src/mcp/event-errors.ts new file mode 100644 index 000000000000..febf2db14bb5 --- /dev/null +++ b/packages/core/src/mcp/event-errors.ts @@ -0,0 +1,28 @@ +import { Schema } from "effect" + +/** + * The server refused the subscription, as for an unknown event type, bad arguments or missing access. + * Experimental: MCP Events is a draft extension; may change without compatibility guarantees. + */ +export class EventStreamRejectedError extends Schema.TaggedError()( + "MCP.EventStreamRejectedError", + { + server: Schema.String, + code: Schema.Number, + message: Schema.String, + }, +) {} + +/** + * The server ended the subscription, as when access was revoked or the event type was removed or changed. + * Experimental: MCP Events is a draft extension; may change without compatibility guarantees. + */ +export class EventStreamTerminatedError extends Schema.TaggedError()( + "MCP.EventStreamTerminatedError", + { + server: Schema.String, + code: Schema.Number, + message: Schema.String, + data: Schema.optional(Schema.Json), + }, +) {} diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index bf088d9e8e59..4f8a5c61305e 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -13,9 +13,11 @@ import { Effect, Exit, Fiber, + FiberMap, FiberSet, Latch, Layer, + Schedule, Schema, Scope, Semaphore, @@ -33,9 +35,12 @@ import { Form } from "../form.js" import { Integration } from "../integration.js" import { KeyedMutex } from "../effect/keyed-mutex.js" import { Location } from "../location.js" +import { Hash } from "@opencode/util/hash" import { waitForAbort } from "@opencode/util/process" import { State } from "../state.js" import type { McpClient } from "./client.js" +import { EventStreamRejectedError, EventStreamTerminatedError } from "./event-errors.js" +import { canonicalJson } from "../util/canonical-json.js" import { McpConnection } from "./connection.js" import { McpPool } from "./pool.js" @@ -131,6 +136,12 @@ const URL_ELICITATION_FIELD_KEY = "elicitation" const changes = { tools: McpEvent.ToolsChanged, resources: McpEvent.ResourcesChanged, prompts: PromptsChanged } +// A broken, silent or closed event stream reopens after a delay growing from a second to this cap. +const EVENT_REOPEN = Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("30 seconds")]) + +const isEnded = (error: Error) => + error instanceof EventStreamRejectedError || error instanceof EventStreamTerminatedError + type Data = { servers: Map> removed: Set @@ -185,10 +196,53 @@ export interface Interface extends State.Transformable { }) => Effect.Effect /** Experimental: MCP Events of a connected server that offers them, while the `mcp_events` flag is on. */ readonly events: (server: ServerName | string) => Effect.Effect + /** + * Experimental: follows an event type of a server, publishing each event as `experimental.mcp.event` while the + * server is connected, and resuming from the last cursor after a reconnect or a broken stream. Its status changes + * publish `experimental.mcp.subscription.changed`. Subscribing again to the same server, name and arguments returns + * the existing subscription. Subscriptions last as long as this service, and an ended one stays until unsubscribed. + */ + readonly subscribe: ( + server: ServerName | string, + input: { + readonly name: string + readonly arguments?: Schema.JsonObject + /** Where to start; omitted or null starts from now. */ + readonly cursor?: string | null + }, + ) => Effect.Effect + /** Experimental: stops following a subscription. */ + readonly unsubscribe: (id: string) => Effect.Effect + /** Experimental: every subscription, with its status. */ + readonly subscriptions: () => Effect.Effect> } export class Service extends Context.Service()("@opencode/MCP") {} +/** + * Why `subscribe` cannot follow a server's events. + * Experimental: MCP Events is a draft extension; may change without compatibility guarantees. + */ +export class EventsUnavailableError extends Schema.TaggedError()("MCP.EventsUnavailableError", { + server: ServerName, + message: Schema.String, +}) {} + +/** + * An event type of a server, followed onto the bus as `experimental.mcp.event`. + * Experimental: MCP Events is a draft extension; may change without compatibility guarantees. + */ +export interface Subscription { + /** The same for every subscribe to this server, event name and arguments, within this Location. */ + readonly id: string + readonly server: ServerName + readonly name: string + readonly arguments?: Schema.JsonObject + readonly status: Mcp.SubscriptionStatus + /** Where it resumes from: the last cursor the server sent. */ + readonly cursor: string | null +} + export const Options = Schema.Struct({ clientInfo: Schema.optional( Schema.Struct({ @@ -239,6 +293,117 @@ export const layer = (options?: Options) => // Legacy era only: pending URL-mode elicitation forms, settled by notifications/elicitation/complete. const urlElicitations = new Map() + // Experimental MCP Events subscriptions, by server. Each streams while its server is connected; the streams + // run here, in this Location, not in a pooled connection's scope. + type Followed = { -readonly [K in keyof Subscription]: Subscription[K] } & { gap: boolean } + const followed = new Map>() + const streams = yield* FiberMap.make() + const runStream = yield* FiberMap.runtime(streams)() + const view = (sub: Followed): Subscription => ({ + id: sub.id, + server: sub.server, + name: sub.name, + arguments: sub.arguments, + status: sub.status, + cursor: sub.cursor, + }) + + const setStatus = (sub: Followed, status: Mcp.SubscriptionStatus) => + Effect.suspend(() => { + if (sub.status.status === status.status) return Effect.void + sub.status = status + return bus.publish(McpEvent.ExperimentalSubscriptionChanged, { id: sub.id }) + }) + + const receive = (sub: Followed, message: McpClient.EventMessage) => { + if (message.type === "error") + return Effect.logWarning("mcp event stream error", { + server: sub.server, + name: sub.name, + code: message.error.code, + }) + if (message.type === "heartbeat") + return Effect.sync(() => { + sub.cursor = message.cursor + }) + if (message.type === "active") + return Effect.sync(() => { + sub.cursor = message.cursor + sub.gap ||= message.cursor !== null && message.truncated + }).pipe(Effect.andThen(setStatus(sub, { status: "active" }))) + // The cursor moves past the event only once it is published. + return bus + .publish(McpEvent.ExperimentalEvent, { + id: sub.id, + server: sub.server, + name: sub.name, + eventId: message.eventId, + timestamp: message.timestamp, + data: message.data, + cursor: message.cursor, + ...(sub.gap ? { truncated: true } : {}), + }) + .pipe( + Effect.andThen( + Effect.sync(() => { + sub.cursor = message.cursor + sub.gap = false + }), + ), + ) + } + + // Streams until the server terminates or rejects the subscription. A clean close reopens like a broken stream. + const follow = (sub: Followed, events: McpClient.Events) => + Stream.suspend(() => events.stream({ name: sub.name, arguments: sub.arguments, cursor: sub.cursor })).pipe( + Stream.tap((message) => receive(sub, message)), + // Stream.retry resets on output. Only a confirmed open resets the delay, not a failed attempt. + Stream.filter((message) => message.type === "active"), + Stream.concat(Stream.fail(new Error(`MCP server ${sub.server} closed the event stream`))), + Stream.tapError((error) => (isEnded(error) ? Effect.void : setStatus(sub, { status: "pending" }))), + Stream.retry( + EVENT_REOPEN.pipe( + Schedule.setInputType(), + Schedule.while(({ input }) => !isEnded(input)), + ), + ), + Stream.runDrain, + Effect.catch((error) => + isEnded(error) + ? setStatus(sub, { + status: "ended", + reason: error instanceof EventStreamRejectedError ? "rejected" : "terminated", + error: { code: error.code, message: error.message }, + }) + : Effect.void, + ), + ) + + // Starts or stops a server's subscriptions to match its status; runs on every status change. + const follows = Effect.fnUntraced(function* (server: ServerName) { + const entry = entries.get(server) + const client = entry?.status.status === "connected" ? entry.connection.client : undefined + for (const sub of followed.get(server)?.values() ?? []) { + if (sub.status.status === "ended") continue + if (client?.events) { + runStream(sub.id, follow(sub, client.events), { onlyIfMissing: true }) + continue + } + yield* FiberMap.remove(streams, sub.id) + yield* setStatus( + sub, + !entry || entry.status.status === "disabled" || client + ? { status: "ended", reason: "unavailable" } + : { status: "pending" }, + ) + } + }) + if (mcpEvents) + yield* bus.subscribe(McpEvent.StatusChanged).pipe( + Stream.runForEach((event) => follows(ServerName.make(event.data.server))), + Effect.forkScoped({ startImmediately: true }), + ) + // Register every remote server as an OAuth integration so credentials live in the global store // rather than in committed config. Servers that connect anonymously simply never use the method. const register = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) { @@ -905,6 +1070,40 @@ export const layer = (options?: Options) => events: Effect.fn("MCP.events")(function* (server) { return (yield* connected(ServerName.make(server))).client?.events }), + subscribe: Effect.fn("MCP.subscribe")(function* (server, input) { + const name = ServerName.make(server) + if (!mcpEvents) + return yield* new EventsUnavailableError({ server: name, message: "MCP events need the mcp_events flag." }) + yield* requireServer(name) + const id = "mcpsub_" + Hash.sha256(canonicalJson([name, input.name, input.arguments ?? {}])).slice(0, 24) + const subs = followed.get(name) ?? new Map() + followed.set(name, subs) + const existing = subs.get(id) + if (existing && existing.status.status !== "ended") return view(existing) + const sub: Followed = { + id, + server: name, + name: input.name, + arguments: input.arguments, + status: { status: "pending" }, + cursor: input.cursor ?? existing?.cursor ?? null, + gap: false, + } + subs.set(id, sub) + yield* bus.publish(McpEvent.ExperimentalSubscriptionChanged, { id }) + yield* follows(name) + return view(sub) + }), + unsubscribe: Effect.fn("MCP.unsubscribe")(function* (id) { + const subs = Array.from(followed.values()).find((subs) => subs.has(id)) + if (!subs) return + subs.delete(id) + yield* FiberMap.remove(streams, id) + yield* bus.publish(McpEvent.ExperimentalSubscriptionChanged, { id }) + }), + subscriptions: Effect.fn("MCP.subscriptions")(function* () { + return Array.from(followed.values()).flatMap((subs) => Array.from(subs.values(), view)) + }), }) }), ) diff --git a/packages/core/src/mcp/oauth.ts b/packages/core/src/mcp/oauth.ts index ec0284201c25..f847f7bffeb6 100644 --- a/packages/core/src/mcp/oauth.ts +++ b/packages/core/src/mcp/oauth.ts @@ -137,7 +137,8 @@ interface Options { readonly config: typeof ConfigMCP.Remote.Type readonly store: Store readonly redirect: { - readonly url: string + readonly url: () => string + readonly registered: string[] readonly state: string readonly open: (url: URL) => void | Promise } @@ -151,7 +152,9 @@ const provider = (options: Options): OAuthClientProvider => { const redirect = options.redirect let discovery = options.discovery return { - redirectUrl: redirect.url, + get redirectUrl() { + return redirect.url() + }, discoveryState: async () => discovery, saveDiscoveryState: (state) => { discovery = state @@ -160,7 +163,7 @@ const provider = (options: Options): OAuthClientProvider => { ...(options.clientMetadataUrl ? { clientMetadataUrl: options.clientMetadataUrl } : {}), state: () => redirect.state, clientMetadata: { - redirect_uris: [redirect.url], + redirect_uris: redirect.registered, client_name: "opencode", client_uri: "https://opencode.ai", logo_uri: "https://opencode.ai/web-app-manifest-512x512.png", @@ -435,7 +438,10 @@ export const authorize = (input: { const client = clientFromCredential(previous) if (client) yield* Effect.promise(() => store.saveClientInformation(client)) } - const code = yield* Deferred.make<{ code: string; iss: string | undefined; response?: ServerResponse }, Error>() + const code = yield* Deferred.make< + { code: string; iss: string | undefined; host?: string; response?: ServerResponse }, + Error + >() const redirect = oauth?.redirect_uri ? new URL(oauth.redirect_uri) : undefined const redirectPath = redirect?.pathname ?? "/callback" const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url") @@ -472,7 +478,12 @@ export const authorize = (input: { // The page waits for the token exchange so the browser never reports success for a rejected code. if ( !Effect.runSync( - Deferred.succeed(code, { code: value, iss: url.searchParams.get("iss") ?? undefined, response }), + Deferred.succeed(code, { + code: value, + iss: url.searchParams.get("iss") ?? undefined, + host: request.headers.host, + response, + }), ) ) response.writeHead(409).end("OAuth callback already received") @@ -530,6 +541,10 @@ export const authorize = (input: { registration: oauth?.client_id ? "static" : cimd ? "cimd" : "dcr", }) + // Some authorization servers (Clerk) rewrite a 127.0.0.1 redirect to localhost before sending the browser back, + // and issue the code for the rewritten URI. Both are registered, and the token exchange repeats the one used. + const loopback = (host: string) => `http://${host}:${port}${redirectPath}` + let reached = "127.0.0.1" let authorizationUrl: URL | undefined const oauthProvider = provider({ config: input.config, @@ -537,7 +552,8 @@ export const authorize = (input: { clientMetadataUrl: cimd ? CLIENT_METADATA_URL : undefined, discovery: { ...discovery, resourceMetadataUrl: resourceMetadataUrl?.toString() }, redirect: { - url: oauth?.redirect_uri ?? `http://127.0.0.1:${port}${redirectPath}`, + url: () => oauth?.redirect_uri ?? loopback(reached), + registered: oauth?.redirect_uri ? [oauth.redirect_uri] : [loopback("127.0.0.1"), loopback("localhost")], state, open: (url) => { authorizationUrl = url @@ -580,6 +596,7 @@ export const authorize = (input: { const completed = yield* Deferred.make() yield* Deferred.await(code).pipe( Effect.flatMap((value) => { + if (value.host === `localhost:${port}`) reached = "localhost" const respond = (error?: string) => Effect.sync(() => value.response diff --git a/packages/core/src/provider.ts b/packages/core/src/provider.ts index 431cee79c47c..e2256c3c8874 100644 --- a/packages/core/src/provider.ts +++ b/packages/core/src/provider.ts @@ -88,6 +88,7 @@ const builtins = new Map Promise>([ ["@opencode/ai/providers/fireworks", () => import("@opencode/ai/providers/fireworks")], ["@opencode/ai/providers/fireworks/embeddings", () => import("@opencode/ai/providers/fireworks/embeddings")], ["@opencode/ai/providers/google", () => import("@opencode/ai/providers/google")], + ["@opencode/ai/providers/google/decisions", () => import("@opencode/ai/providers/google/decisions")], ["@opencode/ai/providers/google/interactions", () => import("@opencode/ai/providers/google/interactions")], ["@opencode/ai/providers/google/embeddings", () => import("@opencode/ai/providers/google/embeddings")], ["@opencode/ai/providers/google/images", () => import("@opencode/ai/providers/google/images")], diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 9b43387b8133..1e03cc6b41fe 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -29,7 +29,6 @@ import path from "path" import { SessionRunner } from "./session/runner/index.js" import { SessionStore } from "./session/store.js" import { SessionExecution } from "./session/execution.js" -import { SubagentMetadata } from "./session/subagent-metadata.js" import { AttachmentError, BusyError, @@ -313,9 +312,7 @@ const layer = Layer.effect( agent: input.agent, // Children inherit metadata and permissions the way they inherit // location, so host policies that read them treat the family uniformly. - // The per-link subagent switch is not host metadata, though: a silent - // child must not silence the sessions created beneath it. - metadata: input.metadata ?? SubagentMetadata.inherit(parent?.metadata), + metadata: input.metadata ?? parent?.metadata, permissions: input.permissions ?? parent?.permissions, model: input.model, }, diff --git a/packages/core/src/session/background.ts b/packages/core/src/session/background.ts index 2471ee883b0f..f0a7c920a3fb 100644 --- a/packages/core/src/session/background.ts +++ b/packages/core/src/session/background.ts @@ -82,14 +82,9 @@ export const outstanding = Effect.fnUntraced(function* ( const children = new Set(items.flatMap((item) => (item.kind === "subagent" ? [item.childSessionID] : []))) for (const activeID of active) { if (activeID === sessionID || children.has(activeID)) continue - // Foreground-blocking work is the caller's inline result, and cancelled work is - // acknowledged elsewhere: neither is still running for this report. + // A cancelled child may still be draining while it cleans up. const tracked = jobs.get ? yield* jobs.get(activeID) : undefined - if ( - tracked && - ((tracked.status === "running" && tracked.notificationID === undefined) || tracked.status === "cancelled") - ) - continue + if (tracked?.status === "cancelled") continue if (!(yield* descends(store, parents, activeID, sessionID))) continue const info = yield* store.get(activeID) if (!info?.parentID) continue diff --git a/packages/core/src/session/execution.ts b/packages/core/src/session/execution.ts index b73168b2017e..382f1f9db358 100644 --- a/packages/core/src/session/execution.ts +++ b/packages/core/src/session/execution.ts @@ -24,11 +24,6 @@ export interface Interface { readonly resume: (sessionID: SessionSchema.ID) => Effect.Effect /** Registers newly recorded work. Repeated wakeups may coalesce. */ readonly wake: (sessionID: SessionSchema.ID) => Effect.Effect - /** - * The durable sequence where the Session's current busy period started, if one is bound. - * Sequence-bounded lookups use it to find only work created by this period. - */ - readonly periodStartSeq: (sessionID: SessionSchema.ID) => Effect.Effect /** * Interrupt active work owned by this process. Idle interruption is a no-op. Resolves once * the interruption is accepted; cleanup settles asynchronously in the execution fiber. @@ -163,8 +158,7 @@ export const layer = Layer.effect( yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID, reason: "shutdown" }) return } - // Classify and claim the Job generation before cancelling it: the settlement commit - // owns the outbox row, and a cancel must not race a foreground classification. + // Claim the Job generation before cancelling it so the settlement commit owns its outbox row. const settlement = yield* subagentReport.prepare(sessionID, outcome) if (outcome.type === "interrupted") yield* jobs.cancel(sessionID) yield* publishTerminal(bus, sessionID, outcome, settlement.commit) @@ -182,7 +176,6 @@ export const layer = Layer.effect( return Service.of({ active: coordinator.active, isActive: coordinator.isActive, - periodStartSeq: subagentReport.periodStartSeq, interrupt: (sessionID, options) => Effect.gen(function* () { const interrupted = yield* coordinator.interrupt(sessionID, "user") @@ -236,7 +229,6 @@ export const noopLayer = Layer.succeed( isActive: () => Effect.succeed(false), resume: () => Effect.void, wake: () => Effect.void, - periodStartSeq: () => Effect.succeed(undefined), interrupt: () => Effect.succeed(false), awaitIdle: () => Effect.void, }), diff --git a/packages/core/src/session/execution/restart.ts b/packages/core/src/session/execution/restart.ts index b24b21c2a88d..af2f126443a9 100644 --- a/packages/core/src/session/execution/restart.ts +++ b/packages/core/src/session/execution/restart.ts @@ -14,13 +14,12 @@ import { ShellTool } from "../../tool/plugin/shell.js" import { SessionEvent } from "../event.js" import { SessionExecution } from "../execution.js" import { SessionHistory } from "../history.js" -import { SessionMessage } from "../message.js" import { SessionSchema } from "../schema.js" import { SessionStore } from "../store.js" import { ImageNotice } from "../../image/notice.js" import { ShellResult } from "../../shell/result.js" import { SubagentCompletion } from "../subagent-completion.js" -import { SubagentMetadata } from "../subagent-metadata.js" +import { SubagentJob } from "../subagent-job.js" const CONTINUE_AFTER_SERVER_RESTART = "The server restarted while you were working. Continue from where you left off without repeating completed work." @@ -42,6 +41,8 @@ export interface Options { const DEFAULT_MAX_ATTEMPTS = 10 +type Notices = Pick + export interface Interface { /** * Resumes Sessions whose execution claim was never released — turns orphaned @@ -86,6 +87,11 @@ export const layer = (options?: Options) => const scope = yield* Effect.scope const maxAttempts = options?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS + const wake = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { + const owner = yield* store.get(sessionID) + if (owner && !owner.revert) yield* execution.wake(sessionID) + }) + const prepareResume = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { // Durable before the resume runs, so a crash inside the resumed turn is // counted by the next sweep and the budget cannot be dodged. @@ -205,29 +211,12 @@ export const layer = (options?: Options) => ) }) - const reattach = ( - shell: Shell.Interface, - sessionID: SessionSchema.ID, - info: ShellSchema.Info, - suspended: ReadonlySet, - notificationID?: SessionMessage.ID, - ) => - ShellTool.reattach({ - shell, - jobs, - sessions, - sessionID, - info, - notificationID, - resume: () => (suspended.has(sessionID) ? false : undefined), - }) - // A shell job the previous server left running is watched again if its command is still known (running or // finished during the restart); otherwise it is reported as lost. const recoverShellJob = Effect.fnUntraced(function* ( background: Job.Background, recovery: Extract, - suspended: ReadonlySet, + notices: Notices, reattached: Set, ) { const shell = background.status === "running" ? yield* shellOf(recovery.sessionID) : undefined @@ -237,14 +226,21 @@ export const layer = (options?: Options) => : Option.none() if (!shell || Option.isNone(info)) return yield* recoverToolJob(background, recovery) reattached.add(info.value.id) - yield* reattach(shell, recovery.sessionID, info.value, suspended, background.notificationID) + yield* ShellTool.reattach({ + shell, + jobs, + sessions: notices, + sessionID: recovery.sessionID, + info: info.value, + notificationID: background.notificationID, + }) }) // A server that stopped (shut down or killed) during a foreground shell call leaves the call unsettled, its // command still running in the daemon. Settle the call as moved to the background and watch the command. const settleBackgroundedCalls = Effect.fnUntraced(function* ( sessionID: SessionSchema.ID, - suspended: ReadonlySet, + notices: Notices, reattached: ReadonlySet, ) { const calls = (yield* SessionHistory.incompleteAssistants(db, sessionID)).flatMap((message) => @@ -281,23 +277,22 @@ export const layer = (options?: Options) => // Backgrounded but stopped before the call was settled: its job row was already reattached (and, for a // command that already finished, may even be done). if (reattached.has(info.id)) return - yield* reattach(shell, sessionID, info, suspended) + yield* ShellTool.reattach({ shell, jobs, sessions: notices, sessionID, info }) }), { discard: true }, ) }) const deliverSubagentSafe = Effect.fnUntraced(function* ( + notices: Notices, notificationID: Job.Background["notificationID"], recovery: Extract, result: Pick, - resume: boolean | undefined, ) { - yield* SubagentCompletion.deliver(sessions, jobs, { + yield* SubagentCompletion.deliver(notices, jobs, { ...result, recovery, notificationID, - resume, }).pipe( // A deleted parent owes nothing to the report; clear its row. Effect.catchTag("Session.NotFoundError", () => jobs.completeBackground(notificationID)), @@ -335,26 +330,17 @@ export const layer = (options?: Options) => const recoverSubagent = Effect.fnUntraced(function* ( background: Job.Background, recovery: Extract, - suspended: ReadonlySet, + notices: Notices, ): Effect.fn.Return { const child = yield* store.get(recovery.childSessionID) if (!child || child.parentID !== recovery.parentSessionID || !(yield* store.get(recovery.parentSessionID))) { yield* jobs.completeBackground(background.notificationID) return false } - const silent = !SubagentMetadata.notify(child.metadata) - // A suspended owner must receive the notice after its own restart accounting, - // otherwise admission would wake it before prepareResume can charge the attempt. - const resumeParent = suspended.has(recovery.parentSessionID) ? false : undefined if (background.status !== "running") { - // The outbox row already holds the formatted result; replay it without touching - // the child. A silent link owes no report, so only the marker needs clearing. - if (silent) { - yield* jobs.completeBackground(background.notificationID) - return false - } - yield* deliverSubagentSafe(background.notificationID, recovery, background, resumeParent) + // The outbox row already holds the formatted result; replay it without touching the child. + yield* deliverSubagentSafe(notices, background.notificationID, recovery, background) return false } @@ -362,16 +348,10 @@ export const layer = (options?: Options) => // prepareResume publishes Execution.Failed directly on the bus outside the // coordinator, so the settle hook never reports an exhausted child. if (!(yield* prepareResume(recovery.childSessionID))) { - if (silent) { - yield* jobs.completeBackground(background.notificationID) - return false - } - yield* deliverSubagentSafe( - background.notificationID, - recovery, - { status: "error", error: RESUME_EXHAUSTED.message }, - resumeParent, - ) + yield* deliverSubagentSafe(notices, background.notificationID, recovery, { + status: "error", + error: RESUME_EXHAUSTED.message, + }) return false } // Defer the start until every suspended root has counted its attempt; a fast @@ -397,6 +377,29 @@ export const layer = (options?: Options) => const suspended = new Set( [...(yield* store.listSuspended()), ...children].filter((sessionID) => !active.has(sessionID)), ) + const state = { defer: true } + const wakes = new Set() + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + state.defer = false + yield* Effect.forEach(wakes, (sessionID) => Effect.ignoreCause(wake(sessionID)), { discard: true }) + suspended.clear() + }), + ) + // Hold notice wakes until every suspended root has counted its attempt, so a woken + // child cannot settle mid-sweep and wake its parent past that budget. + const notices: Notices = { + synthetic: (input) => + sessions.synthetic({ ...input, resume: false }).pipe( + Effect.tap(() => { + if (suspended.has(input.sessionID)) return Effect.void + if (!state.defer) return wake(input.sessionID) + wakes.add(input.sessionID) + return Effect.void + }), + Effect.uninterruptible, + ), + } yield* store.releaseChildClaims(children) const recoverable = Effect.fnUntraced(function* (background: Job.Background) { return (yield* jobs.get(background.id))?.status !== "running" @@ -409,7 +412,7 @@ export const layer = (options?: Options) => Effect.fnUntraced(function* (background) { const recovery = background.recovery if (recovery.kind === "subagent" || !(yield* recoverable(background))) return - if (recovery.kind === "shell") return yield* recoverShellJob(background, recovery, suspended, reattached) + if (recovery.kind === "shell") return yield* recoverShellJob(background, recovery, notices, reattached) yield* recoverToolJob(background, recovery) }), { discard: true }, @@ -417,7 +420,7 @@ export const layer = (options?: Options) => yield* Effect.forEach( suspended, (sessionID) => - settleBackgroundedCalls(sessionID, suspended, reattached).pipe( + settleBackgroundedCalls(sessionID, notices, reattached).pipe( Effect.catch((error) => Effect.logWarning("failed to settle backgrounded shell calls", { sessionID, error }), ), @@ -430,7 +433,7 @@ export const layer = (options?: Options) => Effect.fnUntraced(function* (background) { const recovery = background.recovery if (recovery.kind !== "subagent" || !(yield* recoverable(background))) return - if (yield* recoverSubagent(background, recovery, suspended)) resumable.push({ background, recovery }) + if (yield* recoverSubagent(background, recovery, notices)) resumable.push({ background, recovery }) }), { discard: true }, ) @@ -439,10 +442,11 @@ export const layer = (options?: Options) => const resumed = yield* execution.active yield* Effect.forEach( (yield* store.listSuspended()).filter((sessionID) => !resumed.has(sessionID)), - (sessionID) => - execution - .resume(sessionID) - .pipe(Effect.ignore, Effect.forkIn(scope), Effect.when(prepareResume(sessionID))), + Effect.fnUntraced(function* (sessionID) { + if (!(yield* prepareResume(sessionID))) return + suspended.delete(sessionID) + yield* execution.resume(sessionID).pipe(Effect.ignore, Effect.forkIn(scope)) + }), { concurrency: "unbounded", discard: true }, ) @@ -451,31 +455,13 @@ export const layer = (options?: Options) => // report, so no jobs.wait observer is needed. yield* Effect.forEach( resumable, - ({ background, recovery }) => - jobs.start({ - id: background.id, - type: "subagent", - title: recovery.description, - notificationID: background.notificationID, - recovery, - background: true, - run: execution.resume(recovery.childSessionID).pipe( - Effect.onInterrupt(() => - jobs - .isCancelled(background.id) - .pipe( - Effect.flatMap((cancelled) => - cancelled ? execution.interrupt(recovery.childSessionID) : Effect.void, - ), - ), - ), - Effect.as(""), - ), - }), + Effect.fnUntraced(function* ({ background, recovery }) { + yield* SubagentJob.start(jobs, execution, recovery, background.notificationID) + suspended.delete(recovery.childSessionID) + }), { discard: true }, ) - suspended.clear() - }), + }).pipe(Effect.scoped), }) }), ) diff --git a/packages/core/src/session/execution/subagent-report.ts b/packages/core/src/session/execution/subagent-report.ts index 4a2e1f6e91ab..8ec5f439b360 100644 --- a/packages/core/src/session/execution/subagent-report.ts +++ b/packages/core/src/session/execution/subagent-report.ts @@ -8,7 +8,6 @@ import { SessionMessage } from "../message.js" import type { SessionSchema } from "../schema.js" import type { SessionStore } from "../store.js" import { SubagentCompletion } from "../subagent-completion.js" -import { SubagentMetadata } from "../subagent-metadata.js" export type Outcome = | { readonly type: "succeeded" } @@ -53,8 +52,6 @@ export const make = (deps: Deps) => { periods.delete(sessionID) } - const periodStartSeq = (sessionID: SessionSchema.ID) => Effect.succeed(periods.get(sessionID)?.startedSeq) - const resolveBody = Effect.fnUntraced(function* ( sessionID: SessionSchema.ID, outcome: Exclude, @@ -137,12 +134,6 @@ export const make = (deps: Deps) => { const period = periods.get(sessionID) periods.delete(sessionID) const jobState = yield* deps.jobs.prepareSubagentReport(sessionID, period?.boundGeneration) - if (jobState.mode === "foreground") { - return { - commit: () => deps.store.release(sessionID), - deliver: Effect.void, - } - } const initial = yield* deps.store.get(sessionID) if (!initial?.parentID && jobState.mode === "none") { return { @@ -164,7 +155,7 @@ export const make = (deps: Deps) => { yield* deps.store.release(sessionID) const child = yield* deps.store.get(sessionID) const parent = child?.parentID ? yield* deps.store.get(child.parentID) : undefined - if (!child?.parentID || !SubagentMetadata.notify(child.metadata) || !parent) { + if (!child?.parentID || !parent) { if (jobState.mode === "background") { yield* deps.jobs.deleteBackgroundRow(jobState.notificationID) box.postCommit = { type: "cleanup", notificationID: jobState.notificationID } @@ -207,5 +198,5 @@ export const make = (deps: Deps) => { return { commit, deliver } }) - return { started, clear, periodStartSeq, prepare } + return { started, clear, prepare } } diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index a4707bfe6ce4..a66839ca9e49 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -19,7 +19,6 @@ import { SessionBlob } from "./blob.js" import { SessionInboxTable, SessionMessageTable, SessionPartTable, SessionTable, type SessionPartData } from "./sql.js" import { SessionStored } from "./stored.js" import { InstructionEntry } from "./instruction-entry.js" -import { SubagentMetadata } from "./subagent-metadata.js" import type { SQLiteUpdateSetSource } from "drizzle-orm/sqlite-core/query-builders/update" import { Slug } from "../util/slug.js" import { FSUtil } from "@opencode/util/fs-util" @@ -175,7 +174,7 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( title: forkTitle(parent.title ?? undefined), agent: parent.agent, model: parent.model, - metadata: SubagentMetadata.inherit(parent.metadata ?? undefined) ?? null, + metadata: parent.metadata, permission: parent.permission, version: parent.version, cost: 0, diff --git a/packages/core/src/session/subagent-completion.ts b/packages/core/src/session/subagent-completion.ts index 6fdd83526998..dc88cfd93cc5 100644 --- a/packages/core/src/session/subagent-completion.ts +++ b/packages/core/src/session/subagent-completion.ts @@ -19,7 +19,6 @@ export interface SyntheticSession { readonly text: string readonly description?: string readonly metadata?: SessionSchema.Metadata - readonly resume?: boolean }) => Effect.Effect } @@ -77,7 +76,6 @@ export const deliver = Effect.fnUntraced(function* ( jobs: Pick, input: Pick & { recovery: Extract - resume?: boolean }, ) { if (input.status === "running") return @@ -97,7 +95,6 @@ export const deliver = Effect.fnUntraced(function* ( yield* sessions.synthetic({ ...(input.notificationID ? { id: input.notificationID } : {}), sessionID: recovery.parentSessionID, - ...(input.resume === false ? { resume: false } : {}), description: recovery.description, text: `\n${body}\n`, metadata: { source: "subagent", childID: recovery.childSessionID, agent: recovery.agent, state }, diff --git a/packages/core/src/session/subagent-job.ts b/packages/core/src/session/subagent-job.ts index bcea37ca8b97..3e0d40a982e2 100644 --- a/packages/core/src/session/subagent-job.ts +++ b/packages/core/src/session/subagent-job.ts @@ -3,86 +3,52 @@ export * as SubagentJob from "./subagent-job.js" import { Context, Effect, Layer } from "effect" import { Node } from "@opencode/util/effect/app-node" import type { LayerNode } from "@opencode/util/effect/layer-node" -import { Bus } from "../bus.js" -import { Database } from "../database/database.js" import { Job } from "../job.js" -import { SessionBackground } from "./background.js" import { SessionExecution } from "./execution.js" -import type { SessionSchema } from "./schema.js" -import { SessionStore } from "./store.js" -import { SubagentCompletion } from "./subagent-completion.js" type Recovery = Extract -export type StartOptions = { - readonly background?: boolean -} - export interface Interface { - readonly outstanding: (sessionID: SessionSchema.ID) => Effect.Effect - readonly start: (recovery: Recovery, options?: StartOptions) => Effect.Effect + readonly start: (recovery: Recovery) => Effect.Effect } export class Service extends Context.Service()("@opencode/SubagentJob") {} +export function start( + jobs: Job.Interface, + execution: SessionExecution.Interface, + recovery: Recovery, + notificationID?: Job.Background["notificationID"], +) { + const id = recovery.childSessionID + return jobs.start({ + id, + type: "subagent", + title: recovery.description, + metadata: notificationID === undefined ? {} : undefined, + recovery, + notificationID, + background: true, + run: execution.resume(id).pipe( + // Only an explicit caller cancel releases the child's claim. A server shutdown + // interrupts this job but must leave the child resumable on the next start. + Effect.onInterrupt(() => + jobs.isCancelled(id).pipe(Effect.flatMap((cancelled) => (cancelled ? execution.interrupt(id) : Effect.void))), + ), + Effect.as(""), + ), + }) +} + const make = Effect.gen(function* () { const execution = yield* SessionExecution.Service - const store = yield* SessionStore.Service const jobs = yield* Job.Service - const { db } = yield* Database.Service // Jobs outlive the plugin that launched them. Fork with the global context too, rather // than retaining the caller's location. const context = yield* Effect.context() - const outstanding = (sessionID: SessionSchema.ID) => - Effect.gen(function* () { - return yield* SessionBackground.outstanding(jobs, store, sessionID, yield* execution.active) - }) - return Service.of({ - outstanding, - start: (recovery, options) => - jobs - .start({ - id: recovery.childSessionID, - type: "subagent", - title: recovery.description, - metadata: {}, - recovery, - background: options?.background, - run: Effect.gen(function* () { - const resume = execution.resume(recovery.childSessionID).pipe( - // Only an explicit caller cancel releases the child's claim. A server shutdown - // interrupts this job but must leave the child resumable on the next start. - Effect.onInterrupt(() => - jobs - .isCancelled(recovery.childSessionID) - .pipe( - Effect.flatMap((cancelled) => - cancelled ? execution.interrupt(recovery.childSessionID) : Effect.void, - ), - ), - ), - ) - if (options?.background) return yield* resume.pipe(Effect.as("")) - // A joining period already owns its boundary; otherwise the child was admitted but not - // resumed, so the latest durable sequence precedes everything this period will write. - const startedSeq = - (yield* execution.periodStartSeq(recovery.childSessionID)) ?? - (yield* Bus.latestSequence(db, recovery.childSessionID)) - yield* resume - const assistant = yield* store.lastAssistantAfter({ - sessionID: recovery.childSessionID, - afterSeq: startedSeq, - }) - return SubagentCompletion.formatBody( - SubagentCompletion.text(assistant), - recovery.childSessionID, - yield* outstanding(recovery.childSessionID), - ) - }), - }) - .pipe(Effect.setContext(context)), + start: (recovery) => start(jobs, execution, recovery).pipe(Effect.setContext(context)), }) }) @@ -91,5 +57,5 @@ export const layer = Layer.effect(Service, make) export const node: LayerNode.Provider = Node.makeGlobalNode({ service: Service, layer, - deps: [SessionExecution.node, SessionStore.node, Database.node, Job.node], + deps: [SessionExecution.node, Job.node], }) diff --git a/packages/core/src/session/subagent-metadata.ts b/packages/core/src/session/subagent-metadata.ts deleted file mode 100644 index 897f4af680de..000000000000 --- a/packages/core/src/session/subagent-metadata.ts +++ /dev/null @@ -1,52 +0,0 @@ -export * as SubagentMetadata from "./subagent-metadata.js" - -import type { SessionSchema } from "./schema.js" - -/** Per-link switch for reporting a subagent's idle transition to its parent. */ -export const KEY = "subagent.notify" - -/** Absence means loud: only an explicit `false` silences the link. */ -export function notify(metadata: SessionSchema.Metadata | undefined): boolean { - return metadata?.[KEY] !== false -} - -/** - * Strips the per-link switch when metadata moves to a child or fork. Host - * annotations belong to the family, but a silent link must not silence the - * sessions created beneath it. - */ -export function inherit(metadata: SessionSchema.Metadata | undefined): SessionSchema.Metadata | undefined { - if (metadata === undefined || !Object.hasOwn(metadata, KEY)) return metadata - const { [KEY]: _notify, ...rest } = metadata - return Object.keys(rest).length === 0 ? undefined : rest -} - -/** Writes the switch, keeping default-loud sessions free of redundant keys. */ -export function apply( - metadata: SessionSchema.Metadata | undefined, - value: boolean, -): SessionSchema.Metadata | undefined { - if (value === false) return { ...metadata, [KEY]: false } - return inherit(metadata) -} - -/** Metadata for a child created from `metadata` with the requested link state. */ -export function withNotify( - metadata: SessionSchema.Metadata | undefined, - value: boolean, -): SessionSchema.Metadata | undefined { - return apply(inherit(metadata), value) -} - -/** - * Metadata to persist with `sessions.setMetadata` on an existing session. - * `undefined` means the requested state already holds, so the caller can skip - * the write; `{}` clears the last key. - */ -export function update( - metadata: SessionSchema.Metadata | undefined, - value: boolean, -): SessionSchema.Metadata | undefined { - if (notify(metadata) === value) return undefined - return apply(metadata, value) ?? {} -} diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index 8359d0628ec1..46d5d5167366 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -141,8 +141,8 @@ type Ended = { * here; callers (e.g. `ShellTool`) own that association and store the shell ID. * * Local commands run in the process daemon when it is available (`Daemon`), so they outlive a planned server - * restart: the next server takes them back. Remote workspaces, Windows and an unavailable daemon keep spawning - * them from the server. + * restart: the next server takes them back. Remote workspaces and an unavailable daemon keep spawning them from + * the server. */ export interface Interface { readonly create: ( @@ -615,12 +615,9 @@ const layer = () => // Commands this server spawned for the Location; daemon commands live in `runs`, owned by the server. const commands = new Map() const exitOrder: Shell.ID[] = [] - // Remote workspaces and Windows keep spawning commands from the server. Taken back before the service is - // returned, so session restart recovery sees them. + // Take local commands back before returning the service so session restart recovery sees them. const runs = - location.workspaceID === undefined && process.platform !== "win32" && PersistentPty.available - ? yield* daemon.at(location) - : undefined + location.workspaceID === undefined && PersistentPty.available ? yield* daemon.at(location) : undefined const outputDir = path.join(global.data, DIRECTORY, location.project.id) const { mkdir, unlink, stat } = yield* Effect.promise(() => import("fs/promises")) diff --git a/packages/core/src/tool-output.ts b/packages/core/src/tool-output.ts index f9ec06fe93c9..c5551b8eabf9 100644 --- a/packages/core/src/tool-output.ts +++ b/packages/core/src/tool-output.ts @@ -75,48 +75,56 @@ const layer = Layer.effect( const truncate = Effect.fnUntraced(function* (result: Result) { if (result.metadata?.truncated !== undefined) return result const content = result.content - const text = content.flatMap((item) => (item.type === "text" ? [item.text] : [])).join("\n") + // A line break joins text parts unless the text before already ends in one. + const text = content.reduce( + (joined, item) => + item.type !== "text" + ? joined + : joined === "" || joined.endsWith("\n") + ? joined + item.text + : `${joined}\n${item.text}`, + "", + ) const limits = state.get() - const lines = text.split("\n") - if (text.endsWith("\n")) lines.pop() - const totalBytes = Buffer.byteLength(text, "utf-8") - if (lines.length <= limits.maxLines && totalBytes <= limits.maxBytes) + const totalLines = countLines(text) + if (totalLines <= limits.maxLines && Buffer.byteLength(text, "utf-8") <= limits.maxBytes) return { ...result, metadata: { ...result.metadata, truncated: false } } - const kept: string[] = [] - let bytes = 0 - for (const line of lines.slice(0, limits.maxLines)) { - const size = Buffer.byteLength(line, "utf-8") + (kept.length > 0 ? 1 : 0) - if (bytes + size > limits.maxBytes) break - kept.push(line) - bytes += size - } + // Cut once, at the line or byte limit, whichever comes first, so a line too long for the space left shows its + // start. The preview never ends on a line break. + const end = Math.min(afterLines(text, limits.maxLines), byteBoundary(text, limits.maxBytes)) + const shown = text.slice(0, text.endsWith("\r\n", end) ? end - 2 : text.endsWith("\n", end) ? end - 1 : end) const file = path.join(directory, fileName()) const failure = yield* fs.ensureDir(directory).pipe( Effect.andThen(fs.writeFileString(file, text)), Effect.as(undefined), Effect.catch((error) => - Effect.logWarning("failed to save full tool output", { file, cause: error }).pipe( - Effect.as(describe(error)), - ), + Effect.logWarning("failed to save full tool output", { file, cause: error }).pipe(Effect.as(describe(error))), ), ) - const shown = kept.length > 0 ? `lines 1-${kept.length}` : "0 lines" - const marker = `[showing ${shown} of ${lines.length}; ${ + // Counted before the final line break is stripped, so a blank last line still counts. + const shownLines = countLines(text.slice(0, end)) + const lastLineCut = + shownLines > 0 && + shown.length < text.length && + !text.startsWith("\n", shown.length) && + !text.startsWith("\r\n", shown.length) + const range = shownLines === 0 ? "0 lines" : `lines 1-${shownLines}` + const marker = `[showing ${range} of ${totalLines}${lastLineCut ? " (last line cut)" : ""}; ${ failure === undefined ? `full output saved to ${file}` : `full output could not be saved: ${failure}` }]` const bounded: Tool.Content[] = [] - let remaining = kept.join("\n").length - let seenText = false + let remaining = shown.length + let separator = false let marked = false for (const item of content) { if (item.type === "file") { bounded.push(item) continue } - if (seenText && remaining > 0) remaining-- - seenText = true - if (remaining >= item.text.length) { + if (separator && remaining > 0) remaining-- + separator = item.text !== "" && !item.text.endsWith("\n") + if (!marked && remaining >= item.text.length) { bounded.push(item) remaining -= item.text.length continue @@ -172,3 +180,41 @@ export const node = makeLocationNode({ layer, deps: [FSUtil.node, Global.node, cleanupNode], }) + +/** How many lines `text` has, not counting an empty one after a final line break. Counts without splitting. */ +function countLines(text: string) { + if (text === "") return 0 + let count = 1 + for (let index = text.indexOf("\n"); index !== -1 && index < text.length - 1; index = text.indexOf("\n", index + 1)) + count++ + return count +} + +/** Where the line after the first `count` lines starts, or the end of `text`. */ +function afterLines(text: string, count: number) { + let index = 0 + for (let line = 0; line < count; line++) { + const next = text.indexOf("\n", index) + if (next === -1) return text.length + index = next + 1 + } + return index +} + +const encoder = new TextEncoder() +const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" }) + +/** The longest start of `text` that fits in `budget` UTF-8 bytes without splitting a character, emoji included. */ +function byteBoundary(text: string, budget: number) { + // encodeInto only encodes what fits in the buffer, and stops at a whole code point. + const index = encoder.encodeInto(text, new Uint8Array(Math.max(0, budget))).read + if (index === text.length || index === 0) return index + const before = text.charCodeAt(index - 1) + const after = text.charCodeAt(index) + // Two ASCII characters always have a boundary between them, except the two halves of \r\n. + if (before < 0x80 && after < 0x80) return before === 13 && after === 10 ? index - 1 : index + // Otherwise back off to the start of the grapheme the cut is in. A line break always ends one, so segmenting from the + // start of the line keeps flag pairs and long emoji sequences exact; one code point past the cut gives the context. + const start = text.lastIndexOf("\n", index - 1) + 1 + return start + (graphemes.segment(text.slice(start, index + 2)).containing(index - start)?.index ?? index - start) +} diff --git a/packages/core/src/tool/plugin/image-generate.ts b/packages/core/src/tool/plugin/image-generate.ts index e03d51f23f52..726e35c9b395 100644 --- a/packages/core/src/tool/plugin/image-generate.ts +++ b/packages/core/src/tool/plugin/image-generate.ts @@ -345,9 +345,9 @@ export const Plugin = { title: input.prompt, metadata: { sessionID: context.sessionID, path: stem, model: ref }, recovery: { kind: "image", sessionID: context.sessionID, path: stem, model: ref }, + background: true, run, }) - yield* jobs.background(id) yield* notifyWhenDone({ sessionID: context.sessionID, id, notificationID, file: stem }) return { output: { id, path: stem, model: ref }, @@ -359,9 +359,7 @@ export const Plugin = { ].join("\n"), metadata: { path: stem, model: ref, jobID: id }, } - }).pipe( - Effect.mapError(toolFailure("Unable to generate image")), - ), + }).pipe(Effect.mapError(toolFailure("Unable to generate image"))), }) }) .pipe(Effect.orDie) diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 584ba46af650..a7f215ca210d 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -122,7 +122,7 @@ const backgroundResult = (info: ShellResult.Result["info"], timeout?: number) => // Tells the session how a background command ended, once its job settles. const notify = Effect.fnUntraced(function* ( - sessions: Session.Interface, + sessions: Pick, jobs: Job.Interface, input: { readonly sessionID: SessionSchema.ID @@ -130,15 +130,12 @@ const notify = Effect.fnUntraced(function* ( readonly shellID: string readonly command: string readonly settled: Deferred.Deferred - // Read at delivery; `false` admits the notice without waking the session. - readonly resume?: () => false | undefined }, ) { const info = (yield* jobs.wait({ id: input.id })).info if (!info || info.status === "running") return const output = info.status === "completed" ? yield* Deferred.await(input.settled) : undefined const text = output ? (info.output ?? "") : info.status === "error" ? (info.error ?? "Command failed") : "Cancelled" - const resume = input.resume?.() // A session deleted while its command ran has no one left to tell. yield* sessions .synthetic({ @@ -153,7 +150,6 @@ const notify = Effect.fnUntraced(function* ( text, output, }), - ...(resume === false ? { resume } : {}), }) .pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void)) if (info.notificationID) yield* jobs.completeBackground(info.notificationID) @@ -166,6 +162,7 @@ const startJob = Effect.fnUntraced(function* ( input: { readonly sessionID: SessionSchema.ID readonly info: ShellSchema.Info + readonly background?: boolean readonly notificationID?: SessionMessage.ID readonly timeout?: () => number }, @@ -185,6 +182,7 @@ const startJob = Effect.fnUntraced(function* ( command: info.command, }, ...(input.notificationID ? { notificationID: input.notificationID } : {}), + background: input.background, run: Effect.gen(function* () { const result = yield* shell.result(info) if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id }) @@ -225,22 +223,19 @@ export const backgroundToolResult = (info: ShellSchema.Info) => { export const reattach = Effect.fnUntraced(function* (input: { readonly shell: Shell.Interface readonly jobs: Job.Interface - readonly sessions: Session.Interface + readonly sessions: Pick readonly sessionID: SessionSchema.ID readonly info: ShellSchema.Info // The job's existing durable row, if the previous server had backgrounded it. readonly notificationID?: SessionMessage.ID - readonly resume?: () => false | undefined }) { - const { job, settled } = yield* startJob(input.jobs, input.shell, input) - yield* input.jobs.background(job.id) + const { job, settled } = yield* startJob(input.jobs, input.shell, { ...input, background: true }) const notifying = notify(input.sessions, input.jobs, { sessionID: input.sessionID, id: job.id, shellID: input.info.id, command: input.info.command, settled, - resume: input.resume, }) const current = yield* input.shell.get(input.info.id).pipe(Effect.option) if (Option.isSome(current) && current.value.status !== "running") diff --git a/packages/core/src/tool/plugin/subagent.ts b/packages/core/src/tool/plugin/subagent.ts index ad4b57c9ff0b..b8008972372f 100644 --- a/packages/core/src/tool/plugin/subagent.ts +++ b/packages/core/src/tool/plugin/subagent.ts @@ -12,24 +12,20 @@ import { Model } from "../../model.js" import { Permission } from "../../permission.js" import { Session } from "../../session.js" import { SessionSchema } from "../../session/schema.js" -import { SubagentCompletion } from "../../session/subagent-completion.js" import { SubagentJob } from "../../session/subagent-job.js" -import { SubagentMetadata } from "../../session/subagent-metadata.js" import { SubagentOutput } from "../../session/subagent-output.js" export const name = "subagent" -const backgroundResult = (sessionID: SessionSchema.ID, notify: boolean) => ({ +const backgroundResult = (sessionID: SessionSchema.ID) => ({ sessionID, status: "running" as const, - output: notify - ? [ - `The subagent is working in the background (sessionID: ${sessionID}). You will be notified automatically when it finishes.`, - "DO NOT sleep, poll for progress, ask the subagent for status, or duplicate this subagent's work; avoid working with the same files or topics it is using.", - "Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.", - "To send it follow-ups or change its instructions while it runs, call subagent again with this sessionID.", - ].join("\n") - : `The subagent is working in the background (sessionID: ${sessionID}) and will not notify you when it finishes. To check on it, call the subagent tool with this sessionID or read the session.`, + output: [ + `The subagent is working in the background (sessionID: ${sessionID}). You will receive a message when it goes idle, and again after each later round of work.`, + "DO NOT sleep, poll for progress, ask the subagent for status, or duplicate this subagent's work; avoid working with the same files or topics it is using.", + "Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.", + "To send it follow-ups or change its instructions while it runs, call subagent again with this sessionID.", + ].join("\n"), }) export const Input = Schema.Struct({ @@ -46,32 +42,23 @@ export const Input = Schema.Struct({ sessionID: Schema.optionalKey(SessionSchema.ID).annotate({ description: "Send a follow-up to an existing subagent, running or finished. Omit to start a new one.", }), - background: Schema.optionalKey(Schema.Boolean).annotate({ - description: - "Run the subagent in the background and return immediately. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress.", - }), output: Schema.optionalKey(Schema.Array(SubagentOutput.Field)).annotate({ description: - "Fields you need back from the subagent. Set this when you will act on the answer rather than read it: the subagent is told to end with a JSON object carrying exactly these fields, and the call fails if it does not, instead of handing you prose to guess at.", - }), - notify: Schema.optionalKey(Schema.Boolean).annotate({ - description: - "Send you a `` message each time this subagent goes idle. Defaults to true for new subagents. On follow-ups (sessionID), keeps the subagent's current setting unless you pass it.", + "Fields you need back from the subagent. Set this when you will act on the answer rather than read it: the subagent is told to end with a JSON object carrying exactly these fields, and its message reports an error with what it said if it does not, instead of handing you prose to guess at.", }), }) export const Output = Schema.Struct({ sessionID: SessionSchema.ID, - status: Schema.Literals(["completed", "running"]), + status: Schema.Literal("running"), output: Schema.String, }) export const description = [ "Spawns an agent in a child session to work on the specified task.", - "The output includes a sessionID you can pass back later to continue that specific conversation with the subagent.", + "Subagents always run in the background: the call returns immediately with a sessionID, and you receive a `` message each time the child goes idle, including after later work.", + "Keep working on non-overlapping tasks, or briefly tell the user what you launched and end your response. Do not sleep, poll for progress, or ask the child for status.", "New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.", - "Foreground (default) runs the subagent to completion and returns its final response.", - "Background mode (background=true) launches it asynchronously and returns immediately; you are notified when it finishes.", - "Use background only for independent work that can run while you continue elsewhere.", + "Pass the returned sessionID to continue that specific child conversation. A follow-up to a running child joins its current run.", ].join("\n") export const parallelName = "subagent_parallel" @@ -94,18 +81,18 @@ export const ParallelOutput = Schema.Struct({ Schema.Struct({ description: Schema.String, sessionID: Schema.optionalKey(SessionSchema.ID), - state: Schema.Literals(["completed", "running", "error"]), + state: Schema.Literals(["running", "error"]), output: Schema.String, }), ), }) export const parallelDescription = [ - `Runs 2-${PARALLEL_LIMIT} independent subtasks at once, each in its own subagent session, waits for all of them, and returns every outcome.`, + `Starts 2-${PARALLEL_LIMIT} independent subtasks at once, each in its own subagent session running in the background, and returns their sessionIDs. Each one sends you a message when it goes idle.`, `Use it instead of ${name} when a task splits into parts that do not depend on each other: the wall-clock time is roughly the longest subtask instead of the sum.`, "Each subtask starts with a fresh context, so give each a self-contained prompt that says exactly what to do and what to return.", "Do not run subtasks that write to the same files: parallel edits to shared files conflict.", - "Each outcome is completed, running (moved to the background; you are notified when it finishes) or error, which carries its failure in place of the output and the sessionID to continue it when there is one.", + "Each outcome is running, or error when the subtask could not be started; the error carries its failure in place of the output and the sessionID to continue it when there is one.", "Set a subtask's output to the fields you need back when you will act on its answer: that is what makes several answers integrable side by side.", ].join("\n") @@ -222,13 +209,9 @@ export const Plugin = { if (existing !== undefined) { const switched = existing.agent !== agent.id const model = override ?? (switched ? agent.model : undefined) - // Omitted notify keeps the child's current link state; only an explicit value writes. - const metadata = - input.notify === undefined ? undefined : SubagentMetadata.update(existing.metadata, input.notify) yield* Effect.all([ switched ? sessions.switchAgent({ sessionID: existing.id, agent: agent.id }) : Effect.void, model === undefined ? Effect.void : sessions.switchModel({ sessionID: existing.id, model }), - metadata === undefined ? Effect.void : sessions.setMetadata({ sessionID: existing.id, metadata }), ]).pipe( Effect.mapError( (error) => new ToolFailure({ message: `Failed to switch subagent session: ${existing.id}`, error }), @@ -245,7 +228,6 @@ export const Plugin = { title: input.description, agent: agent.id, model, - metadata: SubagentMetadata.withNotify(parent.metadata, input.notify !== false), }) .pipe( Effect.mapError( @@ -253,8 +235,6 @@ export const Plugin = { ), )) - const background = input.background === true - const notify = input.notify ?? SubagentMetadata.notify(child.metadata) // A child that is not draining yet must be admitted without waking: the job's resume // owns the start, so the period cannot run before its boundary is registered. const running = @@ -282,46 +262,9 @@ export const Plugin = { description: input.description, ...(input.output?.length ? { output: input.output } : {}), } - yield* subagents.start(recovery, { background }) - - if (background) return backgroundResult(child.id, notify) - - const result = yield* jobs.block({ id: child.id, sessionID: context.sessionID }).pipe( - Effect.onInterrupt(() => - Effect.all([sessions.interrupt(child.id), jobs.cancel(child.id)], { - discard: true, - }), - ), - ) - if (result?.type === "backgrounded") return backgroundResult(child.id, notify) - // Failure surfaces keep the sessionID visible so the model can continue the child. - if (result?.info.status === "error") - return yield* new ToolFailure({ - message: SubagentCompletion.formatBody( - `Subagent failed (sessionID: ${child.id}): ${result.info.error ?? "unknown error"}`, - child.id, - yield* subagents.outstanding(child.id), - ), - }) - if (result?.info.status === "cancelled") - return yield* new ToolFailure({ - message: SubagentCompletion.formatBody( - `Subagent cancelled (sessionID: ${child.id})`, - child.id, - yield* subagents.outstanding(child.id), - ), - }) - const checked = SubagentCompletion.declared( - result?.info.output ?? SubagentCompletion.NO_TEXT, - input.output, - child.id, - ) - if (!checked.ok) return yield* new ToolFailure({ message: checked.message }) - return { - sessionID: child.id, - status: "completed" as const, - output: checked.text, - } + // The declared fields travel with the job and are checked when the answer is delivered. + yield* subagents.start(recovery) + return backgroundResult(child.id) }) yield* ctx.tool @@ -340,10 +283,7 @@ export const Plugin = { }).pipe( Effect.map((output) => ({ output, - content: - output.status === "completed" - ? `\n${output.output}\n` - : output.output, + content: output.output, metadata: { sessionID: output.sessionID, status: output.status }, })), ), diff --git a/packages/core/src/tool/read-filesystem.ts b/packages/core/src/tool/read-filesystem.ts index 7fe5d34b51f4..11930dcba8a5 100644 --- a/packages/core/src/tool/read-filesystem.ts +++ b/packages/core/src/tool/read-filesystem.ts @@ -17,7 +17,8 @@ export const MAX_MEDIA_INGEST_BYTES = 20 * 1024 * 1024 const FIRST_CHUNK = 256 * 1024 const TAIL_LINES = 100 const MAX_LINE_LENGTH = 2_000 -const TREE_BASE = 6 +// Enough UTF-8 bytes for the clamped prefix, including a BOM and a partial code point at the end. +const LINE_BYTES = 4 * (MAX_LINE_LENGTH + 1) const MAX_LINE_SUFFIX = `... (line truncated to ${MAX_LINE_LENGTH} chars)` export const MEDIA_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"]) @@ -123,8 +124,7 @@ export const read = Effect.fn("ReadTool.read")(function* ( const first = yield* files.read(input, { offset: 0, length: FIRST_CHUNK }).pipe( Effect.catchTag("Environment.WrongKind", (error) => Effect.gen(function* () { - if (error.actual !== "directory") - return yield* new PathKindError({ resource, expected: "a file or directory" }) + if (error.actual !== "directory") return yield* new PathKindError({ resource, expected: "a file or directory" }) if (page.offset !== undefined && page.offset < 0) return yield* new DirectoryOffsetError({ resource }) return yield* files.list(input).pipe( Effect.map((entries) => list(entries, page, virtual ? "/" : path.sep)), @@ -165,70 +165,7 @@ export const read = Effect.fn("ReadTool.read")(function* ( } } - if (first.bytes.length >= first.info.size) return yield* completePage(input, resource, first.bytes, page) - - const offset = page.offset || 1 - const limit = Math.min(page.limit || MAX_READ_LINES, MAX_READ_LINES) - const leaves = [textLeaf(first.bytes)] - let bytes = first.bytes.length - let lines = leaves[0].summary.lines - let ended = false - while (true) { - const eof = ended || bytes >= first.info.size - const total = lineCount(lines, leaves.at(-1)?.bytes.at(-1)) - if (eof && offset > total) { - const skipped = Math.max(0, total - Math.min(page.limit || TAIL_LINES, TAIL_LINES)) - // Decode from the newline ending the last skipped line, so a byte order mark - // starting the tail stays content. That empty first line is never in the tail. - const tree = textTree(leaves) - const tail = textPage( - textSlice(leaves, Math.max(0, textOffset(tree, skipped) - 1), tree.summary.bytes), - true, - page, - ) - if (tail === undefined) return yield* Effect.die("Read page did not settle for a complete file") - return yield* makeTextPage( - input, - resource, - { ...tail, offset: Math.max(0, skipped - 1) + tail.offset }, - leaves.some((leaf) => leaf.bytes.includes(0)), - ) - } - if (eof || (offset > 0 && lines >= offset - 1)) { - // A negative offset only resolves at EOF, counting back from the last line. - const from = offset < 0 ? Math.max(1, total + offset + 1) : offset - const tree = textTree(leaves) - const start = textOffset(tree, from - 1) - // Decode only the requested lines plus one byte, enough to tell whether more follow. - const end = Math.min(tree.summary.bytes, textOffset(tree, from - 1 + limit) + 1) - const result = textPage(textSlice(leaves, start, end), eof && end === tree.summary.bytes, { limit }) - if (result !== undefined) { - const translated = { - ...result, - offset: from, - ...(result.next === undefined ? { next: undefined } : { next: from + result.next - 1 }), - } - const consumed = start + result.consumed - let checked = 0 - const binary = leaves.some((leaf) => { - const length = Math.min(leaf.summary.bytes, consumed - checked) - checked += leaf.summary.bytes - return length > 0 && leaf.bytes.subarray(0, length).includes(0) - }) - return yield* makeTextPage(input, resource, translated, binary) - } - } - - const next = yield* readFile(files, input, resource, { offset: bytes, length: FIRST_CHUNK }) - if (next.bytes.length === 0) { - ended = true - continue - } - const leaf = textLeaf(next.bytes) - leaves.push(leaf) - bytes += leaf.summary.bytes - lines += leaf.summary.lines - } + return yield* textPage(files, input, resource, first, page) }) const readFile = ( @@ -243,36 +180,155 @@ const readFile = ( Effect.catchTag("Environment.WrongKind", () => Effect.fail(new PathKindError({ resource, expected: "a file" }))), ) -const completePage = Effect.fnUntraced(function* ( +// The first line ending in a chunk may have started many chunks earlier. +type Checkpoint = { byte: number; length: number; firstLine: number; start: number; lastLine: number } + +const textPage = Effect.fnUntraced(function* ( + files: Files, input: AbsolutePath, resource: string, - bytes: Uint8Array, + first: { bytes: Uint8Array; info: { size: number } }, page: PageInput, ) { - const total = lineCount(textLeaf(bytes).summary.lines, bytes.at(-1)) - const result = textPage( - bytes, - true, - page.offset !== undefined && page.offset < 0 ? { ...page, offset: Math.max(1, total + page.offset + 1) } : page, - ) - if (result === undefined) return yield* Effect.die("Read page did not settle for a complete file") - return yield* makeTextPage(input, resource, result, bytes.subarray(0, result.consumed).includes(0)) -}) + const requested = page.offset || 1 + const limit = Math.min(page.limit || MAX_READ_LINES, MAX_READ_LINES) + const checkpoints: Checkpoint[] = [] + const entries: string[] = [] + let size = 0 + let from = requested + let tail = false + let consumed = 0 + let next: number | undefined + let firstNul = Infinity + const decoder = new TextDecoder("utf-8", { ignoreBOM: true }) + + const range = (offset: number, length: number) => readFile(files, input, resource, { offset, length }) + const reread = Effect.fnUntraced(function* (offset: number, length: number) { + const { bytes } = yield* range(offset, length) + if (bytes.length === length) return bytes + const result = new Uint8Array(length) + result.set(bytes) + let filled = bytes.length + while (filled < length) { + const more = yield* range(offset + filled, length - filled) + if (more.bytes.length === 0) break + result.set(more.bytes, filled) + filled += more.bytes.length + } + return result.subarray(0, filled) + }) -const makeTextPage = Effect.fnUntraced(function* ( - input: AbsolutePath, - resource: string, - result: NonNullable>, - binary: boolean, -) { - if (binary) return yield* new BinaryFileError({ resource }) + // Select complete lines in this chunk. Only a split line's displayable prefix ever needs a separate read. + const collect = Effect.fnUntraced(function* (point: Checkpoint, chunk: Uint8Array) { + let start = point.start + let local = Math.max(0, start - point.byte) + for (let line = point.firstLine; line < from && local < chunk.length; local++) { + if (chunk[local] !== 10) continue + line++ + start = point.byte + local + 1 + } + for (let line = Math.max(point.firstLine, from); line <= point.lastLine; line++) { + if (!tail && (entries.length >= limit || size >= MAX_READ_BYTES)) { + next = line + return + } + const lf = chunk.indexOf(10, local) + const end = point.byte + (lf < 0 ? chunk.length : lf) + const length = Math.min(LINE_BYTES, end - start) + const bytes = + start >= point.byte + ? chunk.subarray(start - point.byte, start - point.byte + length) + : start + length <= first.bytes.length + ? first.bytes.subarray(start, start + length) + : yield* reread(start, length) + let text = decoder.decode(bytes) + // Single-chunk pages decode from byte zero. Streamed pages decode from the selected line, + // except a past-end tail, whose embedded BOM remains content. + if ( + text.startsWith("\uFEFF") && + (start === 0 || (!tail && line === from && first.bytes.length < first.info.size)) + ) + text = text.slice(1) + text = clampLine(text.endsWith("\r") ? text.slice(0, -1) : text) + const cost = Buffer.byteLength(text) + (entries.length > 0 ? 1 : 0) + if (!tail && size + cost > MAX_READ_BYTES) { + next = line + return + } + entries.push(text) + size += cost + consumed = end + Number(lf >= 0) + local = lf + 1 + start = end + 1 + } + }) + + let byte = 0 + let total = 0 + let start = 0 + let chunk = first.bytes + let lastByte = 0 + while (chunk.length > 0) { + lastByte = byte + if (firstNul === Infinity) { + const nul = chunk.indexOf(0) + if (nul >= 0) firstNul = byte + nul + } + let count = 0 + for (let i = 0; i < chunk.length; i++) count += Number(chunk[i] === 10) + if (count > 0) { + const point = { byte, length: chunk.length, firstLine: total + 1, start, lastLine: total + count } + checkpoints.push(point) + total += count + if (requested > 0 && total >= requested) yield* collect(point, chunk) + start = byte + chunk.lastIndexOf(10) + 1 + } + byte += chunk.length + // Any byte after a full page starts another line, even if that line has no newline for megabytes. + if (next === undefined && (entries.length >= limit || size >= MAX_READ_BYTES) && consumed < byte) + next = requested + entries.length + if (next !== undefined || byte >= first.info.size) break + const more = yield* range(byte, FIRST_CHUNK) + if (more.bytes.length === 0) break + chunk = more.bytes + } + + // EOF ends an unterminated line. A trailing newline already ended the last one. + if (next === undefined && start < byte) { + total++ + const point = { byte: lastByte, length: chunk.length, firstLine: total, start, lastLine: total } + checkpoints.push(point) + if (requested > 0 && total >= requested) yield* collect(point, chunk) + } + if (requested < 0 || requested > total) { + tail = requested > total + from = Math.max(1, total + 1 + (tail ? -Math.min(page.limit || TAIL_LINES, TAIL_LINES) : requested)) + // Each checkpoint covers disjoint line numbers. Seek to the chunk ending the first selected line; + // chunks in the middle of a long line have no checkpoint and are never reread. + for (const point of checkpoints) { + if (point.lastLine < from) continue + const bytes = + point.byte === 0 ? first.bytes : point.byte === lastByte ? chunk : yield* reread(point.byte, point.length) + yield* collect(point, bytes) + if (next !== undefined) break + } + if (tail) { + while (size > MAX_READ_BYTES) { + size -= Buffer.byteLength(entries.shift() ?? "") + 1 + from++ + } + consumed = byte + } + } + + if (firstNul < consumed) return yield* new BinaryFileError({ resource }) return new TextPage({ type: "text-page", - content: result.entries.join("\n"), + content: entries.join("\n"), mime: mimeType(input), - offset: result.offset, - truncated: result.next !== undefined, - ...(result.next === undefined ? {} : { next: result.next }), + offset: from, + truncated: next !== undefined, + ...(next === undefined ? {} : { next }), }) }) @@ -309,51 +365,6 @@ const list = (items: ReadonlyArray, page: PageInput, sep = }) } -const textPage = (bytes: Uint8Array, eof: boolean, page: PageInput) => { - const offset = page.offset || 1 - const limit = Math.min(page.limit || MAX_READ_LINES, MAX_READ_LINES) - const decoded = new TextDecoder().decode(bytes) - const split = decoded.split("\n") - const complete = eof ? (split.at(-1) === "" ? split.slice(0, -1) : split) : split.slice(0, -1) - const available = complete.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line)) - - const entries: string[] = [] - let size = 0 - // An offset past the end returns the file's last lines that fit, ending at the last line. - if (eof && offset > Math.max(1, available.length)) { - for (const value of available.slice(-Math.min(page.limit || TAIL_LINES, TAIL_LINES)).toReversed()) { - const text = clampLine(value) - size += Buffer.byteLength(text, "utf-8") + (entries.length > 0 ? 1 : 0) - if (size > MAX_READ_BYTES) break - entries.unshift(text) - } - return { entries, offset: available.length - entries.length + 1, next: undefined, consumed: bytes.length } - } - let next: number | undefined - for (const [index, value] of available.slice(offset - 1).entries()) { - const line = offset + index - if (entries.length >= limit || size >= MAX_READ_BYTES) { - next = line - break - } - const text = clampLine(value) - const lineSize = Buffer.byteLength(text, "utf-8") + (entries.length > 0 ? 1 : 0) - if (size + lineSize > MAX_READ_BYTES) { - next = line - break - } - entries.push(text) - size += lineSize - } - if (next === undefined && entries.length >= limit && (!eof || offset - 1 + entries.length < available.length)) - next = offset + entries.length - if (!eof && next === undefined) return - - const consumedLines = next === undefined ? available.length : next - 1 - const consumed = consumedLines === 0 ? 0 : (nthNewline(bytes, consumedLines) ?? bytes.length) - return { entries, offset, next, consumed } -} - const clampLine = (line: string) => { if (line.length <= MAX_LINE_LENGTH) return line const code = line.charCodeAt(MAX_LINE_LENGTH - 1) @@ -361,84 +372,6 @@ const clampLine = (line: string) => { return line.slice(0, end) + MAX_LINE_SUFFIX } -// A trailing newline ends the last line instead of starting an empty one. -const lineCount = (newlines: number, last: number | undefined) => newlines + (last === undefined || last === 10 ? 0 : 1) - -type TextSummary = { readonly bytes: number; readonly lines: number } -// Request-local augmented rope. Subtree byte and newline weights locate a line -// like an order-statistic query without repeatedly decoding the accumulated text. -// https://doi.org/10.1002/spe.4380251203 -type TextNode = - | { readonly type: "leaf"; readonly bytes: Uint8Array; readonly summary: TextSummary } - | { readonly type: "branch"; readonly children: ReadonlyArray; readonly summary: TextSummary } - -const textLeaf = (bytes: Uint8Array): Extract => { - let lines = 0 - for (const byte of bytes) if (byte === 10) lines++ - return { type: "leaf", bytes, summary: { bytes: bytes.length, lines } } -} - -const textTree = (nodes: ReadonlyArray): TextNode => { - if (nodes.length === 1) return nodes[0] - return textTree( - Array.from({ length: Math.ceil(nodes.length / (TREE_BASE * 2)) }, (_, index) => { - const children = nodes.slice(index * TREE_BASE * 2, (index + 1) * TREE_BASE * 2) - return { - type: "branch" as const, - children, - summary: { - bytes: children.reduce((total, child) => total + child.summary.bytes, 0), - lines: children.reduce((total, child) => total + child.summary.lines, 0), - }, - } - }), - ) -} - -const textOffset = (tree: TextNode, newline: number) => { - if (newline === 0) return 0 - let node = tree - let remaining = newline - let offset = 0 - while (node.type === "branch") { - const child = node.children.find((candidate) => { - if (remaining <= candidate.summary.lines) return true - remaining -= candidate.summary.lines - offset += candidate.summary.bytes - return false - }) - if (!child) return tree.summary.bytes - node = child - } - const end = nthNewline(node.bytes, remaining) - return end === undefined ? tree.summary.bytes : offset + end -} - -const textSlice = ( - leaves: ReadonlyArray>, - start: number, - end: number, -) => { - let position = 0 - return Buffer.concat( - leaves.flatMap((leaf) => { - const leafStart = position - position += leaf.summary.bytes - if (position <= start || leafStart >= end) return [] - return [leaf.bytes.subarray(Math.max(0, start - leafStart), end - leafStart)] - }), - ) -} - -const nthNewline = (bytes: Uint8Array, count: number) => { - let found = 0 - for (const [index, byte] of bytes.entries()) { - if (byte !== 10) continue - found++ - if (found === count) return index + 1 - } -} - const layer = Layer.effect( Service, Effect.gen(function* () { diff --git a/packages/core/src/util/canonical-json.ts b/packages/core/src/util/canonical-json.ts new file mode 100644 index 000000000000..388db55eb92c --- /dev/null +++ b/packages/core/src/util/canonical-json.ts @@ -0,0 +1,11 @@ +import type { Schema } from "effect" + +export function canonicalJson(value: Schema.Json): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` + if (value !== null && typeof value === "object") + return `{${Object.entries(value) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`) + .join(",")}}` + return JSON.stringify(value) +} diff --git a/packages/core/test/fixture/mcp.ts b/packages/core/test/fixture/mcp.ts index 380dd1cfdd71..280259850d2d 100644 --- a/packages/core/test/fixture/mcp.ts +++ b/packages/core/test/fixture/mcp.ts @@ -25,6 +25,9 @@ export const emptyMcp = Mcp.Service.of({ resources: () => Effect.succeed(Mcp.ResourceCatalog.make({ resources: [], templates: [] })), readResource: () => Effect.undefined, events: () => Effect.undefined, + subscribe: () => Effect.die("unused Mcp.subscribe"), + unsubscribe: () => Effect.void, + subscriptions: () => Effect.succeed([]), }) export const emptyMcpLayer = Layer.succeed(Mcp.Service, emptyMcp) diff --git a/packages/core/test/generate.test.ts b/packages/core/test/generate.test.ts index 6b73476558f6..adbe8a5d3889 100644 --- a/packages/core/test/generate.test.ts +++ b/packages/core/test/generate.test.ts @@ -417,6 +417,14 @@ describe("image and decision generation", () => { request, Response.json({ model: "clef", answers: { photo: { type: "noul", noul: 0.9 } } }), ) + if (request.url === "https://gemini.test/v1beta/decisions") + return HttpClientResponse.fromWeb( + request, + Response.json({ + answers: { photo: { type: "noul", noul: 0.8, confidence: 0.8 } }, + usage: { total_input_tokens: 12, total_output_tokens: 0, total_tokens: 12 }, + }), + ) if (request.url === "https://openrouter.ai/api/v1/systemone") return HttpClientResponse.fromWeb( request, @@ -606,6 +614,34 @@ describe("image and decision generation", () => { }), ) + mediaIt.effect("routes a gemini-decisions catalog entry to the Google decisions entrypoint", () => + Effect.gen(function* () { + requests.length = 0 + const generate = yield* Generate.Service + const result = yield* generate.decisions({ + model: ref("decide-host", "decide-gemini"), + input: [ + { type: "text", text: "Is this a photo?" }, + { type: "file", data: "aW1hZ2U=", mime: "image/png" }, + ], + questions: [{ type: "predicate", name: "photo", instructions: "Is this a photo?" }], + }) + expect(requests[0]).toMatchObject({ + url: "https://gemini.test/v1beta/decisions", + body: { + model: "decide-gemini", + input: [ + { type: "text", text: "Is this a photo?" }, + { type: "image", mime_type: "image/png", data: "aW1hZ2U=" }, + ], + questions: { photo: { type: "noul", instructions: "Is this a photo?" } }, + }, + }) + expect(result.answers).toEqual([{ type: "predicate", name: "photo", probability: 0.8 }]) + expect(result.tokens).toEqual({ input: 12, output: 0 }) + }), + ) + mediaIt.effect("sends a variant's reasoning setting and maps provider rejections", () => Effect.gen(function* () { requests.length = 0 @@ -684,6 +720,15 @@ function decisionCatalog() { "decide-state": model("decide-state", { media_input: "state" }), "decide-unknown": model("decide-unknown", { media_input: "somewhere_new" }), "decide-override": model("decide-override", { media_input: "state" }), + "decide-gemini": { + ...model("decide-gemini"), + api: { + "gemini-decisions": { + base_url: "https://gemini.test/v1beta", + sdk: { opencodeai: "@opencode/ai/providers/google/decisions" }, + }, + }, + }, }, }, }), diff --git a/packages/core/test/instructions/index.test.ts b/packages/core/test/instructions/index.test.ts index 33c13c6fbdf5..11ec42329de2 100644 --- a/packages/core/test/instructions/index.test.ts +++ b/packages/core/test/instructions/index.test.ts @@ -180,9 +180,9 @@ describe("Instructions", () => { ) test("hashes objects independently of key order", () => { - expect(Instructions.hash({ a: 1, b: { x: true, y: false } })).toBe( - Instructions.hash({ b: { y: false, x: true }, a: 1 }), - ) + const hash = Instructions.Hash.make("21dc66ac9fce28900235d1cf33c48a7d131c80022dfa54990c7ef3070e926210") + expect(Instructions.hash({ a: 1, b: { x: true, y: false } })).toBe(hash) + expect(Instructions.hash({ b: { y: false, x: true }, a: 1 })).toBe(hash) }) test("renders sources in composition order", () => { diff --git a/packages/core/test/job.test.ts b/packages/core/test/job.test.ts index 7db1ff4e4554..b9679427857a 100644 --- a/packages/core/test/job.test.ts +++ b/packages/core/test/job.test.ts @@ -594,15 +594,15 @@ describe("Job", () => { type: "subagent", title: "Report work", recovery, + background: true, run: Deferred.await(latch).pipe(Effect.as("done")), }) - const background = yield* jobs.background(job.id) - if (!background?.notificationID) return yield* Effect.die("background marker missing") + if (!job.notificationID) return yield* Effect.die("background marker missing") expect(yield* jobs.currentGeneration(job.id)).toMatchObject({ running: true }) expect(yield* jobs.prepareSubagentReport(job.id)).toEqual({ mode: "background", - notificationID: background.notificationID, + notificationID: job.notificationID, recovery, startedAt: job.started_at, }) @@ -614,24 +614,22 @@ describe("Job", () => { yield* jobs.wait({ id: job.id }) // The settlement commit owns the terminal row while this generation is settling. // Settling must not overwrite it with a stale running-period value. - expect(yield* jobs.pendingBackground).toMatchObject([ - { notificationID: background.notificationID, status: "running" }, - ]) + expect(yield* jobs.pendingBackground).toMatchObject([{ notificationID: job.notificationID, status: "running" }]) yield* jobs.recordSubagentReport({ - notificationID: background.notificationID, + notificationID: job.notificationID, recovery, status: "completed", output: "done", startedAt: job.started_at, }) expect(yield* jobs.pendingBackground).toMatchObject([ - { notificationID: background.notificationID, status: "completed", output: "done" }, + { notificationID: job.notificationID, status: "completed", output: "done" }, ]) - yield* jobs.completeBackground(background.notificationID) + yield* jobs.completeBackground(job.notificationID) }), ) - it.live("refuses a late background handoff for settling foreground work and starts a fresh generation", () => + it.live("starts a fresh generation while the previous subagent report is settling", () => Effect.gen(function* () { const jobs = yield* Job.Service const latch = yield* Deferred.make() @@ -646,21 +644,22 @@ describe("Job", () => { id: recovery.childSessionID, type: "subagent", recovery, + background: true, run: Deferred.await(latch).pipe(Effect.as("old")), }) const generation = (yield* jobs.currentGeneration(job.id))?.generation if (generation === undefined) return yield* Effect.die("generation missing") const oldWait = yield* jobs.wait({ id: job.id }).pipe(Effect.forkChild({ startImmediately: true })) - expect(yield* jobs.prepareSubagentReport(job.id)).toEqual({ mode: "foreground" }) + expect(yield* jobs.prepareSubagentReport(job.id)).toMatchObject({ mode: "background" }) expect(yield* jobs.currentGeneration(job.id)).toEqual({ generation, running: false }) - expect(yield* jobs.background(job.id)).toBeUndefined() const replacementLatch = yield* Deferred.make() yield* jobs.start({ id: job.id, type: "subagent", recovery, + background: true, run: Deferred.await(replacementLatch), }) const current = yield* jobs.currentGeneration(job.id) @@ -680,40 +679,6 @@ describe("Job", () => { }), ) - it.live("keeps settling work out of a session-wide background handoff", () => - Effect.gen(function* () { - const jobs = yield* Job.Service - const parent = SessionSchema.ID.make("ses_settling_all") - const latch = yield* Deferred.make() - const first = yield* jobs.start({ - id: "job_settling_all_first", - type: "test", - run: Deferred.await(latch).pipe(Effect.as("first")), - }) - const second = yield* jobs.start({ - id: "job_settling_all_second", - type: "test", - run: Deferred.await(latch).pipe(Effect.as("second")), - }) - const scope = yield* Scope.Scope - const firstWait = yield* jobs - .block({ id: first.id, sessionID: parent }) - .pipe(Effect.forkIn(scope, { startImmediately: true })) - const secondWait = yield* jobs - .block({ id: second.id, sessionID: parent }) - .pipe(Effect.forkIn(scope, { startImmediately: true })) - - expect(yield* jobs.prepareSubagentReport(first.id)).toEqual({ mode: "foreground" }) - expect(yield* jobs.backgroundAll({ sessionID: parent })).toMatchObject([{ id: second.id }]) - expect(yield* jobs.get(first.id)).toMatchObject({ status: "running" }) - expect((yield* jobs.get(first.id))?.notificationID).toBeUndefined() - - yield* Deferred.succeed(latch, undefined) - expect(yield* Fiber.join(firstWait)).toMatchObject({ type: "finished", info: { id: first.id } }) - expect(yield* Fiber.join(secondWait)).toMatchObject({ type: "backgrounded", info: { id: second.id } }) - }), - ) - it.live("matches an external cancel to its busy period through the bound generation", () => Effect.gen(function* () { const jobs = yield* Job.Service @@ -728,6 +693,7 @@ describe("Job", () => { id: recovery.childSessionID, type: "subagent", recovery, + background: true, run: Effect.never, }) const generation = (yield* jobs.currentGeneration(job.id))?.generation @@ -736,8 +702,8 @@ describe("Job", () => { yield* jobs.cancel(job.id) expect(yield* jobs.get(job.id)).toMatchObject({ status: "cancelled" }) // The cancel consumed the live entry; its matching generation still belongs to this busy period. - expect(yield* jobs.prepareSubagentReport(job.id, generation)).toEqual({ mode: "foreground" }) expect(yield* jobs.prepareSubagentReport(job.id, generation - 1)).toEqual({ mode: "none" }) + expect(yield* jobs.prepareSubagentReport(job.id, generation)).toMatchObject({ mode: "background" }) expect(yield* jobs.prepareSubagentReport(job.id)).toEqual({ mode: "none" }) }), ) @@ -819,48 +785,6 @@ describe("Job", () => { }), ) - it.live("promotes joined foreground work to background while it is still live", () => - Effect.gen(function* () { - const jobs = yield* Job.Service - const parent = SessionSchema.ID.make("ses_promote_parent") - const recovery = { - kind: "subagent" as const, - parentSessionID: parent, - childSessionID: SessionSchema.ID.make("ses_promote_child"), - agent: "explore", - description: "Promote work", - } - const latch = yield* Deferred.make() - const foreground = yield* jobs.start({ - id: recovery.childSessionID, - type: "subagent", - recovery, - run: Deferred.await(latch).pipe(Effect.as("foreground")), - }) - const waiting = yield* jobs - .block({ id: foreground.id, sessionID: parent }) - .pipe(Effect.forkChild({ startImmediately: true })) - - const promoted = yield* jobs.start({ - id: foreground.id, - type: "subagent", - recovery, - background: true, - run: Effect.die("Joined work must not run twice"), - }) - expect(promoted.notificationID).toEqual(expect.any(String)) - expect(yield* Fiber.join(waiting)).toMatchObject({ type: "backgrounded", info: { id: foreground.id } }) - expect(yield* jobs.pendingBackground).toMatchObject([{ id: foreground.id, status: "running" }]) - - yield* Deferred.succeed(latch, undefined) - yield* jobs.wait({ id: foreground.id }) - const marker = (yield* jobs.pendingBackground)[0] - if (!marker) return yield* Effect.die("background marker missing") - expect(marker.status).toBe("completed") - yield* jobs.completeBackground(marker.notificationID) - }), - ) - it.live("distinguishes caller cancellation from teardown", () => Effect.gen(function* () { const jobs = yield* Job.Service diff --git a/packages/core/test/mcp-oauth.test.ts b/packages/core/test/mcp-oauth.test.ts index e9b17193abdb..9c179d1730f7 100644 --- a/packages/core/test/mcp-oauth.test.ts +++ b/packages/core/test/mcp-oauth.test.ts @@ -407,6 +407,28 @@ describe("MCP OAuth", () => { }) }) + test("redeems the code with the localhost redirect a server sent the browser back to", async () => { + const { server, registrations, tokenRequests } = authorizationServer({}) + const sent = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const { authorization, url } = yield* start(server) + const redirect = new URL(url.searchParams.get("redirect_uri")!) + redirect.searchParams.set("code", "accepted") + redirect.searchParams.set("state", url.searchParams.get("state")!) + // Clerk's consent page rewrites 127.0.0.1 to localhost; the browser reaches the same listener. + yield* Effect.promise(() => fetch(redirect, { headers: { host: `localhost:${redirect.port}` } })) + yield* authorization.callback + return redirect + }), + ), + ).finally(() => server.stop(true)) + expect(registrations[0]).toMatchObject({ + redirect_uris: [`http://127.0.0.1:${sent.port}/callback`, `http://localhost:${sent.port}/callback`], + }) + expect(tokenRequests[0]?.get("redirect_uri")).toBe(`http://localhost:${sent.port}/callback`) + }) + test("reuses the client registered by an earlier login", async () => { const { server, registrations } = authorizationServer({}) const previous = credential({ access: "a", refresh: "r", url: server.url.href }) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index bdd473ee8794..8718c6634a9b 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -1,7 +1,7 @@ import path from "node:path" import fs from "node:fs/promises" import os from "node:os" -import { describe, expect, test } from "bun:test" +import { describe, expect, spyOn, test } from "bun:test" import { Client, InMemoryTransport, @@ -49,6 +49,7 @@ import { McpResourceTools } from "@opencode/core/tool/plugin/mcp-resource" import { Tool } from "@opencode/core/tool" import { ToolOutput } from "@opencode/core/tool-output" import { + Clock, Context, Deferred, Effect, @@ -59,6 +60,7 @@ import { Logger, Option, PubSub, + Queue, Ref, Schedule, Schema, @@ -1573,9 +1575,7 @@ test("acknowledges completed MCP URL elicitations without returning internal con const result = yield* Fiber.join(call) expect(yield* forms.state(form.id)).toEqual({ status: "answered", answer: { elicitation: true } }) return result - }).pipe( - Effect.provide(resourceMcpLayer(server.url, (form) => recordForm(created, form))), - ) + }).pipe(Effect.provide(resourceMcpLayer(server.url, (form) => recordForm(created, form)))) expect(result.structured).toEqual({ action: "accept" }) }), @@ -1596,10 +1596,12 @@ test("cancels MCP elicitation forms when the server gives up on them", async () const { form } = yield* Deferred.await(created) yield* Fiber.await(call) // The server's cancellation and its tool error race; the form settles shortly after either. - const state = yield* forms.state(form.id).pipe( - Effect.repeat({ until: (state) => state.status !== "pending", schedule: Schedule.spaced("10 millis") }), - Effect.timeout("2 seconds"), - ) + const state = yield* forms + .state(form.id) + .pipe( + Effect.repeat({ until: (state) => state.status !== "pending", schedule: Schedule.spaced("10 millis") }), + Effect.timeout("2 seconds"), + ) expect(state.status).toBe("cancelled") }).pipe(Effect.provide(resourceMcpLayer(server.url, (form) => recordForm(created, form)))) }), @@ -3197,85 +3199,81 @@ for (const modern of [false, true]) { } for (const source of ["config", "organization"] as const) { - testEffect(Config.testLayer()).live( - `revokes and restores a connected MCP through ${source} policy`, - () => - Effect.gen(function* () { - const server = yield* resourceServer() - const config = yield* Config.Service - const test = yield* Config.Test - const updates = yield* PubSub.unbounded<{ readonly type: string }>() - const document = (effect: ConfigPolicy.Effect) => - new Document({ - type: "document", - info: new Info({ - mcp: new ConfigMCP.Info({ - servers: { resources: new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }) }, - }), - policies: [{ action: "mcp.use", resource: "*", effect }], - }), - }) - yield* test.setEntries([document("allow")]) - yield* Effect.gen(function* () { - const service = yield* Mcp.Service - expect(yield* settled(service)).toEqual({ status: "connected" }) - expect((yield* service.tools()).length).toBeGreaterThan(0) - if (source === "config") yield* test.setEntries([document("deny")]) - if (source === "organization") - yield* setOrganizationPolicy([{ action: "mcp.use", resource: "*", effect: "deny" }]) - yield* PubSub.publish(updates, { type: Event.Updated.type }) - yield* service.servers().pipe( - Effect.filterOrFail( - (servers) => servers.length === 0, - () => new Error("MCP policy was not applied"), - ), - Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }), - ) - expect(yield* service.servers()).toEqual([]) - expect(yield* service.tools()).toEqual([]) - expect(yield* service.instructions()).toEqual([]) - expect(yield* service.prompts()).toEqual([]) - expect(yield* service.resourceCatalog()).toEqual({ resources: [], templates: [] }) - expect(Exit.isFailure(yield* service.resources({ server: "resources" }).pipe(Effect.exit))).toBe(true) - expect(Exit.isFailure(yield* service.prompt({ server: "resources", name: "greet" }).pipe(Effect.exit))).toBe( - true, - ) - expect( - Exit.isFailure( - yield* service.readResource({ server: "resources", uri: "docs://readme" }).pipe(Effect.exit), - ), - ).toBe(true) - expect(Exit.isFailure(yield* service.connect("resources").pipe(Effect.exit))).toBe(true) - expect(Exit.isFailure(yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.exit))).toBe( - true, - ) - expect(server.state.toolCalls).toEqual([]) - expect(server.state.resourceReads).toEqual([]) - yield* Effect.promise(server.restart) - if (source === "config") yield* test.setEntries([document("allow")]) - if (source === "organization") yield* setOrganizationPolicy(undefined) - yield* PubSub.publish(updates, { type: Event.Updated.type }) - yield* service.servers().pipe( - Effect.filterOrFail( - (servers) => servers.some((server) => server.status.status === "connected"), - () => new Error("MCP policy was not restored"), - ), - Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }), - ) - expect(yield* settled(service)).toEqual({ status: "connected" }) - expect((yield* service.tools()).length).toBeGreaterThan(0) - }).pipe( - Effect.provide( - resourceMcpLayer(server.url, undefined, undefined, { - entries: config.entries, - subscribe: ((definition?: { readonly type: string }) => - Stream.fromPubSub(updates).pipe( - Stream.filter((event) => !definition || event.type === definition.type), - )) as Bus.Interface["subscribe"], + testEffect(Config.testLayer()).live(`revokes and restores a connected MCP through ${source} policy`, () => + Effect.gen(function* () { + const server = yield* resourceServer() + const config = yield* Config.Service + const test = yield* Config.Test + const updates = yield* PubSub.unbounded<{ readonly type: string }>() + const document = (effect: ConfigPolicy.Effect) => + new Document({ + type: "document", + info: new Info({ + mcp: new ConfigMCP.Info({ + servers: { resources: new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }) }, }), + policies: [{ action: "mcp.use", resource: "*", effect }], + }), + }) + yield* test.setEntries([document("allow")]) + yield* Effect.gen(function* () { + const service = yield* Mcp.Service + expect(yield* settled(service)).toEqual({ status: "connected" }) + expect((yield* service.tools()).length).toBeGreaterThan(0) + if (source === "config") yield* test.setEntries([document("deny")]) + if (source === "organization") + yield* setOrganizationPolicy([{ action: "mcp.use", resource: "*", effect: "deny" }]) + yield* PubSub.publish(updates, { type: Event.Updated.type }) + yield* service.servers().pipe( + Effect.filterOrFail( + (servers) => servers.length === 0, + () => new Error("MCP policy was not applied"), ), + Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }), ) - }), + expect(yield* service.servers()).toEqual([]) + expect(yield* service.tools()).toEqual([]) + expect(yield* service.instructions()).toEqual([]) + expect(yield* service.prompts()).toEqual([]) + expect(yield* service.resourceCatalog()).toEqual({ resources: [], templates: [] }) + expect(Exit.isFailure(yield* service.resources({ server: "resources" }).pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* service.prompt({ server: "resources", name: "greet" }).pipe(Effect.exit))).toBe( + true, + ) + expect( + Exit.isFailure(yield* service.readResource({ server: "resources", uri: "docs://readme" }).pipe(Effect.exit)), + ).toBe(true) + expect(Exit.isFailure(yield* service.connect("resources").pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.exit))).toBe( + true, + ) + expect(server.state.toolCalls).toEqual([]) + expect(server.state.resourceReads).toEqual([]) + yield* Effect.promise(server.restart) + if (source === "config") yield* test.setEntries([document("allow")]) + if (source === "organization") yield* setOrganizationPolicy(undefined) + yield* PubSub.publish(updates, { type: Event.Updated.type }) + yield* service.servers().pipe( + Effect.filterOrFail( + (servers) => servers.some((server) => server.status.status === "connected"), + () => new Error("MCP policy was not restored"), + ), + Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }), + ) + expect(yield* settled(service)).toEqual({ status: "connected" }) + expect((yield* service.tools()).length).toBeGreaterThan(0) + }).pipe( + Effect.provide( + resourceMcpLayer(server.url, undefined, undefined, { + entries: config.entries, + subscribe: ((definition?: { readonly type: string }) => + Stream.fromPubSub(updates).pipe( + Stream.filter((event) => !definition || event.type === definition.type), + )) as Bus.Interface["subscribe"], + }), + ), + ) + }), ) } @@ -3953,6 +3951,12 @@ describe("MCP pool", () => { }) describe("MCP events", () => { + const ready = (mcp: Mcp.Interface) => + mcp.awaitStartup().pipe( + Effect.andThen(mcp.servers()), + Effect.map((all) => all[0]?.status), + ) + // Answers `events/stream` with one `active` notification, then closes the stream. const eventServer = (input: { events?: boolean } = {}) => { const streams: Array<{ name: string | null; params: unknown }> = [] @@ -3990,7 +3994,7 @@ describe("MCP events", () => { const server = yield* eventServer({ events: true }) yield* Effect.gen(function* () { const mcp = yield* Mcp.Service - expect(yield* settled(mcp)).toEqual({ status: "connected" }) + expect(yield* ready(mcp)).toEqual({ status: "connected" }) const events = yield* mcp.events("resources") if (!events) throw new Error("expected MCP events") const messages = yield* Stream.runCollect(events.stream({ name: "job.finished", arguments: { job: "j1" } })) @@ -4002,6 +4006,311 @@ describe("MCP events", () => { }), ) + // Holds each `events/stream` open so a test can send notifications on it or close it. An event named "missing" + // is refused with NotFound. + const streamServer = Effect.fnUntraced(function* (input: { events?: boolean; failedOpens?: number } = {}) { + const attempts: unknown[] = [] + const streams = yield* Queue.unbounded<{ + params: unknown + aborted: Effect.Effect + send: (method: string, params: Record) => void + close: () => void + }>() + const encode = (message: Record) => + new TextEncoder().encode(`data: ${JSON.stringify({ jsonrpc: "2.0", ...message })}\n\n`) + const server = yield* resourceServer({ + modern: true, + events: input.events ?? true, + respond: async (request) => { + if (request.method !== "POST") return undefined + const body: unknown = await request.clone().json() + if (!isRecord(body) || body.method !== "events/stream") return undefined + attempts.push(body.params) + if (attempts.length <= (input.failedOpens ?? 0)) + return Response.json({ jsonrpc: "2.0", id: body.id, error: { code: -32603, message: "Temporary failure" } }) + if (isRecord(body.params) && body.params.name === "missing") + return Response.json({ jsonrpc: "2.0", id: body.id, error: { code: -32023, message: "Unknown event type" } }) + const meta = { "io.modelcontextprotocol/subscriptionId": body.id } + const controller = Promise.withResolvers>() + const aborted = Deferred.makeUnsafe() + const abort = () => Deferred.doneUnsafe(aborted, Exit.void) + Queue.offerUnsafe(streams, { + params: body.params, + aborted: Deferred.await(aborted), + send: (method: string, params: Record) => + void controller.promise.then((open) => + open.enqueue(encode({ method, params: { ...params, _meta: meta } })), + ), + close: () => + void controller.promise.then((open) => { + open.enqueue(encode({ id: body.id, result: { resultType: "complete", _meta: meta } })) + open.close() + }), + }) + request.signal.addEventListener("abort", abort) + return new Response( + new ReadableStream({ + start: (open) => controller.resolve(open), + cancel: () => void abort(), + }), + { headers: { "content-type": "text/event-stream" } }, + ) + }, + }) + return { url: server.url, attempts, opened: Queue.take(streams) } + }) + + // A bus whose published events reach its subscribers, recorded in order. + const workingBus = Effect.gen(function* () { + const hub = yield* PubSub.unbounded<{ readonly type: string; readonly data: unknown }>() + const published: Array<{ readonly type: string; readonly data: unknown }> = [] + const updates = yield* Queue.unbounded() + const layer = Layer.mock(Bus.Service, { + publish: (definition, data) => + Effect.suspend(() => { + const event = { id: ID.create(), type: definition.type, data } as Payload + published.push({ type: definition.type, data }) + Queue.offerUnsafe(updates, undefined) + return PubSub.publish(hub, event).pipe(Effect.as(event)) + }), + subscribe: ((definition?: { readonly type: string }) => + Stream.fromPubSub(hub).pipe( + Stream.filter((event) => !definition || event.type === definition.type), + )) as Bus.Interface["subscribe"], + }) + // Recheck the snapshot on publication; buffer signals that arrived before the assertion. + const until = (snapshot: Effect.Effect, ready: (value: A) => boolean) => + Effect.gen(function* () { + while (true) { + const value = yield* snapshot + if (ready(value)) return value + yield* Queue.take(updates) + } + }) + const delivered = (count: number) => + until( + Effect.sync(() => published.filter((event) => event.type === "experimental.mcp.event")), + (events) => events.length >= count, + ) + return { layer, published, until, delivered } + }) + + const subscriptionLayer = (url: string, bus: Layer.Layer, flags = "mcp_events") => + resourceMcpLayer( + new ConfigMCP.Remote({ type: "remote", url, oauth: false, protocol: "2026-07-28" }), + undefined, + undefined, + { flags, bus }, + ) + + const only = (mcp: Mcp.Interface) => mcp.subscriptions().pipe(Effect.map((all) => all[0])) + + testEffect(Layer.empty).live("publishes a subscription's events on the bus and follows its status", () => + Effect.gen(function* () { + const server = yield* streamServer() + const bus = yield* workingBus + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + const subscription = yield* mcp.subscribe("resources", { + name: "job.finished", + arguments: { job: "j1", filter: { a: 1, b: 2 } }, + }) + expect(subscription).toMatchObject({ + id: "mcpsub_2c691983d6df57af6bb5e2e8", + server: "resources", + status: { status: "pending" }, + cursor: null, + }) + const stream = yield* server.opened + stream.send("notifications/events/active", { cursor: "c1", truncated: false }) + yield* bus.until(only(mcp), (sub) => sub?.status.status === "active") + stream.send("notifications/events/event", { + eventId: "e1", + name: "job.finished", + timestamp: "2026-11-11T00:00:00Z", + data: [null, { job: "j1" }, false], + cursor: "c2", + }) + expect(yield* bus.delivered(1)).toEqual([ + { + type: "experimental.mcp.event", + data: { + id: subscription.id, + server: "resources", + name: "job.finished", + eventId: "e1", + timestamp: "2026-11-11T00:00:00Z", + data: [null, { job: "j1" }, false], + cursor: "c2", + }, + }, + ]) + expect(bus.published).toContainEqual({ + type: "experimental.mcp.subscription.changed", + data: { id: subscription.id }, + }) + + // The same arguments in another key order are the same subscription. + const again = yield* mcp.subscribe("resources", { + name: "job.finished", + arguments: { filter: { b: 2, a: 1 }, job: "j1" }, + }) + expect(again.id).toBe(subscription.id) + expect(server.attempts).toHaveLength(1) + + yield* mcp.unsubscribe(subscription.id) + expect(yield* mcp.subscriptions()).toEqual([]) + yield* stream.aborted + }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer))) + }), + ) + + const finishedEvent = (eventId: string, cursor: string) => ({ + eventId, + cursor, + name: "job.finished", + timestamp: "2026-11-11T00:00:00Z", + data: {}, + }) + + testEffect(Layer.empty).effect( + "backs off failed opens, resets after active, and resumes with a replay gap once", + () => + Effect.gen(function* () { + const server = yield* streamServer({ failedOpens: 2 }) + const bus = yield* workingBus + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + const events = yield* mcp.events("resources") + if (!events) throw new Error("expected MCP events") + const clock = yield* Clock.Clock + const openedAt: number[] = [] + const failed = yield* Queue.unbounded() + const open = events.stream + // A failed open stays pending. Wait for the client stream to fail, not just for the server to reply. + using observer = spyOn(events, "stream") + observer.mockImplementation((input) => { + openedAt.push(clock.currentTimeMillisUnsafe()) + return open(input).pipe(Stream.onError(() => Queue.offer(failed, undefined))) + }) + yield* mcp.subscribe("resources", { name: "job.finished" }) + yield* Queue.take(failed) + yield* TestClock.adjust("1 second") + expect(openedAt).toEqual([0, 1000]) + yield* Queue.take(failed) + yield* TestClock.adjust("2 seconds") + expect(openedAt).toEqual([0, 1000, 3000]) + const first = yield* server.opened + first.send("notifications/events/active", { cursor: "c1", truncated: false }) + yield* bus.until(only(mcp), (sub) => sub?.status.status === "active") + first.send("notifications/events/heartbeat", { cursor: "c5" }) + first.close() + expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "pending")).toMatchObject({ cursor: "c5" }) + yield* TestClock.adjust("1 second") + expect(openedAt).toEqual([0, 1000, 3000, 4000]) + const reopened = yield* server.opened + expect(server.attempts).toHaveLength(4) + expect(reopened.params).toMatchObject({ name: "job.finished", cursor: "c5" }) + reopened.send("notifications/events/active", { cursor: "c8", truncated: true }) + reopened.send("notifications/events/event", finishedEvent("e9", "c9")) + reopened.send("notifications/events/event", finishedEvent("e10", "c10")) + const delivered = yield* bus.delivered(2) + expect(delivered).toMatchObject([{ data: { eventId: "e9", truncated: true } }, { data: { eventId: "e10" } }]) + expect(delivered[1].data).not.toHaveProperty("truncated") + reopened.close() + expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "pending")).toMatchObject({ + cursor: "c10", + }) + }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer))) + }), + ) + + testEffect(Layer.empty).effect("ends a subscription the server terminates or rejects, without reopening it", () => + Effect.gen(function* () { + const server = yield* streamServer() + const bus = yield* workingBus + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + const finished = yield* mcp.subscribe("resources", { name: "job.finished" }) + const stream = yield* server.opened + stream.send("notifications/events/terminated", { error: { code: -32024, message: "Revoked" } }) + + const missing = yield* mcp.subscribe("resources", { name: "missing" }) + const status = (id: string) => + mcp.subscriptions().pipe(Effect.map((all) => all.find((sub) => sub.id === id)?.status)) + expect(yield* bus.until(status(finished.id), (value) => value?.status === "ended")).toEqual({ + status: "ended", + reason: "terminated", + error: { code: -32024, message: "Revoked" }, + }) + expect(yield* bus.until(status(missing.id), (value) => value?.status === "ended")).toMatchObject({ + status: "ended", + reason: "rejected", + error: { code: -32023 }, + }) + yield* TestClock.adjust("30 seconds") + expect(server.attempts).toMatchObject([{ name: "job.finished" }, { name: "missing" }]) + }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer))) + }), + ) + + testEffect(Layer.empty).live("reopens without a replay gap when cursorless, and ends when disabled", () => + Effect.gen(function* () { + const server = yield* streamServer() + const bus = yield* workingBus + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + yield* mcp.subscribe("resources", { name: "job.finished" }) + const first = yield* server.opened + first.send("notifications/events/active", { cursor: null }) + yield* bus.until(only(mcp), (sub) => sub?.status.status === "active") + + yield* mcp.connect("resources") + const reopened = yield* server.opened + yield* first.aborted + expect(reopened.params).toMatchObject({ cursor: null }) + // The null cursor means replay is unsupported; reconnecting is not evidence of a gap. + reopened.send("notifications/events/active", { cursor: null, truncated: false }) + reopened.send("notifications/events/event", finishedEvent("e2", "c2")) + const delivered = yield* bus.delivered(1) + expect(delivered).toMatchObject([{ data: { eventId: "e2" } }]) + expect(delivered[0].data).not.toHaveProperty("truncated") + + yield* mcp.disconnect("resources") + expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "ended")).toMatchObject({ + status: { status: "ended", reason: "unavailable" }, + cursor: "c2", + }) + }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer))) + }), + ) + + testEffect(Layer.empty).live("refuses to subscribe with the flag off, and ends at a server without events", () => + Effect.gen(function* () { + const offering = yield* streamServer() + const plain = yield* streamServer({ events: false }) + const bus = yield* workingBus + const refused = yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + return yield* mcp.subscribe("resources", { name: "job.finished" }).pipe(Effect.flip) + }).pipe(Effect.provide(subscriptionLayer(offering.url, bus.layer, "-mcp_events"))) + expect(refused).toBeInstanceOf(Mcp.EventsUnavailableError) + + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + yield* mcp.subscribe("resources", { name: "job.finished" }) + expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "ended")).toMatchObject({ + status: { status: "ended", reason: "unavailable" }, + }) + }).pipe(Effect.provide(subscriptionLayer(plain.url, bus.layer))) + }), + ) + testEffect(Layer.empty).live("offers no events with the mcp_events flag off, or from a server without them", () => Effect.gen(function* () { const offering = yield* eventServer({ events: true }) @@ -4009,7 +4318,7 @@ describe("MCP events", () => { const events = (url: string, flags: string) => Effect.gen(function* () { const mcp = yield* Mcp.Service - expect(yield* settled(mcp)).toEqual({ status: "connected" }) + expect(yield* ready(mcp)).toEqual({ status: "connected" }) return yield* mcp.events("resources") }).pipe(Effect.provide(layer(url, flags))) expect(yield* events(offering.url, "-mcp_events")).toBeUndefined() diff --git a/packages/core/test/persistent-pty-session.test.ts b/packages/core/test/persistent-pty-session.test.ts index cf305ceb2d15..565d3a91f82e 100644 --- a/packages/core/test/persistent-pty-session.test.ts +++ b/packages/core/test/persistent-pty-session.test.ts @@ -1,4 +1,5 @@ import { describe, expect } from "bun:test" +import path from "node:path" import { Effect, Fiber, Layer, Option, Stream } from "effect" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" @@ -110,25 +111,24 @@ describe("PersistentPty rename", () => { ) }) -// Pipe mode is Unix-only: Windows daemons reject create_pipe, so OpenCode keeps spawning shell commands there. -describe.skipIf(process.platform === "win32")("PersistentPty pipe processes", () => { - const input = { - program: "/bin/sh", - args: ["-c", "echo hi"], - cwd: "/tmp", - env: { PATH: "/usr/bin" }, - groupID: "proj_test", - outputPath: "/tmp/sh_test.out", - metadata: { id: "sh_test", command: "echo hi" }, - } +const pipeInput = (cwd: string) => ({ + program: process.execPath, + args: ["--version"], + cwd, + env: { TEST: "1" }, + groupID: "proj_test", + outputPath: path.join(cwd, "sh_test.out"), + metadata: { id: "sh_test", command: "--version" }, +}) +describe("PersistentPty pipe processes", () => { it.live("knows a handoff is prepared until a shutdown or until its ticket expires", () => Effect.gen(function* () { const daemon = yield* fakeDaemon() yield* Effect.gen(function* () { const pty = yield* PersistentPty.Service expect(pty.handoffPrepared()).toBe(false) - yield* pty.createPipe(input) + yield* pty.createPipe(pipeInput(daemon.options.root)) expect(yield* pty.handoff()).not.toBeNull() expect(pty.handoffPrepared()).toBe(true) // Abandoned by a shutdown. @@ -141,7 +141,7 @@ describe.skipIf(process.platform === "win32")("PersistentPty pipe processes", () expiring.handoffTTL.ms = 50 yield* Effect.gen(function* () { const pty = yield* PersistentPty.Service - yield* pty.createPipe(input) + yield* pty.createPipe(pipeInput(expiring.options.root)) expect(yield* pty.handoff()).not.toBeNull() expect(pty.handoffPrepared()).toBe(true) yield* Effect.sleep(80) @@ -155,20 +155,21 @@ describe.skipIf(process.platform === "win32")("PersistentPty pipe processes", () const daemon = yield* fakeDaemon() yield* Effect.gen(function* () { const pty = yield* PersistentPty.Service + const input = pipeInput(daemon.options.root) const created = yield* pty.createPipe(input) expect(daemon.requests.at(-1)).toEqual({ op: "create_pipe", - program: "/bin/sh", - args: ["-c", "echo hi"], - cwd: "/tmp", - env: { PATH: "/usr/bin" }, + program: input.program, + args: input.args, + cwd: input.cwd, + env: input.env, group_id: "proj_test", - output_path: "/tmp/sh_test.out", - metadata: { id: "sh_test", command: "echo hi" }, + output_path: input.outputPath, + metadata: input.metadata, }) expect(created).toMatchObject({ groupID: "proj_test", - outputPath: "/tmp/sh_test.out", + outputPath: input.outputPath, lifecycle: { status: "running" }, metadata: input.metadata, exitedAt: undefined, @@ -210,7 +211,7 @@ describe.skipIf(process.platform === "win32")("PersistentPty pipe processes", () title: "test", env: {}, }) - const pipe = yield* pty.createPipe(input) + const pipe = yield* pty.createPipe(pipeInput(directory.path)) expect((yield* pty.list()).map((item) => item.id)).toEqual([terminal.id]) expect((yield* pty.listPipes()).map((item) => item.id)).toEqual([pipe.id]) @@ -225,6 +226,7 @@ describe.skipIf(process.platform === "win32")("PersistentPty pipe processes", () const daemon = yield* fakeDaemon() yield* Effect.gen(function* () { const pty = yield* PersistentPty.Service + const input = pipeInput(daemon.options.root) expect(yield* Effect.flip(pty.createPipe({ ...input, cwd: "relative" }))).toEqual( new PersistentPty.RequestError({ message: "cwd must be absolute" }), ) @@ -278,21 +280,13 @@ const layer = (daemon: { readonly options: PersistentPty.Options }) => ], ) -describe.skipIf(process.platform === "win32")("PersistentPty handoff", () => { +describe("PersistentPty handoff", () => { it.live("prepares a handoff more than once on the same owner connection", () => Effect.gen(function* () { const daemon = yield* fakeDaemon() yield* Effect.gen(function* () { const pty = yield* PersistentPty.Service - yield* pty.createPipe({ - program: "/bin/sh", - args: ["-c", "echo hi"], - cwd: "/tmp", - env: {}, - groupID: "proj_test", - outputPath: "/tmp/sh_handoff.out", - metadata: {}, - }) + yield* pty.createPipe(pipeInput(daemon.options.root)) expect(yield* pty.handoff()).toMatchObject({ ticket: "next" }) expect(yield* pty.handoff()).toMatchObject({ ticket: "next" }) }).pipe(Effect.provide(layer(daemon))) diff --git a/packages/core/test/schedule.test.ts b/packages/core/test/schedule.test.ts index bde767359a04..abd5f698ef4d 100644 --- a/packages/core/test/schedule.test.ts +++ b/packages/core/test/schedule.test.ts @@ -63,7 +63,6 @@ const execution = Layer.succeed( isActive: () => Effect.succeed(false), resume: () => Effect.void, interrupt: () => Effect.succeed(false), - periodStartSeq: () => Effect.succeed(undefined), wake: (sessionID) => Effect.suspend(() => { wakes.push(sessionID) diff --git a/packages/core/test/session-background.test.ts b/packages/core/test/session-background.test.ts index 76e24e77060b..14b1a7da5679 100644 --- a/packages/core/test/session-background.test.ts +++ b/packages/core/test/session-background.test.ts @@ -71,38 +71,17 @@ describe("SessionBackground.outstanding", () => { }), ) - it.effect("skips created foreground-blocking and cancelled descendants when job state is available", () => + it.effect("skips cancelled descendants when job state is available", () => Effect.gen(function* () { const jobs = { runningBackground: Effect.succeed([]), get: (sessionID: string) => Effect.succeed( - sessionID === grandchild - ? info(grandchild, "running") - : sessionID === other - ? info(other, "cancelled") - : undefined, + sessionID === child ? info(child, "cancelled") : info(grandchild, "running", SessionMessage.ID.create()), ), } - // A foreground subagent's inline caller owns its result, and a cancelled one is - // acknowledged elsewhere: neither is still running for this report. - expect(yield* SessionBackground.outstanding(jobs, store, root, new Set([grandchild, other]))).toEqual([]) - - expect( - yield* SessionBackground.outstanding( - { - runningBackground: Effect.succeed([]), - get: (sessionID) => - Effect.succeed( - sessionID === grandchild ? info(grandchild, "running", SessionMessage.ID.create()) : undefined, - ), - }, - store, - root, - new Set([grandchild]), - ), - ).toEqual([ + expect(yield* SessionBackground.outstanding(jobs, store, root, new Set([child, grandchild]))).toEqual([ { kind: "subagent", sessionID: child, childSessionID: grandchild, agent: "subagent", description: "Subagent" }, ]) }), diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index dd5fa05b9a3d..1701d99de655 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -31,7 +31,6 @@ import { InstructionEntry } from "@opencode/core/session/instruction-entry" import { SessionEvent } from "@opencode/core/session/event" import { SessionTable } from "@opencode/core/session/sql" import { SessionStore } from "@opencode/core/session/store" -import { SubagentMetadata } from "@opencode/core/session/subagent-metadata" import { SessionTransfer } from "@opencode/core/session/transfer" import { Workspace } from "@opencode/core/workspace" import { Expected } from "./lib/session-message" @@ -475,42 +474,6 @@ describe("Session.create", () => { }), ) - it.effect("does not inherit the per-link subagent notify switch through children", () => - Effect.gen(function* () { - const session = yield* Session.Service - - const parent = yield* session.create({ - location, - metadata: { threadID: "t1", "subagent.notify": false }, - }) - const child = yield* session.create({ parentID: parent.id }) - expect(child.metadata).toEqual({ threadID: "t1" }) - expect(SubagentMetadata.notify(child.metadata)).toBe(true) - - const silent = yield* session.create({ parentID: parent.id, metadata: { "subagent.notify": false } }) - expect(silent.metadata).toEqual({ "subagent.notify": false }) - expect(SubagentMetadata.notify(silent.metadata)).toBe(false) - }), - ) - - it.effect("strips the per-link subagent notify switch when forking", () => - Effect.gen(function* () { - const session = yield* Session.Service - const bus = yield* Bus.Service - const { db } = yield* Database.Service - const parent = yield* session.create({ - location, - metadata: { threadID: "t1", "subagent.notify": false }, - }) - yield* session.prompt({ sessionID: parent.id, text: "Fork context", resume: false }) - yield* SessionInbox.promote(db, bus, parent.id, "steer") - - const forked = yield* session.fork({ sessionID: parent.id }) - expect(forked.metadata).toEqual({ threadID: "t1" }) - expect(SubagentMetadata.notify(forked.metadata)).toBe(true) - }), - ) - it.effect("stores permission rules, inherits them through children and forks, and replaces them", () => Effect.gen(function* () { const session = yield* Session.Service diff --git a/packages/core/test/session-execution.test.ts b/packages/core/test/session-execution.test.ts index 2b97349dedae..f1787d1e6b11 100644 --- a/packages/core/test/session-execution.test.ts +++ b/packages/core/test/session-execution.test.ts @@ -1,6 +1,7 @@ import type { FileSystem } from "@opencode/core/filesystem" import { describe, expect, test } from "bun:test" import { AIError, TransportError } from "@opencode/ai/effect" +import { Money } from "@opencode/schema/money" import { Database } from "@opencode/core/database/database" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" @@ -29,7 +30,7 @@ import { ID } from "@opencode/core/model" import { Provider } from "@opencode/core/provider" import { daemonShells } from "./fixture/shell-daemon" import { SubagentCompletion } from "@opencode/core/session/subagent-completion" -import { Context, Deferred, Effect, Exit, Fiber, Layer, LayerMap, Logger, Scope } from "effect" +import { Cause, Context, Deferred, Effect, Exit, Fiber, Layer, LayerMap, Logger, Scope } from "effect" import { eq } from "drizzle-orm" import { testEffect } from "./lib/effect" @@ -437,9 +438,6 @@ describe("SessionExecution lifecycle", () => { ) }) -// Shell commands only run in the process daemon off Windows (pipe mode is Unix-only), so the daemon shell cases skip there. -const daemonLive = process.platform === "win32" ? it.live.skip : it.live - describe("SessionRestart background recovery", () => { it.effect("keeps shell owners idle until a user prompt delivers recovered notices exactly once", () => Effect.gen(function* () { @@ -529,7 +527,85 @@ describe("SessionRestart background recovery", () => { }), ) - daemonLive("watches shell jobs whose commands survived the restart", () => + it.live("counts a suspended parent's restart attempt before its shell-woken child can wake it", () => + Effect.gen(function* () { + const db = yield* Database.Service + const jobs = yield* Job.Service + const parent = Session.ID.make("ses_shell_wake_budget_parent") + const child = Session.ID.make("ses_shell_wake_budget_child") + yield* seedSessions(db, [parent], { time_suspended: Date.now(), resume_attempts: 1 }) + yield* seedSessions(db, [child], { parent_id: parent }) + const daemon = yield* daemonShells() + const [finished, other] = yield* daemon.withShell("/project", (shell) => + Effect.all([ + shell.create({ shell: "/bin/sh", command: "finished", cwd: "/tmp" }), + shell.create({ shell: "/bin/sh", command: "still running", cwd: "/tmp" }), + ]), + ) + yield* seedBackground(jobs, child, [{ id: finished.id, shellID: finished.id, command: "finished" }]) + yield* seedBackground(jobs, parent, [{ id: other.id, shellID: other.id, command: "still running" }]) + daemon.daemon.exit(1, 0) + const scope = yield* Scope.make() + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) + const restarted = yield* Job.make.pipe(Scope.provide(scope)) + const shell = yield* daemon.openShell("/project").pipe(Scope.provide(scope)) + const store = yield* SessionStore.Service + const firstRootDrain = yield* Deferred.make() + const bus = yield* Bus.Service + const context = yield* buildExecution( + scope, + ({ sessionID }) => + Effect.gen(function* () { + yield* SessionInbox.promote(db.db, bus, sessionID, "steer") + if (sessionID === parent) { + yield* Deferred.succeed(firstRootDrain, yield* attempts(db, parent)) + return + } + const assistantMessageID = SessionMessage.ID.create() + yield* bus.publish(SessionEvent.Step.Started, { + sessionID, + assistantMessageID, + agent: Agent.ID.make("build"), + model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") }, + started: 0, + }) + yield* bus.publish(SessionEvent.Text.Started, { sessionID, assistantMessageID, ordinal: 1 }) + yield* bus.publish(SessionEvent.Text.Ended, { + sessionID, + assistantMessageID, + ordinal: 1, + text: "Shell done", + }) + yield* bus.publish(SessionEvent.Step.Ended, { + sessionID, + assistantMessageID, + finish: "stop", + cost: Money.USD.make(0), + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + }) + }), + { maxAttempts: 2 }, + restarted, + { + ...shell, + // If the finished shell already woke its child, let that drain settle mid-sweep. + get: (id) => + id === other.id ? execution.awaitIdle(child).pipe(Effect.andThen(shell.get(id))) : shell.get(id), + }, + ) + const execution: SessionExecution.Interface = Context.get(context, SessionExecution.Service) + yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions + expect(yield* Deferred.await(firstRootDrain)).toBe(2) + yield* execution.awaitIdle(child) + yield* execution.awaitIdle(parent) + expect((yield* store.context(parent)).filter((message) => message.type === "synthetic")).toMatchObject([ + { metadata: { notice: "restart" } }, + { metadata: { source: "subagent", childID: child } }, + ]) + }), + ) + + it.live("watches shell jobs whose commands survived the restart", () => Effect.gen(function* () { const database = yield* Database.Service const store = yield* SessionStore.Service @@ -591,7 +667,7 @@ describe("SessionRestart background recovery", () => { }), ) - daemonLive("settles a shell call a killed server left running as moved to the background", () => + it.live("settles a shell call a killed server left running as moved to the background", () => Effect.gen(function* () { const database = yield* Database.Service const store = yield* SessionStore.Service @@ -678,7 +754,7 @@ describe("SessionRestart background recovery", () => { ) for (const exited of [false, true]) - daemonLive( + it.live( `reattaches once a ${exited ? "finished" : "running"} shell a killed server backgrounded without settling its call`, () => Effect.gen(function* () { @@ -739,7 +815,7 @@ describe("SessionRestart background recovery", () => { }), ) - daemonLive("settles a recovered child's unsettled shell call before the child resumes", () => + it.live("settles a recovered child's unsettled shell call before the child resumes", () => Effect.gen(function* () { const database = yield* Database.Service const store = yield* SessionStore.Service @@ -1349,6 +1425,46 @@ describe("SessionRestart background recovery", () => { }), ) + it.effect("wakes the parent of an admitted report if the restart sweep fails afterward", () => + Effect.gen(function* () { + const database = yield* Database.Service + const jobs = yield* Job.Service + const bus = yield* Bus.Service + const parent = Session.ID.make("ses_failed_sweep_parent") + const child = Session.ID.make("ses_failed_sweep_child") + const root = Session.ID.make("ses_failed_sweep_root") + yield* seedSessions(database, [parent]) + yield* seedSessions(database, [child], { parent_id: parent }) + yield* seedSessions(database, [root], { time_suspended: Date.now() }) + yield* jobs.start({ + id: child, + type: "subagent", + recovery: { + kind: "subagent", + parentSessionID: parent, + childSessionID: child, + agent: "explore", + description: "Inspect", + }, + background: true, + run: Effect.succeed("Recovered result"), + }) + yield* jobs.wait({ id: child }) + + // The completed report is admitted before recovery publishes the unrelated root's restart notice. + const failure = new Error("failed to project restart notice") + yield* bus.project(SessionEvent.Synthetic, () => Effect.die(failure)) + const scope = yield* Scope.fork(yield* Effect.scope) + const drained: Session.ID[] = [] + const context = yield* buildExecution(scope, ({ sessionID }) => Effect.sync(() => void drained.push(sessionID))) + const exit = yield* Effect.exit(Context.get(context, SessionRestart.Service).resumeSuspendedSessions) + expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toBe(failure) + expect(yield* jobs.pendingBackground).toEqual([]) + yield* Context.get(context, SessionExecution.Service).awaitIdle(parent) + expect(drained).toEqual([parent]) + }), + ) + it.effect("reconciles an outbox row whose notification was already delivered", () => Effect.gen(function* () { const database = yield* Database.Service @@ -1593,124 +1709,6 @@ describe("SessionRestart background recovery", () => { }), ) - it.effect("clears an exhausted silent subagent without notifying its parent", () => - Effect.gen(function* () { - const database = yield* Database.Service - const jobs = yield* Job.Service - const parent = Session.ID.make("ses_silent_exhausted_parent") - const child = Session.ID.make("ses_silent_exhausted_child") - yield* seedSessions(database, [parent]) - yield* seedSessions(database, [child], { - parent_id: parent, - time_suspended: Date.now(), - resume_attempts: 2, - metadata: { "subagent.notify": false }, - }) - yield* jobs.start({ - id: child, - type: "subagent", - recovery: { - kind: "subagent", - parentSessionID: parent, - childSessionID: child, - agent: "explore", - description: "Silent exhausted inspection", - }, - run: Effect.never, - }) - yield* jobs.background(child) - - const drained: Session.ID[] = [] - const scope = yield* Scope.make() - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) - const restarted = yield* Job.make.pipe(Effect.provideService(Scope.Scope, scope)) - const context = yield* buildExecution( - scope, - ({ sessionID }) => Effect.sync(() => void drained.push(sessionID)), - { maxAttempts: 2 }, - restarted, - ) - yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions - - expect(drained).toEqual([]) - expect((yield* claims(database))[child]).toBe(false) - expect(yield* SessionInbox.list(database.db, parent)).toEqual([]) - expect(yield* restarted.pendingBackground).toEqual([]) - }), - ) - - it.effect("keeps a silent subagent quiet across restart for both finished and running rows", () => - Effect.gen(function* () { - const database = yield* Database.Service - const jobs = yield* Job.Service - const store = yield* SessionStore.Service - const parent = Session.ID.make("ses_silent_recovery_parent") - const finished = Session.ID.make("ses_silent_recovery_finished") - const running = Session.ID.make("ses_silent_recovery_running") - const metadata = { "subagent.notify": false } - yield* seedSessions(database, [parent]) - yield* seedSessions(database, [finished], { parent_id: parent, metadata }) - yield* seedSessions(database, [running], { parent_id: parent, metadata, time_suspended: Date.now() }) - const recovery = (child: Session.ID, description: string) => ({ - kind: "subagent" as const, - parentSessionID: parent, - childSessionID: child, - agent: "explore", - description, - }) - yield* jobs.start({ - id: finished, - type: "subagent", - recovery: recovery(finished, "Silent finished inspection"), - background: true, - run: Effect.succeed("Silent result"), - }) - yield* jobs.wait({ id: finished }) - yield* jobs.start({ - id: running, - type: "subagent", - recovery: recovery(running, "Silent running inspection"), - background: true, - run: Effect.never, - }) - - const resumed = yield* Deferred.make() - const release = yield* Deferred.make() - const drained: Session.ID[] = [] - const scope = yield* Scope.make() - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) - const restarted = yield* Job.make.pipe(Effect.provideService(Scope.Scope, scope)) - const context = yield* buildExecution( - scope, - ({ sessionID }) => - Effect.sync(() => void drained.push(sessionID)).pipe( - Effect.andThen( - sessionID === running - ? Deferred.succeed(resumed, undefined).pipe(Effect.andThen(Deferred.await(release))) - : Effect.void, - ), - ), - undefined, - restarted, - ) - const execution = Context.get(context, SessionExecution.Service) - yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions - yield* Deferred.await(resumed) - - // The finished row is acknowledged at inspection; only the still-running row remains. - expect(drained).toEqual([running]) - expect(yield* restarted.pendingBackground).toMatchObject([{ id: running, status: "running" }]) - expect(yield* SessionInbox.list(database.db, parent)).toEqual([]) - - yield* Deferred.succeed(release, undefined) - yield* execution.awaitIdle(running) - expect(yield* restarted.pendingBackground).toEqual([]) - expect(yield* SessionInbox.list(database.db, parent)).toEqual([]) - expect((yield* store.context(parent)).filter((message) => message.type === "synthetic")).toEqual([]) - expect(yield* claims(database)).toEqual({ [parent]: false, [finished]: false, [running]: false }) - }), - ) - it.effect("charges a suspended parent's restart attempt before a fast child can wake it", () => Effect.gen(function* () { const database = yield* Database.Service @@ -1976,9 +1974,7 @@ function seedInbox( function seedSessions( database: Database.Service["Service"], sessionIDs: ReadonlyArray, - values: Partial< - Pick - > = {}, + values: Partial> = {}, ) { return Effect.gen(function* () { yield* database.db diff --git a/packages/core/test/session-owned.test.ts b/packages/core/test/session-owned.test.ts index b9ce1832075a..0c3c996286d3 100644 --- a/packages/core/test/session-owned.test.ts +++ b/packages/core/test/session-owned.test.ts @@ -105,7 +105,6 @@ const setup = Effect.fnUntraced(function* (options?: { }), awaitIdle: () => Effect.void, interrupt: () => Effect.succeed(false), - periodStartSeq: () => Effect.succeed(undefined), wake: (id) => Effect.gen(function* () { const pending = yield* SessionInbox.list(database.db, id) @@ -638,7 +637,6 @@ describe("Session-owned handles", () => { }), wake: coordinator.wake, awaitIdle: coordinator.awaitIdle, - periodStartSeq: () => Effect.succeed(undefined), interrupt: (id, options) => Effect.sync(() => void interrupts.push({ sessionID: id, options })).pipe( Effect.andThen(coordinator.interrupt(id)), diff --git a/packages/core/test/session-prompt.test.ts b/packages/core/test/session-prompt.test.ts index cd5848ac9143..6c50de01f379 100644 --- a/packages/core/test/session-prompt.test.ts +++ b/packages/core/test/session-prompt.test.ts @@ -75,7 +75,6 @@ const execution = Layer.succeed( wakeCalls.push(sessionID) }), awaitIdle: () => Effect.void, - periodStartSeq: () => Effect.succeed(undefined), }), ) const mediaDirectory = "/media" diff --git a/packages/core/test/session-runner-recorded.test.ts b/packages/core/test/session-runner-recorded.test.ts index 691e7a966204..2c2d3894239e 100644 --- a/packages/core/test/session-runner-recorded.test.ts +++ b/packages/core/test/session-runner-recorded.test.ts @@ -125,7 +125,6 @@ const execution = (llmClient: Layer.Layer) => wake: coordinator.wake, interrupt: (sessionID) => coordinator.interrupt(sessionID), awaitIdle: coordinator.awaitIdle, - periodStartSeq: () => Effect.succeed(undefined), }) }), ).pipe(Layer.provide(runnerLayer(llmClient)), Layer.orDie) diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index d0754d13eca8..1e1c97f12797 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -509,7 +509,6 @@ const layer = Layer.unwrap( wake: coordinator.wake, interrupt: (sessionID) => coordinator.interrupt(sessionID), awaitIdle: coordinator.awaitIdle, - periodStartSeq: () => Effect.succeed(undefined), }) }), ).pipe( diff --git a/packages/core/test/session-shell.test.ts b/packages/core/test/session-shell.test.ts index 007ac7492409..8f1c92cff267 100644 --- a/packages/core/test/session-shell.test.ts +++ b/packages/core/test/session-shell.test.ts @@ -50,7 +50,6 @@ const executionLayer = Layer.effect( resume: coordinator.run, interrupt: (sessionID) => coordinator.interrupt(sessionID), awaitIdle: coordinator.awaitIdle, - periodStartSeq: () => Effect.succeed(undefined), wake: (sessionID) => Effect.sync(() => control.wakes.push(sessionID)).pipe(Effect.andThen(coordinator.wake(sessionID))), }) diff --git a/packages/core/test/shell-daemon.test.ts b/packages/core/test/shell-daemon.test.ts index 73e1500d22d3..5051819f124f 100644 --- a/packages/core/test/shell-daemon.test.ts +++ b/packages/core/test/shell-daemon.test.ts @@ -23,15 +23,12 @@ import { tmpdirScoped } from "./fixture/tmpdir" import { binaryPath } from "@opencode/pty" import { it } from "./lib/effect" -const unix = process.platform !== "win32" -const test = unix ? it.live : it.live.skip -// On the test clock, for timers. -const timed = unix ? it.effect : it.effect.skip +const windows = process.platform === "win32" const lines = (count: number) => Array.from({ length: count }, (_, index) => `line ${index + 1}\n`).join("") describe("Shell on the process daemon", () => { - test("runs a command with the server's environment, an absolute cwd and its metadata", () => + it.live("runs a command with the server's environment, an absolute cwd and its metadata", () => Effect.gen(function* () { const env = yield* daemonShells() yield* Effect.promise(() => mkdir(path.join(env.directory, "sub"))) @@ -103,9 +100,10 @@ describe("Shell on the process daemon", () => { expect(yield* shell.list()).toEqual([]) }), ) - })) + }), + ) - test("counts lines like the spawner and reads only what reached the file after a write error", () => + it.live("counts lines like the spawner and reads only what reached the file after a write error", () => Effect.gen(function* () { const env = yield* daemonShells() yield* env.withShell(env.directory, (shell) => @@ -139,9 +137,10 @@ describe("Shell on the process daemon", () => { ) }), ) - })) + }), + ) - test("bounds what it reads to number lines the daemon has not counted yet", () => + it.live("bounds what it reads to number lines the daemon has not counted yet", () => Effect.gen(function* () { const env = yield* daemonShells() yield* env.withShell(env.directory, (shell) => @@ -168,9 +167,10 @@ describe("Shell on the process daemon", () => { ) }), ) - })) + }), + ) - test("reports a command lost with the daemon as killed, with what it wrote", () => + it.live("reports a command lost with the daemon as killed, with what it wrote", () => Effect.gen(function* () { const env = yield* daemonShells() yield* env.withShell(env.directory, (shell) => @@ -185,9 +185,10 @@ describe("Shell on the process daemon", () => { }) }), ) - })) + }), + ) - test("stops what a failed command left in its group, and leaves a successful one's", () => + it.live("stops what a failed command left in its group, and leaves a successful one's", () => Effect.gen(function* () { const env = yield* daemonShells() yield* env.withShell(env.directory, (shell) => @@ -203,9 +204,10 @@ describe("Shell on the process daemon", () => { expect(env.signals(1)).toEqual([]) }), ) - })) + }), + ) - test("fails a command the daemon rejected instead of spawning it", () => + it.live("fails a command the daemon rejected instead of spawning it", () => Effect.gen(function* () { const env = yield* daemonShells() env.daemon.failCreate.message = "output path is a symlink" @@ -217,10 +219,11 @@ describe("Shell on the process daemon", () => { expect(yield* shell.list()).toEqual([]) }), ) - })) + }), + ) // On the test clock: the timeout and the grace period pass without waiting for them. - timed("stops a timed-out command with SIGTERM, then SIGKILL after the grace period, and keeps it", () => + it.effect("stops a timed-out command with SIGTERM, then SIGKILL after the grace period, and keeps it", () => Effect.gen(function* () { const env = yield* daemonShells() env.daemon.trap.add(1) @@ -250,7 +253,7 @@ describe("Shell on the process daemon", () => { }), ) - test("forgets a command in the daemon before deleting its file, on remove and on eviction", () => + it.live("forgets a command in the daemon before deleting its file, on remove and on eviction", () => Effect.gen(function* () { const env = yield* daemonShells() yield* env.withShell(env.directory, (shell) => @@ -280,9 +283,10 @@ describe("Shell on the process daemon", () => { expect(existsSync(finished[1]!.file)).toBe(true) }), ) - })) + }), + ) - test("takes its commands back after a restart and leaves other Locations' alone", () => + it.live("takes its commands back after a restart and leaves other Locations' alone", () => Effect.gen(function* () { const env = yield* daemonShells() env.daemon.trap.add(4) @@ -346,10 +350,11 @@ describe("Shell on the process daemon", () => { expect(yield* shell.wait(before.running.id)).toMatchObject({ status: "exited", exit: 0 }) }), ) - })) + }), + ) // A reload or an eviction closes a Location while the server keeps running. - timed("a Location closed while the server runs keeps enforcing its commands' timeouts", () => + it.effect("a Location closed while the server runs keeps enforcing its commands' timeouts", () => Effect.gen(function* () { const env = yield* daemonShells() const closing = yield* env.openLocation(env.directory) @@ -363,7 +368,7 @@ describe("Shell on the process daemon", () => { }), ) - timed("a closed Location and its replacement see the same commands, with one timer and one report each", () => + it.effect("a closed Location and its replacement see the same commands, with one timer and one report each", () => Effect.gen(function* () { const env = yield* daemonShells() const closing = yield* env.openLocation(env.directory) @@ -404,7 +409,7 @@ describe("Shell on the process daemon", () => { }), ) - test("finishes taking a Location's commands back even if the call that started it is interrupted", () => + it.live("finishes taking a Location's commands back even if the call that started it is interrupted", () => Effect.gen(function* () { const env = yield* daemonShells() const created = yield* env.withShell(env.directory, (shell) => @@ -435,9 +440,10 @@ describe("Shell on the process daemon", () => { const runs = yield* server.at(place) expect(runs.list().map((run) => run.info.id)).toEqual([created.id]) expect(lists()).toBe(before + 1) - })) + }), + ) - test("the sweep keeps a running command's file, and deletes a finished one's file and forgets it", () => + it.live("the sweep keeps a running command's file, and deletes a finished one's file and forgets it", () => Effect.gen(function* () { const env = yield* daemonShells() const ids = yield* env.withShell(env.directory, (shell) => @@ -481,11 +487,12 @@ describe("Shell on the process daemon", () => { expect(env.daemon.processes.map((process) => process.id)).toEqual([1]) // The old process's file is recent, so it stays. expect(existsSync(ids.old.file)).toBe(true) - })) + }), + ) }) // Against the real opencode-pty, like server/test/persistent-pty.test.ts. -const binary = unix ? (process.env.OPENCODE_PTY_BIN ?? binaryPath) : undefined +const binary = process.env.OPENCODE_PTY_BIN ?? binaryPath const real = binary !== undefined && existsSync(binary) ? it.live : it.live.skip describe("Shell on a real process daemon", () => { @@ -502,12 +509,15 @@ describe("Shell on a real process daemon", () => { yield* Effect.addFinalizer(() => Effect.sync(() => delete process.env.OPENCODE_TEST_REMOVED)) yield* Effect.gen(function* () { const shell = yield* Shell.Service + const pty = yield* PersistentPty.Service yield* Shell.cleanup() expect(started()).toBe(false) const info = yield* shell.create( { - shell: "/bin/sh", - command: 'printf "%s|%s|%s\\n" "${OPENCODE_TEST_REMOVED:-unset}" "$TERM" "$(pwd)"; printf tail', + shell: windows ? (Bun.which("pwsh") ?? "powershell.exe") : "/bin/sh", + command: windows + ? "if ($env:OPENCODE_TEST_REMOVED) { exit 1 }; [Console]::Out.Write('unset|' + $env:TERM + '|' + $PWD.Path + [char]10 + 'tail')" + : 'printf "%s|%s|%s\\n" "${OPENCODE_TEST_REMOVED:-unset}" "$TERM" "$(pwd)"; printf tail', }, (invocation) => Effect.sync(() => { @@ -515,6 +525,7 @@ describe("Shell on a real process daemon", () => { }), ) expect(started()).toBe(true) + expect(yield* pty.listPipes()).toMatchObject([{ pid: info.pid, metadata: { id: info.id } }]) expect(yield* shell.result(info)).toMatchObject({ info: { status: "exited", exit: 0 }, capture: { diff --git a/packages/core/test/shell-restart.test.ts b/packages/core/test/shell-restart.test.ts index 604371cfb18b..1882acc901ca 100644 --- a/packages/core/test/shell-restart.test.ts +++ b/packages/core/test/shell-restart.test.ts @@ -35,6 +35,7 @@ import { testEffect } from "./lib/effect" import { permissionLayer } from "./lib/permission" const it = testEffect(tempGlobalLayer) +const idleCommand = process.platform === "win32" ? "Start-Sleep -Seconds 60" : "sleep 60" const model = SessionRunnerModel.node.replace( Layer.succeed(SessionRunnerModel.Service, { @@ -95,7 +96,7 @@ const world = Effect.gen(function* () { ), scope, ) - const shellSpawns = () => spawns.filter((command) => JSON.stringify(command).includes("sleep 60")) + const shellSpawns = () => spawns.filter((spawn) => JSON.stringify(spawn).includes(idleCommand)) return { daemon, llm: Context.get(llm, TestLLM.Test), project, server, shellSpawns } }) @@ -115,8 +116,7 @@ const until = (check: () => boolean) => while (!check()) yield* Effect.sleep(5) }) -// Shell commands only run in the process daemon off Windows (pipe mode is Unix-only). -describe.skipIf(process.platform === "win32")("shell commands across a graceful restart", () => { +describe("shell commands across a graceful restart", () => { for (const finished of [false, true]) it.live( `settles a foreground call ${finished ? "whose command finished during the restart" : "whose command still runs"} and resumes its session`, @@ -127,7 +127,7 @@ describe.skipIf(process.platform === "win32")("shell commands across a graceful let turns = 0 yield* llm.serve((request) => request.tools.some((tool) => tool.name === "shell") && turns++ === 0 - ? TestLLM.toolCall("call-restart", "shell", { command: "sleep 60" }) + ? TestLLM.toolCall("call-restart", "shell", { command: idleCommand }) : TestLLM.text("Done", "done"), ) @@ -210,7 +210,7 @@ describe.skipIf(process.platform === "win32")("shell commands across a graceful let turns = 0 yield* llm.serve((request) => request.tools.some((tool) => tool.name === "shell") && turns++ === 0 - ? TestLLM.toolCall("call-shutdown", "shell", { command: "sleep 60" }) + ? TestLLM.toolCall("call-shutdown", "shell", { command: idleCommand }) : TestLLM.text("Done", "done"), ) let release = () => {} diff --git a/packages/core/test/subagent-idle-e2e.test.ts b/packages/core/test/subagent-idle-e2e.test.ts index 6abe7a75c8bc..6be495a9f50b 100644 --- a/packages/core/test/subagent-idle-e2e.test.ts +++ b/packages/core/test/subagent-idle-e2e.test.ts @@ -267,13 +267,6 @@ const harness = Effect.fnUntraced(function* (input?: HarnessInput) { const outputSessionID = (value: unknown) => Schema.decodeUnknownSync(Schema.Struct({ sessionID: Session.ID }))(value).sessionID -const messageText = (message: SessionMessage.Info) => - message.type === "assistant" - ? message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n\n") - : message.type === "synthetic" - ? message.text - : "" - const deliveredReports = (app: { readonly sessions: Session.Interface }, sessionID: Session.ID) => app.sessions .context(sessionID) @@ -334,7 +327,7 @@ describe("subagent idle reports end to end", () => { }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") expect(launched).toMatchObject({ status: "completed", metadata: { status: "running" } }) yield* waitForReports(h, h.parent.id, 1) @@ -372,7 +365,7 @@ describe("subagent idle reports end to end", () => { build: [TestLLM.text("parent ack", "parent-1"), TestLLM.text("parent ack", "parent-2")], }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* waitForReports(h, h.parent.id, 1) expect((yield* deliveredReports(h, h.parent.id))[0]!.text).toContain("first answer") @@ -412,18 +405,18 @@ describe("subagent idle reports end to end", () => { build: [TestLLM.text("parent ack", "parent-1"), TestLLM.text("parent ack", "parent-2")], }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* waitForReports(h, h.parent.id, 1) yield* h.sessions.wait(childID) yield* h.jobs.wait({ id: childID }) - const second = yield* h.call("call-follow-up", { background: true, sessionID: childID }) + const second = yield* h.call("call-follow-up", { sessionID: childID }) expect(second).toMatchObject({ metadata: { sessionID: childID, status: "running" } }) yield* waitForReports(h, h.parent.id, 2) expect((yield* deliveredReports(h, h.parent.id))[1]!.text).toContain("second answer") - const third = yield* h.call("call-follow-up-again", { background: true, sessionID: childID }) + const third = yield* h.call("call-follow-up-again", { sessionID: childID }) expect(third).toMatchObject({ metadata: { sessionID: childID, status: "running" } }) yield* waitForReports(h, h.parent.id, 3) expect((yield* deliveredReports(h, h.parent.id))[2]!.text).toContain("third answer") @@ -454,7 +447,6 @@ describe("subagent idle reports end to end", () => { agent: "fallback", description: "grandchild review", prompt: "review the grandchild fixture", - background: true, }), TestLLM.text("child launched grandchild", "child-turn-1"), TestLLM.text("child saw first grandchild report", "child-turn-2"), @@ -474,7 +466,7 @@ describe("subagent idle reports end to end", () => { }), ) - const launched = yield* h.call("call-child", { background: true, description: "child review" }) + const launched = yield* h.call("call-child", { description: "child review" }) const childID = outputSessionID(launched.metadata) yield* waitForReports(h, h.parent.id, 1) @@ -515,56 +507,6 @@ describe("subagent idle reports end to end", () => { 30_000, ) - e2e.live( - "a silent middle keeps its loud grandchild from skipping a level", - () => - Effect.gen(function* () { - const h = yield* harness({ - config: { - experimental: { subagent_depth: 2 }, - permissions: [{ action: "*", resource: "*", effect: "allow" }], - }, - }) - yield* h.llm.serve( - script({ - reviewer: [ - TestLLM.toolCall("call-grandchild", SubagentTool.name, { - agent: "fallback", - description: "grandchild review", - prompt: "review the grandchild fixture", - background: true, - }), - TestLLM.text("silent child launched grandchild", "child-turn-1"), - TestLLM.text("silent child saw grandchild", "child-turn-2"), - ], - fallback: [TestLLM.text("grandchild answer", "grandchild-turn-1")], - build: [TestLLM.text("parent ack", "parent-1")], - }), - ) - - const launched = yield* h.call("call-silent-child", { - background: true, - notify: false, - description: "silent child review", - }) - const childID = outputSessionID(launched.metadata) - expect((yield* h.sessions.get(childID)).metadata).toEqual({ "subagent.notify": false }) - - yield* waitForReports(h, childID, 1) - const report = (yield* deliveredReports(h, childID))[0]! - const grandchildID = Schema.decodeUnknownSync(Session.ID)(report.metadata?.childID) - expect((yield* h.sessions.get(grandchildID)).metadata).toBeUndefined() - expect((yield* h.sessions.context(childID)).map(messageText)).toContain("silent child saw grandchild") - - // The grandchild reported to the silent child, and the silent child never reported up. - expect(yield* deliveredReports(h, h.parent.id)).toEqual([]) - expect((yield* h.sessions.inbox(h.parent.id)).filter((item) => item.type === "synthetic")).toEqual([]) - expect((yield* h.sessions.get(childID)).metadata).toEqual({ "subagent.notify": false }) - expect(yield* h.jobs.pendingBackground).toEqual([]) - }), - 30_000, - ) - e2e.live( "replays the report committed before a crash without running the child again", () => @@ -578,7 +520,7 @@ describe("subagent idle reports end to end", () => { }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* Deferred.await(crashed) yield* h.sessions.wait(childID) @@ -647,7 +589,7 @@ describe("subagent idle reports end to end", () => { type: "tool-call", id: "call-launch", name: SubagentTool.name, - input: { agent: "reviewer", description: "restart review", prompt: "review this", background: true }, + input: { agent: "reviewer", description: "restart review", prompt: "review this" }, }, }) const childID = outputSessionID(launched.metadata) @@ -704,7 +646,7 @@ describe("subagent idle reports end to end", () => { }), ) const gate = yield* h.llm.gate() - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* gate.started expect((yield* claims(h))[childID]).toBe(true) @@ -739,7 +681,7 @@ describe("subagent idle reports end to end", () => { }), ) const gate = yield* h.llm.gate() - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* gate.started diff --git a/packages/core/test/subagent-lifetime.test.ts b/packages/core/test/subagent-lifetime.test.ts index 0a5de6d13b18..d24148b8d9b8 100644 --- a/packages/core/test/subagent-lifetime.test.ts +++ b/packages/core/test/subagent-lifetime.test.ts @@ -106,11 +106,11 @@ describe("subagent observer lifetime", () => { sessionID: child.id, description: "Review fixture", prompt: "Review the fixture", - background: true, }, }, }) expect(result.status).toBe("completed") + expect(result.output).toMatchObject({ status: "running" }) yield* gate.started expect(yield* sessions.context(parent.id)).toEqual([]) if (evict) { diff --git a/packages/core/test/subagent-metadata.test.ts b/packages/core/test/subagent-metadata.test.ts deleted file mode 100644 index dfb47021e081..000000000000 --- a/packages/core/test/subagent-metadata.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { SubagentMetadata } from "@opencode/core/session/subagent-metadata" - -const silent = { [SubagentMetadata.KEY]: false } as const -const silentThread = { threadID: "123", [SubagentMetadata.KEY]: false } as const -const thread = { threadID: "123" } as const - -describe("SubagentMetadata.notify", () => { - test("defaults to loud when the switch is absent", () => { - expect(SubagentMetadata.notify(undefined)).toBe(true) - expect(SubagentMetadata.notify({})).toBe(true) - expect(SubagentMetadata.notify(thread)).toBe(true) - expect(SubagentMetadata.notify({ [SubagentMetadata.KEY]: true })).toBe(true) - }) - - test("only an explicit false silences the link", () => { - expect(SubagentMetadata.notify(silent)).toBe(false) - expect(SubagentMetadata.notify(silentThread)).toBe(false) - }) -}) - -describe("SubagentMetadata.inherit", () => { - test("returns metadata without the switch unchanged", () => { - expect(SubagentMetadata.inherit(undefined)).toBeUndefined() - expect(SubagentMetadata.inherit(thread)).toBe(thread) - }) - - test("strips the switch and keeps host annotations", () => { - expect(SubagentMetadata.inherit(silentThread)).toEqual({ threadID: "123" }) - expect(SubagentMetadata.inherit({ ...thread, [SubagentMetadata.KEY]: true })).toEqual({ threadID: "123" }) - }) - - test("collapses metadata that only carried the switch", () => { - expect(SubagentMetadata.inherit(silent)).toBeUndefined() - }) -}) - -describe("SubagentMetadata.apply", () => { - test("writes an explicit false", () => { - expect(SubagentMetadata.apply(undefined, false)).toEqual({ [SubagentMetadata.KEY]: false }) - expect(SubagentMetadata.apply(thread, false)).toEqual({ threadID: "123", [SubagentMetadata.KEY]: false }) - }) - - test("loud stays clean by stripping the switch", () => { - expect(SubagentMetadata.apply(undefined, true)).toBeUndefined() - expect(SubagentMetadata.apply(thread, true)).toEqual({ threadID: "123" }) - expect(SubagentMetadata.apply(silent, true)).toBeUndefined() - expect(SubagentMetadata.apply(silentThread, true)).toEqual({ threadID: "123" }) - }) -}) - -describe("SubagentMetadata.withNotify", () => { - test("creates loud children from absent or silent parents", () => { - expect(SubagentMetadata.withNotify(undefined, true)).toBeUndefined() - expect(SubagentMetadata.withNotify(thread, true)).toEqual({ threadID: "123" }) - expect(SubagentMetadata.withNotify(silent, true)).toBeUndefined() - expect(SubagentMetadata.withNotify(silentThread, true)).toEqual({ threadID: "123" }) - }) - - test("creates silent children without inheriting the parent's switch", () => { - expect(SubagentMetadata.withNotify(undefined, false)).toEqual({ [SubagentMetadata.KEY]: false }) - expect(SubagentMetadata.withNotify(thread, false)).toEqual({ threadID: "123", [SubagentMetadata.KEY]: false }) - expect(SubagentMetadata.withNotify(silentThread, false)).toEqual({ - threadID: "123", - [SubagentMetadata.KEY]: false, - }) - }) -}) - -describe("SubagentMetadata.update", () => { - test("skips writes that would not change the link state", () => { - expect(SubagentMetadata.update(undefined, true)).toBeUndefined() - expect(SubagentMetadata.update({}, true)).toBeUndefined() - expect(SubagentMetadata.update(thread, true)).toBeUndefined() - expect(SubagentMetadata.update({ [SubagentMetadata.KEY]: true }, true)).toBeUndefined() - expect(SubagentMetadata.update(silent, false)).toBeUndefined() - expect(SubagentMetadata.update(silentThread, false)).toBeUndefined() - }) - - test("returns the metadata to persist on a transition", () => { - expect(SubagentMetadata.update(undefined, false)).toEqual({ [SubagentMetadata.KEY]: false }) - expect(SubagentMetadata.update(thread, false)).toEqual({ threadID: "123", [SubagentMetadata.KEY]: false }) - expect(SubagentMetadata.update(silentThread, true)).toEqual({ threadID: "123" }) - }) - - test("returns an empty object when clearing the last key", () => { - expect(SubagentMetadata.update(silent, true)).toEqual({}) - }) -}) diff --git a/packages/core/test/subagent-report.test.ts b/packages/core/test/subagent-report.test.ts index 741bbd613e25..bec0c8d59d6d 100644 --- a/packages/core/test/subagent-report.test.ts +++ b/packages/core/test/subagent-report.test.ts @@ -82,12 +82,11 @@ describe("SubagentReport settlement", () => { const parent = sessionID("ses_bgreport_parent") const child = sessionID("ses_bgreport_child") const active = sessionID("ses_bgreport_active") - const foreground = sessionID("ses_bgreport_foreground") const cancelled = sessionID("ses_bgreport_cancelled") const stopping = sessionID("ses_bgreport_stopping") yield* seedSessions(database, [parent]) yield* seedSessions(database, [child], { parent_id: parent, agent: "explore", title: "Background audit" }) - yield* seedSessions(database, [active, foreground, cancelled, stopping], { parent_id: child }) + yield* seedSessions(database, [active, cancelled, stopping], { parent_id: child }) const shell = yield* jobs.start({ id: "sh_bgreport_shell", @@ -103,18 +102,6 @@ describe("SubagentReport settlement", () => { background: true, run: Effect.never, }) - yield* jobs.start({ - id: foreground, - type: "subagent", - recovery: { - kind: "subagent", - parentSessionID: child, - childSessionID: foreground, - agent: "explore", - description: "Foreground descendant", - }, - run: Effect.never, - }) yield* jobs.start({ id: cancelled, type: "subagent", @@ -138,7 +125,7 @@ describe("SubagentReport settlement", () => { const scope = yield* Scope.make() yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) const context = yield* buildExecution(scope, ({ sessionID }) => { - if (sessionID === active || sessionID === foreground || sessionID === cancelled) return gate + if (sessionID === active || sessionID === cancelled) return gate if (sessionID === stopping) return Deferred.succeed(stoppingStarted, undefined).pipe( Effect.andThen(Effect.never), @@ -148,7 +135,6 @@ describe("SubagentReport settlement", () => { }) const execution = Context.get(context, SessionExecution.Service) yield* execution.resume(active).pipe(Effect.forkIn(scope)) - yield* execution.resume(foreground).pipe(Effect.forkIn(scope)) yield* execution.resume(cancelled).pipe(Effect.forkIn(scope)) yield* execution.resume(stopping).pipe(Effect.forkIn(scope)) yield* Deferred.await(started) @@ -445,122 +431,6 @@ describe("SubagentReport settlement", () => { if (marker) yield* jobs.completeBackground(marker.notificationID) }), ) - - it.effect("suppresses reports for a silent child and clears its background marker", () => - Effect.gen(function* () { - const database = yield* Database.Service - const jobs = yield* Job.Service - const parent = sessionID("ses_silent_parent") - const child = sessionID("ses_silent_child") - yield* seedSessions(database, [parent]) - yield* seedSessions(database, [child], { - parent_id: parent, - metadata: { "subagent.notify": false }, - }) - - const scope = yield* Scope.make() - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) - const context = yield* buildExecution(scope, () => Effect.void) - const execution = Context.get(context, SessionExecution.Service) - - yield* seedAssistant(database, child, 100, "Silent work") - yield* execution.wake(child) - yield* execution.awaitIdle(child) - expect(yield* SessionInbox.list(database.db, parent)).toEqual([]) - - const job = yield* jobs.start({ - id: child, - type: "subagent", - recovery: { - kind: "subagent", - parentSessionID: parent, - childSessionID: child, - agent: "explore", - description: "Silent job", - }, - background: true, - run: execution.resume(child).pipe(Effect.as("")), - }) - yield* jobs.wait({ id: job.id }) - expect(yield* SessionInbox.list(database.db, parent)).toEqual([]) - expect(yield* jobs.pendingBackground).toEqual([]) - expect(yield* jobs.backgroundJobs).toEqual([]) - expect(yield* jobs.get(child)).toBeUndefined() - }), - ) - - it.effect("suppresses foreground job reports and still reports a later non-job period", () => - Effect.gen(function* () { - const database = yield* Database.Service - const jobs = yield* Job.Service - const parent = sessionID("ses_foreground_parent") - const child = sessionID("ses_foreground_child") - const cancelled = sessionID("ses_foreground_cancelled") - yield* seedSessions(database, [parent]) - yield* seedSessions(database, [child, cancelled], { parent_id: parent, agent: "explore" }) - - const started = yield* Deferred.make() - const released = yield* Deferred.make() - const cancelStarted = yield* Deferred.make() - const cancelReleased = yield* Deferred.make() - const scope = yield* Scope.make() - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) - const context = yield* buildExecution(scope, ({ sessionID }) => { - if (sessionID === child) - return Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(released))) - if (sessionID === cancelled) - return Deferred.succeed(cancelStarted, undefined).pipe(Effect.andThen(Deferred.await(cancelReleased))) - return Effect.void - }) - const execution = Context.get(context, SessionExecution.Service) - - // Normal foreground completion returns to the inline caller, not the parent's inbox. - const job = yield* jobs.start({ - id: child, - type: "subagent", - recovery: { - kind: "subagent", - parentSessionID: parent, - childSessionID: child, - agent: "explore", - description: "Foreground audit", - }, - run: execution.resume(child).pipe(Effect.as("inline")), - }) - yield* Deferred.await(started) - yield* seedAssistant(database, child, 100, "Inline answer") - yield* Deferred.succeed(released, undefined) - yield* jobs.wait({ id: job.id }) - expect(yield* SessionInbox.list(database.db, parent)).toEqual([]) - - // The next non-job period is a fresh busy period and reports normally. - yield* seedAssistant(database, child, 200, "Follow-up after foreground") - yield* execution.wake(child) - yield* execution.awaitIdle(child) - const reports = yield* SessionInbox.list(database.db, parent) - expect(reports).toHaveLength(1) - expect(text(reports[0])).toContain("Follow-up after foreground") - - // A cancelled foreground generation is still the inline caller's to report. - yield* jobs.start({ - id: cancelled, - type: "subagent", - recovery: { - kind: "subagent", - parentSessionID: parent, - childSessionID: cancelled, - agent: "explore", - description: "Foreground cancellation", - }, - run: execution.resume(cancelled).pipe(Effect.as("")), - }) - yield* Deferred.await(cancelStarted) - expect(yield* jobs.cancel(cancelled)).toMatchObject({ status: "cancelled" }) - expect(yield* execution.interrupt(cancelled)).toBe(true) - yield* execution.awaitIdle(cancelled) - expect(yield* SessionInbox.list(database.db, parent)).toHaveLength(1) - }), - ) }) describe("SubagentReport outbox", () => { @@ -828,10 +698,7 @@ function buildExecution(scope: Scope.Scope, drain: Drain) { } type SeedValues = Partial< - Pick< - typeof SessionTable.$inferInsert, - "time_suspended" | "resume_attempts" | "parent_id" | "metadata" | "title" | "revert" - > + Pick > & { readonly agent?: string } function seedSessions( diff --git a/packages/core/test/tool-output.test.ts b/packages/core/test/tool-output.test.ts index 439fda7ee70c..ba509d6eb6b6 100644 --- a/packages/core/test/tool-output.test.ts +++ b/packages/core/test/tool-output.test.ts @@ -59,7 +59,9 @@ describe("ToolOutput", () => { { type: "text", text: "one\ntwo" }, { type: "text", - text: expect.stringMatching(/^\[showing lines 1-2 of 3; full output could not be saved: E[A-Z]+: [^\n]+\]$/), + text: expect.stringMatching( + /^\[showing lines 1-2 of 3; full output could not be saved: E[A-Z]+: [^\n]+\]$/, + ), }, ]) }), @@ -67,16 +69,16 @@ describe("ToolOutput", () => { ), ) - it.live("reports lines shown under the byte limit", () => + it.live("cuts at the byte limit, inside a line when it falls there", () => withStore( (output) => Effect.gen(function* () { const result = yield* output.truncate({ content: [{ type: "text", text: "one\ntwo" }] }) expect(result.content).toEqual([ - { type: "text", text: "one" }, + { type: "text", text: "one\nt" }, { type: "text", - text: expect.stringMatching(/^\[showing lines 1-1 of 2; full output saved to .+\]$/), + text: expect.stringMatching(/^\[showing lines 1-2 of 2 \(last line cut\); full output saved to .+\]$/), }, ]) }), @@ -84,6 +86,165 @@ describe("ToolOutput", () => { ), ) + it.live("shows the start of a single line longer than the byte limit", () => + withStore( + (output) => + Effect.gen(function* () { + const text = JSON.stringify({ items: Array.from({ length: 50 }, (_, index) => index) }) + const result = yield* output.truncate({ content: [{ type: "text", text }] }) + expect(result.content).toEqual([ + { type: "text", text: text.slice(0, 20) }, + { + type: "text", + text: expect.stringMatching( + new RegExp("^\\[showing lines 1-1 of 1 \\(last line cut\\); full output saved to .+\\]$"), + ), + }, + ]) + }), + { maxLines: 100, maxBytes: 20 }, + ), + ) + + it.live("never splits a character or an emoji at the cut", () => + withStore( + (output) => + Effect.gen(function* () { + const family = "👨‍👩‍👧‍👦" + const cases = [ + { text: "ab✓✓✓", shown: "ab✓" }, + { text: `ab${family}cd`, shown: "ab" }, + { text: "ab👍🏽cd", shown: "ab" }, + { text: "ab🇯🇵cd", shown: "ab" }, + { text: "ab𝒳𝒳", shown: "ab𝒳" }, + ] + for (const item of cases) { + const result = yield* output.truncate({ content: [{ type: "text", text: item.text }] }) + const first = result.content[0] + expect(first).toEqual({ type: "text", text: item.shown }) + expect(first?.type === "text" && first.text.isWellFormed()).toBe(true) + } + }), + { maxLines: 100, maxBytes: 7 }, + ), + ) + + it.live("keeps flags and long clusters whole however long the text before them", () => + withStore( + (output) => + Effect.gen(function* () { + const flags = yield* output.truncate({ content: [{ type: "text", text: "a" + "🇯🇵".repeat(40) }] }) + expect(flags.content[0]).toEqual({ type: "text", text: "a" + "🇯🇵".repeat(20) }) + const cluster = "👍" + "🏽\u0301".repeat(60) + const long = yield* output.truncate({ content: [{ type: "text", text: `ab${cluster}z` }] }) + expect(long.content[0]).toEqual({ type: "text", text: "ab" }) + }), + { maxLines: 100, maxBytes: 165 }, + ), + ) + + it.live("cuts inside a later text part and leaves out the parts after it", () => + withStore( + (output) => + Effect.gen(function* () { + const inside = yield* output.truncate({ + content: [ + { type: "text", text: "" }, + { type: "text", text: "abc" }, + { type: "text", text: "defgh" }, + { type: "text", text: "" }, + ], + }) + expect(inside.content).toEqual([ + { type: "text", text: "" }, + { type: "text", text: "abc" }, + { type: "text", text: "de" }, + { + type: "text", + text: expect.stringMatching(/^\[showing lines 1-2 of 2 \(last line cut\);/), + }, + ]) + const between = yield* output.truncate({ + content: [ + { type: "text", text: "abcde" }, + { type: "text", text: "fgh" }, + ], + }) + expect(between.content).toEqual([ + { type: "text", text: "abcde" }, + { type: "text", text: expect.stringMatching(/^\[showing lines 1-1 of 2;/) }, + ]) + }), + { maxLines: 100, maxBytes: 6 }, + ), + ) + + it.live("ends a line cut before its line break", () => + withStore( + (output) => + Effect.gen(function* () { + const crlf = yield* output.truncate({ content: [{ type: "text", text: "one\r\ntwo\r\nthree" }] }) + expect(crlf.content).toEqual([ + { type: "text", text: "one" }, + { type: "text", text: expect.stringMatching(/^\[showing lines 1-1 of 3;/) }, + ]) + const blank = yield* output.truncate({ content: [{ type: "text", text: "\nfoo\nbar" }] }) + expect(blank.content).toEqual([{ type: "text", text: expect.stringMatching(/^\[showing lines 1-1 of 3;/) }]) + }), + { maxLines: 1, maxBytes: 1_000 }, + ), + ) + + it.live("counts a blank last line of the preview", () => + withStore( + (output) => + Effect.gen(function* () { + const result = yield* output.truncate({ content: [{ type: "text", text: "a\n\n\nb" }] }) + expect(result.content).toEqual([ + { type: "text", text: "a\n" }, + { type: "text", text: expect.stringMatching(/^\[showing lines 1-2 of 4;/) }, + ]) + }), + { maxLines: 2, maxBytes: 1_000 }, + ), + ) + + it.live("shows nothing under a zero line limit", () => + withStore( + (output) => + Effect.gen(function* () { + const result = yield* output.truncate({ content: [{ type: "text", text: "secret" }] }) + expect(result.content).toEqual([{ type: "text", text: expect.stringMatching(/^\[showing 0 lines of 1;/) }]) + }), + { maxLines: 0, maxBytes: 1_000 }, + ), + ) + + it.live("joins text parts with a line break only where one is missing", () => + withStore( + (output, fs) => + Effect.gen(function* () { + const result = yield* output.truncate({ + content: [ + { type: "text", text: "one\n" }, + { type: "text", text: "two" }, + { type: "text", text: "three" }, + ], + }) + const outputPath = result.metadata?.outputPath + expect(typeof outputPath).toBe("string") + if (typeof outputPath !== "string") return + expect(yield* fs.readFileString(outputPath)).toBe("one\ntwo\nthree") + expect(result.content).toEqual([ + { type: "text", text: "one\n" }, + { type: "text", text: "two" }, + { type: "text", text: expect.stringMatching(/^\[showing lines 1-2 of 3;/) }, + ]) + }), + { maxLines: 2, maxBytes: 1_000 }, + ), + ) + it.live("preserves mixed content ordering", () => withStore( (output) => @@ -144,7 +305,10 @@ describe("ToolOutput", () => { const result = yield* output.truncate({ content: [{ type: "text", text: "one\n" }] }) expect(result.content).toEqual([ { type: "text", text: "one" }, - { type: "text", text: expect.stringMatching(/^\[showing lines 1-1 of 1; full output saved to /) }, + { + type: "text", + text: expect.stringMatching(/^\[showing lines 1-1 of 1; full output saved to /), + }, ]) }), { maxLines: 2, maxBytes: 3 }, diff --git a/packages/core/test/tool-read-filesystem.test.ts b/packages/core/test/tool-read-filesystem.test.ts index f60db5839a58..f4997f9b4b27 100644 --- a/packages/core/test/tool-read-filesystem.test.ts +++ b/packages/core/test/tool-read-filesystem.test.ts @@ -392,6 +392,53 @@ describe("ReadToolFileSystem", () => { }), ) + it.effect("reads the end of a file many chunks long", () => + Effect.gen(function* () { + const { environment, files, directory } = yield* fixture + const read = (name: string, content: string | Uint8Array, page: ReadToolFileSystem.PageInput) => + (typeof content === "string" + ? files.writeFileString(path.join(directory, name), content) + : files.writeFile(path.join(directory, name), content) + ).pipe( + Effect.andThen(ReadToolFileSystem.read(environment, absolute(path.join(directory, name)), name, page)), + Effect.map((result) => String(ReadTool.toModelContent(name, page.offset, result)).split("\n")), + ) + // 60,000 lines of 51 bytes span 12 chunks. + const lines = Array.from({ length: 60_000 }, (_, index) => `${index + 1}`.padEnd(50, "x")) + const content = lines.join("\n") + "\n" + const expected = (from: number, to: number) => + lines.slice(from - 1, to).map((line, index) => `${from + index}: ${line}`) + + expect(yield* read("negative.txt", content, { offset: -5 })).toEqual([ + "Read file negative.txt, lines 59996-60000", + ...expected(59_996, 60_000), + ]) + expect(yield* read("past.txt", content, { offset: 70_000, limit: 3 })).toEqual([ + "Read file past.txt, lines 59998-60000 (offset 70000 is past the end; the file has 60000 lines)", + ...expected(59_998, 60_000), + ]) + expect(yield* read("deep.txt", content, { offset: 45_000, limit: 2 })).toEqual([ + "Read file deep.txt, lines 45000-45001", + ...expected(45_000, 45_001), + "[Output truncated. Continue reading with offset: 45002]", + ]) + // Far from the end, a negative offset still reads from the line it counts back to. + expect(yield* read("far.txt", content, { offset: -10_000, limit: 3 })).toEqual([ + "Read file far.txt, lines 50001-50003", + ...expected(50_001, 50_003), + "[Output truncated. Continue reading with offset: 50004]", + ]) + + // A null byte in an earlier scanned chunk still marks the file as binary. + const early = new TextEncoder().encode(content) + early[10] = 0 + const negative = yield* read("early-nul.txt", early, { offset: -5 }).pipe(Effect.flip) + expect(negative).toBeInstanceOf(ReadToolFileSystem.BinaryFileError) + const past = yield* read("early-nul-past.txt", early, { offset: 70_000 }).pipe(Effect.flip) + expect(past).toBeInstanceOf(ReadToolFileSystem.BinaryFileError) + }), + ) + it.effect("rejects a negative offset for a directory", () => Effect.gen(function* () { const { environment, files, directory } = yield* fixture @@ -496,6 +543,33 @@ describe("ReadToolFileSystem", () => { }), ) + it.live("ignores a NUL after a chunked page but rejects it for a past-end offset", () => + Effect.gen(function* () { + const { environment, files, directory } = yield* fixture + const file = absolute(path.join(directory, "nul.txt")) + yield* files.writeFileString(file, `${"x".repeat(256 * 1024)}\nselected\n\0\ntail`) + const read = (offset: number) => ReadToolFileSystem.read(environment, file, "nul.txt", { offset, limit: 1 }) + + for (const offset of [2, -3]) { + expect(yield* read(offset)).toMatchObject({ content: "selected", offset: 2, truncated: true, next: 3 }) + } + expect(yield* read(5).pipe(Effect.flip)).toBeInstanceOf(ReadToolFileSystem.BinaryFileError) + }), + ) + + it.live("keeps a split byte order mark in a past-end tail and strips it at a negative offset", () => + Effect.gen(function* () { + const { environment, files, directory } = yield* fixture + const file = absolute(path.join(directory, "marked.txt")) + // The first byte of the three-byte UTF-8 mark is the last byte of the first chunk. + yield* files.writeFileString(file, `${"x".repeat(256 * 1024 - 2)}\n\uFEFFselected`) + const read = (offset: number) => ReadToolFileSystem.read(environment, file, "marked.txt", { offset, limit: 1 }) + + expect(yield* read(3)).toMatchObject({ content: "\uFEFFselected", offset: 2, truncated: false }) + expect(yield* read(-1)).toMatchObject({ content: "selected", offset: 2, truncated: false }) + }), + ) + it.effect("checks skipped lines for null bytes", () => Effect.gen(function* () { const { environment, files, directory } = yield* fixture diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 9e96e55e4480..0954d32c4d4a 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -127,7 +127,6 @@ const executionNode = makeGlobalNode({ resume: complete, wake: () => Effect.void, interrupt: () => Effect.succeed(false), - periodStartSeq: () => Effect.succeed(undefined), awaitIdle: (id) => complete(id).pipe(Effect.exit, Effect.asVoid), }) }), @@ -232,8 +231,6 @@ const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({ }) const isWindows = process.platform === "win32" -// Shell commands only run in the process daemon off Windows (pipe mode is Unix-only), so these cases have no daemon there. -const daemonLive = isWindows ? fakeDaemonIt.live.skip : fakeDaemonIt.live // The process daemon keeps a finished command's zombie until the command is forgotten. const running = (pid: number) => { @@ -1806,7 +1803,7 @@ describe("ShellTool", () => { }), ) - daemonLive("keeps a background daemon command's job across a Location reload and reports how it ended", () => + fakeDaemonIt.live("keeps a background daemon command's job across a Location reload and reports how it ended", () => withTempDir((tmp) => Effect.gen(function* () { reset() @@ -2225,44 +2222,47 @@ describe("ShellTool stopped", () => { return { shellID, exit, result: Exit.isSuccess(exit) ? exit.value : undefined } }) - const test = isWindows ? parity.skip : parity.live - - test("stops a command the user stopped, keeps its file and fails the call with the tail, file and shell ID", () => - withTempDir((tmp) => { - reset() - return withSession(tmp.path, (registry) => - Effect.gen(function* () { - const shell = yield* Shell.Service - const jobs = yield* Job.Service - const { shellID, result } = yield* stopCall( - registry, - "printf 'first\\nsecond\\n'; sleep 60", - "call-stopped", - "cancel", - ) - const info = yield* shell.get(shellID) - expect(info.status).toBe("killed") - expect(yield* Effect.promise(() => fs.readFile(info.file, "utf8"))).toBe("first\nsecond\n") - expect(result).toEqual({ - status: "error", - error: { - type: "tool.execution", - message: `first\nsecond\n\n[full output saved to ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, - }, - }) - expect((yield* jobs.get(shellID))?.status).not.toBe("running") - }), - ) - })) + parity.live( + "stops a command the user stopped, keeps its file and fails the call with the tail, file and shell ID", + () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const jobs = yield* Job.Service + const { shellID, result } = yield* stopCall( + registry, + isWindows + ? "[Console]::Out.Write('first' + [char]10 + 'second' + [char]10); Start-Sleep -Seconds 60" + : "printf 'first\\nsecond\\n'; sleep 60", + "call-stopped", + "cancel", + ) + const info = yield* shell.get(shellID) + expect(info.status).toBe("killed") + expect(yield* Effect.promise(() => fs.readFile(info.file, "utf8"))).toBe("first\nsecond\n") + expect(result).toEqual({ + status: "error", + error: { + type: "tool.execution", + message: `first\nsecond\n\n[full output saved to ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, + }, + }) + expect((yield* jobs.get(shellID))?.status).not.toBe("running") + }), + ) + }), + ) - test("ends a call the user stopped before its command started, without starting it", () => + parity.live("ends a call the user stopped before its command started, without starting it", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const result = yield* executeTool(registry, { - ...call({ command: "printf started > started" }, "call-early-stop"), + ...call({ command: "echo started > started" }, "call-early-stop"), // Already stopped, as when the user stops the step while the call waits for permission. cancel: Effect.void, }) @@ -2271,24 +2271,28 @@ describe("ShellTool stopped", () => { expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "started")).exists())).toBe(false) }), ) - })) + }), + ) - test("says once that a stopped command wrote nothing", () => + parity.live("says once that a stopped command wrote nothing", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service - const { shellID, result } = yield* stopCall(registry, "sleep 60", "call-silent", "cancel", false) + const { shellID, result } = yield* stopCall(registry, idleCommand, "call-silent", "cancel", false) const info = yield* shell.get(shellID) expect(result?.error?.message).toBe( `[no output; output file: ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, ) }), ) - })) + }), + ) - test( + // Windows signals terminate the job immediately; a process cannot ignore SIGTERM there. + const ignoresTerm = isWindows ? parity.skip : parity.live + ignoresTerm( "settles a stopped call without waiting for a command that ignores SIGTERM", () => withTempDir((tmp) => { @@ -2325,7 +2329,7 @@ describe("ShellTool stopped", () => { // The step's own gate: a stop goes through `cancel` only if the tool is awaiting it. const cancel = SessionStep.makeCancel() const fiber = yield* executeTool(registry, { - ...call({ command: "sleep 60" }, id), + ...call({ command: idleCommand }, id), cancel: cancel.effect, }).pipe(Effect.forkChild({ startImmediately: true })) while (!fake?.ops.includes("create_pipe")) yield* Effect.promise(() => Bun.sleep(2)) @@ -2339,7 +2343,7 @@ describe("ShellTool stopped", () => { } }) - daemonLive("stops a command the user stopped while it was being created", () => + fakeDaemonIt.live("stops a command the user stopped while it was being created", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => @@ -2364,7 +2368,7 @@ describe("ShellTool stopped", () => { }), ) - daemonLive("stops a command the user stopped after its Location reloaded", () => + fakeDaemonIt.live("stops a command the user stopped after its Location reloaded", () => withTempDir((tmp) => Effect.gen(function* () { reset() @@ -2380,7 +2384,7 @@ describe("ShellTool stopped", () => { const cancel = SessionStep.makeCancel() const started = yield* Deferred.make() const fiber = yield* executeTool(registry, { - ...call({ command: "sleep 60" }, "call-reloaded"), + ...call({ command: idleCommand }, "call-reloaded"), progress: (update) => typeof update.shellID === "string" ? Deferred.succeed(started, update.shellID).pipe(Effect.asVoid) @@ -2403,7 +2407,7 @@ describe("ShellTool stopped", () => { for (const handoff of [false, true]) for (const starting of [true, false]) - daemonLive( + fakeDaemonIt.live( `${handoff ? "leaves a command running" : "stops a command"} when an interrupt ${handoff ? "during a handoff " : ""}cuts its call off while it ${starting ? "starts" : "runs"}`, () => withTempDir((tmp) => { @@ -2448,12 +2452,12 @@ describe("ShellTool stopped", () => { }), ) - daemonLive("records which call waits on a daemon command, and keeps no timeout for a restart", () => + fakeDaemonIt.live("records which call waits on a daemon command, and keeps no timeout for a restart", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { - const { shellID } = yield* stopCall(registry, "sleep 60", "call-recorded", "interrupt", false) + const { shellID } = yield* stopCall(registry, idleCommand, "call-recorded", "interrupt", false) const request = fake?.requests.find((item) => item.op === "create_pipe") expect(request?.metadata).toMatchObject({ id: shellID, @@ -2466,7 +2470,7 @@ describe("ShellTool stopped", () => { }), ) - test("lets an execute.after hook replace a stopped call's failure", () => + parity.live("lets an execute.after hook replace a stopped call's failure", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => @@ -2480,7 +2484,7 @@ describe("ShellTool stopped", () => { event.error = new Tool.Error({ message: "rewritten by a plugin" }) }), ) - const { shellID, result } = yield* stopCall(registry, "printf ready; sleep 60", "call-hooked", "cancel") + const { shellID, result } = yield* stopCall(registry, startingCommand, "call-hooked", "cancel") expect(seen).toEqual([ { interrupted: true, @@ -2492,20 +2496,22 @@ describe("ShellTool stopped", () => { expect(result?.error?.message).toBe("rewritten by a plugin") }), ) - })) + }), + ) - test("stops a command whose call an interrupt cut off, with no handoff to take it over", () => + parity.live("stops a command whose call an interrupt cut off, with no handoff to take it over", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const jobs = yield* Job.Service - const { shellID, exit } = yield* stopCall(registry, "printf ready; sleep 60", "call-teardown", "interrupt") + const { shellID, exit } = yield* stopCall(registry, startingCommand, "call-teardown", "interrupt") expect(Exit.hasInterrupts(exit)).toBe(true) expect((yield* shell.wait(shellID)).status).toBe("killed") expect((yield* jobs.get(shellID))?.status).toBe("cancelled") }), ) - })) + }), + ) }) diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index b7282ed1d61b..edc2d343d8c0 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" -import { Context, Deferred, Effect, Exit, Fiber, Layer, Schema, Scope, Stream } from "effect" -import { LanguageModel } from "@opencode/ai/effect" +import { Context, Deferred, Effect, Exit, Fiber, Layer, Schedule, Schema, Scope, Stream } from "effect" +import { AIError, InvalidRequestError, LanguageModel, LLMEvent } from "@opencode/ai/effect" import { OpenAIChat } from "@opencode/ai/protocols" import { TestLLM } from "@opencode/ai/testing" import path from "path" @@ -31,7 +31,6 @@ import { SessionMessage } from "@opencode/core/session/message" import { SessionRunnerModel } from "@opencode/core/session/runner/model" import { SessionStore } from "@opencode/core/session/store" import { SubagentJob } from "@opencode/core/session/subagent-job" -import { SubagentMetadata } from "@opencode/core/session/subagent-metadata" import { Plugin } from "@opencode/core/plugin" import { PluginHooks } from "@opencode/core/plugin/hooks" import { PluginSupervisor } from "@opencode/core/plugin/supervisor" @@ -45,9 +44,6 @@ import { testEffect } from "./lib/effect" import { executeTool, registerToolPlugin, toolIdentity } from "./lib/tool" const childText = "child final response" -const subagentOutput = (sessionID: Session.ID, output: string) => - `\n${output}\n` -const completedOutput = (sessionID: Session.ID) => subagentOutput(sessionID, childText) const childModel = Model.Ref.make({ id: Model.ID.make("child"), providerID: Provider.ID.make("test") }) const parentModel = Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }) const overrideModel = Model.Ref.make({ @@ -60,6 +56,18 @@ const tokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } const outputSessionID = (value: unknown) => Schema.decodeUnknownSync(Schema.Struct({ sessionID: Session.ID }))(value).sessionID +// Subagents always run in the background: their answers reach the caller as synthetic `` +// messages, visible once the caller's run has promoted them. +const deliveredTo = (sessionID: Session.ID, count: number) => + Session.Service.use((sessions) => + sessions.wait(sessionID).pipe( + Effect.andThen(sessions.context(sessionID)), + Effect.map((messages) => messages.flatMap((message) => (message.type === "synthetic" ? [message.text] : []))), + Effect.repeat({ until: (texts) => texts.length >= count, schedule: Schedule.spaced("20 millis") }), + Effect.timeout("20 seconds"), + ), + ) + const executionNode = makeGlobalNode({ service: SessionExecution.Service, layer: Layer.effect( @@ -112,7 +120,6 @@ const executionNode = makeGlobalNode({ resume: complete, wake: () => Effect.void, interrupt: () => Effect.succeed(false), - periodStartSeq: () => Effect.succeed(undefined), awaitIdle: (sessionID) => complete(sessionID).pipe(Effect.exit, Effect.asVoid), }) }), @@ -227,7 +234,7 @@ const withSubagent = (location: Location.Ref) => }) describe("SubagentTool", () => { - // AGENTS.md: a subagent reported as done must say what it left running. The child here answers and + // AGENTS.md: a subagent reported as idle must say what it left running. The child here answers and // goes idle with a shell and a subagent of its own still running in the background, and one that // already finished, which is not left running and is not mentioned. completionIt.live("says what a completed subagent left running in its own session", () => @@ -277,9 +284,9 @@ describe("SubagentTool", () => { agent: "reviewer", description: "review", }) - const output = (yield* jobs.wait({ id: child.id })).info?.output ?? "" + const output = (yield* deliveredTo(parent.id, 1))[0] ?? "" - expect(output.startsWith(childText)).toBe(true) + expect(output).toContain(childText) expect(output).toContain("Background work still running:") expect(output).toContain("- shell (shell-dev): bun run dev") expect(output).toContain("- subagent (reviewer, sessionID: ses_grandchild): audit dependencies") @@ -291,9 +298,9 @@ describe("SubagentTool", () => { ) // A caller that will act on the answer declares the fields it needs back. The child is told to end - // with them, and an answer that does not carry them fails the call with what it said, instead of - // handing the caller prose to guess at. - completionIt.live("returns the fields a caller declared, and fails an answer that does not carry them", () => + // with them, and its answer reaches the caller as those fields alone. One that does not carry them is + // covered by the next test. + completionIt.live("delivers the fields a caller declared", () => tmpdirScoped().pipe( Effect.flatMap((dir) => Effect.gen(function* () { @@ -323,27 +330,15 @@ describe("SubagentTool", () => { }) yield* llm.push(TestLLM.text('Checked.\n```json\n{ "summary": "two advisories", "count": 2 }\n```', "fields")) - const answered = yield* call("call-fields") - expect(answered).toMatchObject({ status: "completed", metadata: { status: "completed" } }) - const child = outputSessionID(answered.metadata) - expect(answered.content).toEqual([ - { - type: "text", - text: `\n${JSON.stringify({ summary: "two advisories", count: 2 }, null, 2)}\n`, - }, - ]) + const started = yield* call("call-fields") + expect(started).toMatchObject({ status: "completed", metadata: { status: "running" } }) + const child = outputSessionID(started.metadata) + const delivered = yield* deliveredTo(parent.id, 1) + expect(delivered[0]).toContain(` { agent: "reviewer", description: "background audit", prompt: "audit", - background: true, output: [{ name: "count", description: "How many", type: "number" }], }, }, @@ -399,9 +393,9 @@ describe("SubagentTool", () => { ), ) - // The fan-out runs its subtasks at once and reports each on its own: one that misses its declared + // The fan-out starts its subtasks at once and each reports on its own: one that misses its declared // fields is an error beside a sibling that completed, not a failure of the whole call. - completionIt.live("runs subtasks at the same time and reports each outcome on its own", () => + completionIt.live("starts subtasks at the same time and each reports its own outcome", () => tmpdirScoped().pipe( Effect.flatMap((dir) => Effect.gen(function* () { @@ -442,16 +436,20 @@ describe("SubagentTool", () => { yield* gate.release const result = yield* Fiber.join(run) + // The call itself only starts them: each subtask's answer arrives as its own message. expect(result).toMatchObject({ status: "completed" }) const text = result.status === "completed" ? (result.content ?? []).map((part) => ("text" in part ? part.text : "")).join("") : "" - expect(text).toMatch( - /\n\{\n "count": 3\n\}\n<\/subagent>/, + expect(text).toMatch(//) + expect(text).toMatch(//) + const delivered = yield* deliveredTo(parent.id, 2) + expect(delivered.find((message) => message.includes('description="alpha"'))).toMatch( + /state="completed" description="alpha">\n\{\n "count": 3\n\}\n<\/subagent>/, ) - expect(text).toMatch( - /\nSubagent did not return the requested fields \(sessionID: ses_\w+\)/, + expect(delivered.find((message) => message.includes('description="beta"'))).toMatch( + /state="error" description="beta">\nSubagent did not return the requested fields \(sessionID: ses_\w+\)/, ) }), ), @@ -533,7 +531,7 @@ describe("SubagentTool", () => { type: "tool-call", id: "call-completion-replay", name: SubagentTool.name, - input: { agent: "reviewer", description: "background review", prompt: "review", background: true }, + input: { agent: "reviewer", description: "background review", prompt: "review" }, }, }) const marker = yield* Deferred.await(admitted) @@ -680,12 +678,13 @@ describe("SubagentTool", () => { expect(settled).toMatchObject({ status: "completed", - metadata: { status: "completed" }, - content: [{ type: "text", text: expect.stringContaining(childText) }], + output: { status: "running" }, + metadata: { status: "running" }, + content: [{ type: "text", text: expect.stringContaining("working in the background") }], }) expect(settled.metadata).toEqual({ sessionID: outputSessionID(settled.metadata), - status: "completed", + status: "running", }) expect((yield* sessions.get(outputSessionID(settled.metadata))).parentID).toBe(parent.id) }), @@ -693,7 +692,7 @@ describe("SubagentTool", () => { ), ) - it.live("runs a foreground child session and returns the final assistant text", () => + it.live("starts a child session and returns the running handle", () => tmpdirScoped().pipe( Effect.flatMap((dir) => Effect.gen(function* () { @@ -719,12 +718,14 @@ describe("SubagentTool", () => { expect(settled).toMatchObject({ status: "completed", - metadata: { status: "completed" }, - content: [{ type: "text", text: expect.stringContaining(childText) }], + output: { status: "running" }, + metadata: { status: "running" }, + content: [{ type: "text", text: expect.stringContaining("working in the background") }], }) const child = yield* sessions.get(outputSessionID(settled.metadata)) - expect(settled.content).toEqual([{ type: "text", text: completedOutput(child.id) }]) - expect(settled.metadata).toEqual({ sessionID: child.id, status: "completed" }) + expect(settled.output).toMatchObject({ sessionID: child.id, status: "running" }) + expect(settled.output.output).toContain(`sessionID: ${child.id}`) + expect(settled.metadata).toEqual({ sessionID: child.id, status: "running" }) expect(progress[0]).toEqual({ sessionID: child.id, status: "running" }) expect(child).toMatchObject({ parentID: parent.id, @@ -800,7 +801,11 @@ describe("SubagentTool", () => { message.type === "user" ? [message.payload.text] : [], ), ).toEqual(["You are a subagent spawned by another session.\nreview this", "continue this"]) - expect(second.content).toEqual([{ type: "text", text: completedOutput(childID) }]) + expect(second).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) }), ), ), @@ -837,13 +842,13 @@ describe("SubagentTool", () => { description: "follow up", prompt: "continue while running", sessionID: child.id, - background: true, }, }, }) expect(result).toMatchObject({ status: "completed", + output: { status: "running" }, metadata: { sessionID: child.id, status: "running" }, }) expect((yield* sessions.inbox(child.id)).find((message) => message.type === "user")?.payload.text).toBe( @@ -856,7 +861,7 @@ describe("SubagentTool", () => { ), ) - completionIt.live("follow-ups to a running background child return immediately and notify once", () => + completionIt.live("follow-ups to a running child return immediately and notify once", () => tmpdirScoped().pipe( Effect.flatMap((dir) => Effect.gen(function* () { @@ -876,7 +881,7 @@ describe("SubagentTool", () => { Stream.runCollect, Effect.forkScoped({ startImmediately: true }), ) - const call = (id: string, input: { background?: boolean; sessionID?: Session.ID }) => + const call = (id: string, input: { sessionID?: Session.ID }) => executeTool(registry, { sessionID: parent.id, ...toolIdentity, @@ -888,12 +893,12 @@ describe("SubagentTool", () => { }, }).pipe(Effect.timeout("2 seconds")) - const launched = yield* call("call-launch", { background: true }) + const launched = yield* call("call-launch", {}) const childID = outputSessionID(launched.metadata) yield* gate.started - const steered = yield* call("call-steer", { background: true, sessionID: childID }) - const unflagged = yield* call("call-steer-foreground", { sessionID: childID }) - ;[launched, steered, unflagged].forEach((result) => + const steered = yield* call("call-steer", { sessionID: childID }) + const followed = yield* call("call-steer-again", { sessionID: childID }) + ;[launched, steered, followed].forEach((result) => expect(result).toMatchObject({ metadata: { sessionID: childID, status: "running" } }), ) @@ -984,7 +989,8 @@ describe("SubagentTool", () => { }) expect(yield* call(switched.id, "call-switched-child")).toMatchObject({ status: "completed", - metadata: { sessionID: switched.id, status: "completed" }, + output: { status: "running" }, + metadata: { sessionID: switched.id, status: "running" }, }) expect(yield* sessions.get(switched.id)).toMatchObject({ agent: "reviewer", @@ -993,7 +999,8 @@ describe("SubagentTool", () => { // Switching to an agent without a configured model keeps the child's current model. expect(yield* call(switched.id, "call-modelless-switch", "fallback")).toMatchObject({ status: "completed", - metadata: { sessionID: switched.id, status: "completed" }, + output: { status: "running" }, + metadata: { sessionID: switched.id, status: "running" }, }) expect(yield* sessions.get(switched.id)).toMatchObject({ agent: "fallback", @@ -1028,13 +1035,21 @@ describe("SubagentTool", () => { // The requested model beats the agent's configured model. const spawned = yield* call("call-override", { model: "test/override#fast", sessionID: "" }) - expect(spawned).toMatchObject({ status: "completed", metadata: { status: "completed" } }) + expect(spawned).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { status: "running" }, + }) const child = yield* sessions.get(outputSessionID(spawned.metadata)) expect(child).toMatchObject({ agent: "reviewer", model: overrideModel }) // Continuing with a model switches the existing child even when the agent is unchanged. const continued = yield* call("call-override-continue", { sessionID: child.id, model: "test/override" }) - expect(continued).toMatchObject({ status: "completed", metadata: { sessionID: child.id } }) + expect(continued).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: child.id, status: "running" }, + }) expect((yield* sessions.get(child.id)).model).toEqual({ id: overrideModel.id, providerID: overrideModel.providerID, @@ -1066,40 +1081,6 @@ describe("SubagentTool", () => { ), ) - it.live("returns child runner failures as tool errors", () => - tmpdirScoped().pipe( - Effect.flatMap((dir) => - Effect.gen(function* () { - const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) - const sessions = yield* Session.Service - const parent = yield* sessions.create({ location }) - yield* withSubagent(parent.location) - const locations = yield* LocationServiceMap.Service - const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) - - expect( - yield* executeTool(registry, { - sessionID: parent.id, - ...toolIdentity, - call: { - type: "tool-call", - id: "call-subagent-failure", - name: SubagentTool.name, - input: { agent: "reviewer", description: "fail review", prompt: "please fail" }, - }, - }), - ).toEqual({ - status: "error", - error: { - type: "tool.execution", - message: expect.stringContaining("No model is available for session"), - }, - }) - }), - ), - ), - ) - completionIt.live("notifies once when background work completes", () => tmpdirScoped().pipe( Effect.flatMap((dir) => @@ -1132,7 +1113,7 @@ describe("SubagentTool", () => { type: "tool-call", id: "call-background-subagent", name: SubagentTool.name, - input: { agent: "reviewer", description: "background review", prompt: "review", background: true }, + input: { agent: "reviewer", description: "background review", prompt: "review" }, }, }) const childID = outputSessionID(settled.metadata) @@ -1203,162 +1184,82 @@ const reportingFixture = () => }) describe("SubagentTool reporting", () => { - completionIt.live("returns a foreground answer inline without reporting to the parent", () => + completionIt.live("reports the child's final answer to the parent", () => Effect.gen(function* () { const fixture = yield* reportingFixture() - const settled = yield* fixture.call("call-foreground-inline") + const settled = yield* fixture.call("call-report") const childID = outputSessionID(settled.metadata) - expect(settled.status).toBe("completed") - expect(settled.content).toEqual([{ type: "text", text: completedOutput(childID) }]) - expect((yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent")).toEqual([]) + expect(settled).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) + yield* fixture.sessions.wait(childID) + yield* fixture.sessions.wait(fixture.parent.id) + + const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") + expect(reports).toHaveLength(1) + expect(reports[0]?.text).toContain(` + completionIt.live("reports only the current busy period when an idle child is continued", () => Effect.gen(function* () { const fixture = yield* reportingFixture() const llm = yield* TestLLM.Test yield* llm.push(TestLLM.text("first answer", "first")) - const first = yield* fixture.call("call-foreground-first") + const first = yield* fixture.call("call-first") const childID = outputSessionID(first.metadata) - expect(first.content).toEqual([{ type: "text", text: subagentOutput(childID, "first answer") }]) - - const second = yield* fixture.call("call-foreground-second", { sessionID: childID }) - expect(second.content).toEqual([{ type: "text", text: completedOutput(childID) }]) - }), - ) - - completionIt.live("includes still-running background work in a foreground answer", () => - Effect.gen(function* () { - const fixture = yield* reportingFixture() - const jobs = yield* Job.Service - const child = yield* fixture.sessions.create({ - parentID: fixture.parent.id, - title: "review", - agent: Agent.ID.make("reviewer"), - model: childModel, - }) - yield* jobs.start({ - id: "sh_foreground_shell", - type: "shell", - recovery: { kind: "shell", sessionID: child.id, shellID: "sh_1", command: "bun test --watch" }, - background: true, - run: Effect.never, - }) - - const settled = yield* fixture.call("call-foreground-running-shell", { sessionID: child.id }) - expect(settled.content).toEqual([ - { - type: "text", - text: subagentOutput( - child.id, - `${childText}\n\nBackground work still running:\n- shell (sh_1): bun test --watch`, - ), - }, - ]) - yield* jobs.cancel("sh_foreground_shell") - }), - ) - - completionIt.live("keeps a silent child silent until a follow-up enables notify", () => - Effect.gen(function* () { - const fixture = yield* reportingFixture() - const jobs = yield* Job.Service - const spawned = yield* fixture.call("call-silent-spawn", { background: true, notify: false }) - const childID = outputSessionID(spawned.metadata) - expect(spawned.content).toEqual([ - { - type: "text", - text: `The subagent is working in the background (sessionID: ${childID}) and will not notify you when it finishes. To check on it, call the subagent tool with this sessionID or read the session.`, - }, - ]) - expect((yield* fixture.sessions.get(childID)).metadata).toEqual({ "subagent.notify": false }) yield* fixture.sessions.wait(childID) yield* fixture.sessions.wait(fixture.parent.id) - expect(yield* fixture.notices).toEqual([]) - - // Omitted notify keeps the child silent across follow-ups. - const silent = yield* fixture.call("call-silent-follow", { sessionID: childID, background: true }) - expect(silent.content).toEqual(spawned.content) + const firstReports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") + expect(firstReports).toHaveLength(1) + expect(firstReports[0]?.text).toContain("first answer") + + const second = yield* fixture.call("call-second", { sessionID: childID }) + expect(second).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) yield* fixture.sessions.wait(childID) yield* fixture.sessions.wait(fixture.parent.id) - expect((yield* fixture.sessions.get(childID)).metadata).toEqual({ "subagent.notify": false }) - expect(yield* fixture.notices).toEqual([]) - const loud = yield* fixture.call("call-loud-follow", { sessionID: childID, background: true, notify: true }) - expect(loud.content).toEqual([ - { type: "text", text: expect.stringContaining("You will be notified automatically when it finishes.") }, - ]) - yield* fixture.sessions.wait(childID) - yield* fixture.sessions.wait(fixture.parent.id) - expect((yield* fixture.sessions.get(childID)).metadata).toEqual({}) const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") - expect(reports).toHaveLength(1) - expect(reports[0]?.text).toContain(` - Effect.gen(function* () { - const dir = yield* tmpdirScoped() - const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) - const sessions = yield* Session.Service - const parent = yield* sessions.create({ - location, - model: parentModel, - metadata: { [SubagentMetadata.KEY]: false }, - }) - yield* withSubagent(parent.location) - const locations = yield* LocationServiceMap.Service - const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) - - const spawned = yield* executeTool(registry, { - sessionID: parent.id, - ...toolIdentity, - call: { - type: "tool-call", - id: "call-silent-parent-child", - name: SubagentTool.name, - input: { agent: "reviewer", description: "review", prompt: "review this", background: true }, - }, - }) - const childID = outputSessionID(spawned.metadata) - // The link switch belongs to the child's link, not to the parent's own metadata. - expect((yield* sessions.get(childID)).metadata).toBeUndefined() - yield* sessions.wait(childID) - yield* sessions.wait(parent.id) - const delivered = (yield* sessions.context(parent.id)) - .filter((message) => message.type === "synthetic") - .filter((message) => message.metadata?.["source"] === "subagent") - expect(delivered).toHaveLength(1) - expect(delivered[0]?.text).toContain(` + completionIt.live("reports a child runner failure to the parent", () => Effect.gen(function* () { const fixture = yield* reportingFixture() const llm = yield* TestLLM.Test - const gate = yield* llm.gate() - const running = yield* fixture - .call("call-foreground-backgrounded", {}) - .pipe(Effect.forkScoped({ startImmediately: true })) - - yield* gate.started - yield* fixture.sessions.background(fixture.parent.id) - const settled = yield* Fiber.join(running) - const childID = outputSessionID(settled.metadata) - expect(settled).toMatchObject({ status: "completed", metadata: { sessionID: childID, status: "running" } }) + yield* llm.push( + TestLLM.failAfter( + new AIError({ reason: new InvalidRequestError({ message: "provider exploded" }) }), + LLMEvent.textStart({ id: "failed" }), + ), + ) - yield* gate.release + const settled = yield* fixture.call("call-failing-child", { description: "fail review" }) + const childID = outputSessionID(settled.metadata) + expect(settled).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) yield* fixture.sessions.wait(childID) yield* fixture.sessions.wait(fixture.parent.id) + const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") expect(reports).toHaveLength(1) - expect(reports[0]?.text).toContain(` { it.live("interrupts the child only for an explicit cancel and preserves shutdown claims", () => Effect.gen(function* () { const database = yield* Database.Service - const store = yield* SessionStore.Service const scope = yield* Scope.make() const cancelStarted = yield* Deferred.make() const shutdownStarted = yield* Deferred.make() @@ -1390,7 +1290,6 @@ describe("SubagentJob cancellation", () => { Effect.onInterrupt(() => Effect.sync(() => interrupted.add(sessionID))), ), wake: () => Effect.void, - periodStartSeq: () => Effect.succeed(0), interrupt: (sessionID) => Effect.sync(() => { interrupts.push(sessionID) @@ -1403,9 +1302,7 @@ describe("SubagentJob cancellation", () => { const context = yield* Layer.buildWithScope( SubagentJob.layer.pipe( Layer.provide(Layer.succeed(SessionExecution.Service, execution)), - Layer.provide(Layer.succeed(SessionStore.Service, store)), Layer.provide(Layer.succeed(Job.Service, jobs)), - Layer.provide(Layer.succeed(Database.Service, database)), ), scope, ) @@ -1418,7 +1315,7 @@ describe("SubagentJob cancellation", () => { description: "review", }) - yield* subagents.start(recovery("ses_job_cancel_parent", cancelChild), { background: true }) + yield* subagents.start(recovery("ses_job_cancel_parent", cancelChild)) yield* Deferred.await(cancelStarted) yield* jobs.cancel(cancelChild) expect(interrupted.has(cancelChild)).toBe(true) @@ -1426,7 +1323,7 @@ describe("SubagentJob cancellation", () => { expect(claimed.has(cancelChild)).toBe(false) // A server shutdown interrupts the job fiber but must not release the child's claim. - yield* subagents.start(recovery("ses_job_shutdown_parent", shutdownChild), { background: true }) + yield* subagents.start(recovery("ses_job_shutdown_parent", shutdownChild)) yield* Deferred.await(shutdownStarted) yield* Scope.close(scope, Exit.void) expect(interrupted.has(shutdownChild)).toBe(true) diff --git a/packages/data/core/src/resource.ts b/packages/data/core/src/resource.ts index 101afe530326..62a6575b78c7 100644 --- a/packages/data/core/src/resource.ts +++ b/packages/data/core/src/resource.ts @@ -1,7 +1,8 @@ // The stage's resources, read from the environment. Deployed Workers (services/data) get them as bindings, which // nodejs_compat copies into process.env; scripts on your machine read your exported variables. Each value is read // when used, so importing this module never touches the environment. -const ACCOUNT_ID = "15d29c8639fd3733b1b5486a2acfd968" +const PRODUCTION_ACCOUNT_ID = "15d29c8639fd3733b1b5486a2acfd968" +const DEV_ACCOUNT_ID = "d8e944f537ceef3f06a5bd3aec1d7a53" function required(name: string) { const value = process.env[name] @@ -36,7 +37,9 @@ export const Resource = { }, }, R2Sql: { - accountId: ACCOUNT_ID, + get accountId() { + return stage() === "dev" ? (process.env.R2_SQL_ACCOUNT_ID ?? DEV_ACCOUNT_ID) : PRODUCTION_ACCOUNT_ID + }, namespace: "inference", table: "generation", get bucket() { diff --git a/packages/gui-plugins/src/browser/model.ts b/packages/gui-plugins/src/browser/model.ts index 6bf26ae72d4a..5b759c73f493 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -379,8 +379,9 @@ export function createModel(ctx: SetupContext) { setState("pages", sessionKey, undefined) } - // A server whose plugin lacked the browser RPC may have it once its event stream reconnects or a restarted server - // replaces its controller. Leaving the list ends the watch too: its next session asks again. + // A server whose plugin lacked the browser RPC may have it once its plugins finish loading, its event stream + // reconnects, or a restarted server replaces its controller. Leaving the list ends the watch too: its next session + // asks again. const watchServer = (serverID: string) => { servers.get(serverID)?.() const changed = () => queueMicrotask(() => dispatch({ type: "server.changed", serverID })) @@ -397,6 +398,7 @@ export function createModel(ctx: SetupContext) { (data) => { if (data !== marked) return changed() onCleanup(data.on("server.connected", changed)) + onCleanup(data.on("plugin.updated", changed)) }, { otherwise: changed }, ) diff --git a/packages/plugin/src/gui/host-apis.ts b/packages/plugin/src/gui/host-apis.ts index fe7fc28731fb..7913f8bd4b44 100644 --- a/packages/plugin/src/gui/host-apis.ts +++ b/packages/plugin/src/gui/host-apis.ts @@ -685,7 +685,7 @@ export interface Composer { focused(): boolean } -/** Work the session moved to the background. */ +/** A running subagent or background shell command of the session. */ export interface BackgroundTask { /** The task's id. */ id: string @@ -737,7 +737,7 @@ export interface MountedSession extends SessionRef { readonly directory: string /** The session runs in the project root rather than a worktree. Reactive. */ readonly local: boolean - /** Shell commands and subagents the session moved to the background; empty once another session is routed. */ + /** Running subagents and background shell commands of the session; empty once another session is routed. */ readonly background: readonly BackgroundTask[] } diff --git a/packages/process-daemon/Cargo.lock b/packages/process-daemon/Cargo.lock index 51e585e6dba7..45e56cbf5b2b 100644 --- a/packages/process-daemon/Cargo.lock +++ b/packages/process-daemon/Cargo.lock @@ -184,7 +184,7 @@ dependencies = [ [[package]] name = "opencode-pty" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "base64", diff --git a/packages/process-daemon/Cargo.toml b/packages/process-daemon/Cargo.toml index 91af213a5c05..136a2b8fadce 100644 --- a/packages/process-daemon/Cargo.toml +++ b/packages/process-daemon/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencode-pty" -version = "0.5.1" +version = "0.5.2" edition = "2024" rust-version = "1.90" description = "Persistent PTY service for OpenCode" diff --git a/packages/process-daemon/SPEC.md b/packages/process-daemon/SPEC.md index 55a35075ca32..bb1d679a6b8d 100644 --- a/packages/process-daemon/SPEC.md +++ b/packages/process-daemon/SPEC.md @@ -145,12 +145,13 @@ starts a pipe process: any command without a terminal. Both return - On Unix the child gets its own process group and an empty signal mask with default actions (the daemon blocks SIGTERM and SIGINT, and std keeps the mask across exec). On Windows it is created with `CREATE_NO_WINDOW` (no - console window and no console) and is placed in a kill-on-close job from - creation. The program is resolved the way `CreateProcessW` resolves a bare - executable name (the application directory, the current directory, the - system directories and `PATH`); the daemon does not run a shell unless the - request itself asks for one, and passing `["/c", command]` to `cmd.exe` is - the caller's job. + console) inside a kill-on-close job. For a bare executable name, + `CreateProcessW` searches the directory containing the daemon executable, + the daemon's current directory, the 32-bit and then 16-bit Windows system + directories, the Windows directory, and finally the directories in the + daemon's `PATH`. This search is independent of the request's `cwd` and `env`, + which set the child's working directory and environment. To invoke a shell, + the caller must request one explicitly, e.g. `cmd.exe` with `["/c", command]`. - `output_path` must be absolute. The daemon opens it before spawning, truncating an existing file or creating one (mode `0666` minus the daemon's umask on Unix), and refuses a symlink or other reparse point as the final @@ -177,17 +178,17 @@ starts a pipe process: any command without a terminal. Both return nothing reads what comes later. The file is closed before the exit is published. - `Exited` and the lifecycle carry `signal`, the signal's name such as - `"SIGTERM"`, when the daemon terminated the process; `exit_code` is then - null. `signal` is left out when there is none. + `"SIGTERM"`, when a signal ended the process (on Windows, when the daemon + signalled it); `exit_code` is then null. `signal` is left out when there is + none. - On Unix an exited pipe process stays listed, as a zombie, until `terminate`. The zombie keeps its PID and process group ID reserved, so killing the group can never reach an unrelated process. On Windows the process object and job handle stay open until `terminate`, so the PID is not reused either. - `terminate` kills the whole tree (SIGKILL on Unix; `TerminateJobObject`, or - the main process only when no job could be used, on Windows), reaps it and - removes the process; it never waits on a descendant that left the process - group or job and still holds the pipe. The daemon never deletes output - files. + `terminate` kills the whole tree (SIGKILL on Unix; the job on Windows), + reaps it and removes the process; it never waits on a descendant that left + the process group or job and still holds the pipe. The daemon never deletes + output files. ### Line count @@ -221,18 +222,17 @@ only; left out for PTYs), `output_error` (left out when there is none) and `signal { id, signal }` (pipe only; `"SIGTERM"`, `"SIGINT"` or `"SIGKILL"`) signals the process tree and returns `Ok`. On Unix the signal goes to the process group and the child, as a real signal. **On Windows every signal is a -hard kill** of the job (or of the main process when no job could be used) with -`TerminateJobObject`/`TerminateProcess`: there is no console and no console -control event, so SIGTERM and SIGINT cannot be caught or trapped, and the exit -reports the signal that was sent, not a platform exit code. Unlike -`terminate`, `signal` keeps the process: `wait` then gets a normal `Exited` -with `signal`. Signalling an exited process is allowed and reaches whatever is -left of its group or job (an empty group is not an error); after `terminate` -the process is gone and `signal` fails. If an outer job refuses the child -(`ERROR_ACCESS_DENIED`, for example a job with UI restrictions), the daemon -runs the command anyway without a job, logs a warning once, and kills only the -main process with `TerminateProcess`; descendants then survive a signal or -terminate. +hard kill** of the job: there is no console, so SIGTERM and SIGINT cannot be +caught, and the exit reports the signal that was sent, not a platform exit +code. Unlike `terminate`, `signal` keeps the process: `wait` then gets a normal +`Exited` with `signal`. Signalling an exited process is allowed and reaches +whatever is left of its group or job (an empty group is not an error); after +`terminate` the process is gone and `signal` fails. + +If an outer job refuses the child (`ERROR_ACCESS_DENIED`, for example a job +with UI restrictions), the daemon runs the command anyway without a job, logs +a warning once, and kills only the main process; descendants then survive a +signal or terminate. `metadata` on `create_pipe` is an opaque JSON object the daemon stores and returns as `pipe.metadata` without interpreting it. `set_metadata { id, diff --git a/packages/process-daemon/npm/package.json b/packages/process-daemon/npm/package.json index af51d40c5a5b..19e9c44e5a20 100644 --- a/packages/process-daemon/npm/package.json +++ b/packages/process-daemon/npm/package.json @@ -1,6 +1,6 @@ { "name": "@opencode/pty", - "version": "0.5.1", + "version": "0.5.2", "description": "Persistent PTY service for OpenCode", "type": "module", "license": "MIT", @@ -25,14 +25,14 @@ "index.js" ], "optionalDependencies": { - "@opencode/pty-darwin-arm64": "0.5.1", - "@opencode/pty-darwin-x64": "0.5.1", - "@opencode/pty-linux-arm64-gnu": "0.5.1", - "@opencode/pty-linux-arm64-musl": "0.5.1", - "@opencode/pty-linux-x64-gnu": "0.5.1", - "@opencode/pty-linux-x64-musl": "0.5.1", - "@opencode/pty-win32-arm64": "0.5.1", - "@opencode/pty-win32-x64": "0.5.1" + "@opencode/pty-darwin-arm64": "0.5.2", + "@opencode/pty-darwin-x64": "0.5.2", + "@opencode/pty-linux-arm64-gnu": "0.5.2", + "@opencode/pty-linux-arm64-musl": "0.5.2", + "@opencode/pty-linux-x64-gnu": "0.5.2", + "@opencode/pty-linux-x64-musl": "0.5.2", + "@opencode/pty-win32-arm64": "0.5.2", + "@opencode/pty-win32-x64": "0.5.2" }, "publishConfig": { "access": "public" diff --git a/packages/process-daemon/src/daemon/windows.rs b/packages/process-daemon/src/daemon/windows.rs index 973cab2278f3..16b1b3aa795b 100644 --- a/packages/process-daemon/src/daemon/windows.rs +++ b/packages/process-daemon/src/daemon/windows.rs @@ -30,7 +30,7 @@ use windows_sys::Win32::System::WindowsProgramming::{ use super::{LOCK_FILE, REGISTRATION_FILE, Registration, registration_path, sweep}; use crate::protocol::{PROTOCOL_VERSION, features}; use crate::transport::Listener; -use crate::transport::windows::{owned_handle, security::PrivateSecurity}; +use crate::transport::windows::{owned_handle, security::PrivateSecurity, wide}; pub(super) fn read_registration(directory: &Path) -> Result { let security = PrivateSecurity::new()?; @@ -74,9 +74,9 @@ impl Runtime { if let Some(parent) = directory.parent() { fs::create_dir_all(parent)?; } - let wide = wide_path(directory)?; + let directory_wide = wide(directory.as_os_str())?; // SAFETY: wide path and private descriptor are valid through creation. - if unsafe { CreateDirectoryW(wide.as_ptr(), &security.attributes()) } == 0 { + if unsafe { CreateDirectoryW(directory_wide.as_ptr(), &security.attributes()) } == 0 { let error = std::io::Error::last_os_error(); if error.raw_os_error() != Some(ERROR_ALREADY_EXISTS as i32) { return Err(error.into()); @@ -300,7 +300,7 @@ fn open( sharing: u32, security: &PrivateSecurity, ) -> Result { - let path = wide_path(path)?; + let path = wide(path.as_os_str())?; // SAFETY: all pointers are valid; OPEN_REPARSE_POINT lets check_kind reject // links rather than inspecting a different target after following them. let handle = unsafe { @@ -332,15 +332,6 @@ fn check_kind(file: &File, directory: bool) -> Result<()> { Ok(()) } -fn wide_path(path: &Path) -> Result> { - let mut wide = path.as_os_str().encode_wide().collect::>(); - if wide.contains(&0) { - bail!("PTY storage path contains NUL"); - } - wide.push(0); - Ok(wide) -} - #[cfg(test)] mod tests { use super::*; diff --git a/packages/process-daemon/src/service/pipe.rs b/packages/process-daemon/src/service/pipe.rs index b630bf2d44f7..f2a39135c580 100644 --- a/packages/process-daemon/src/service/pipe.rs +++ b/packages/process-daemon/src/service/pipe.rs @@ -21,7 +21,7 @@ use std::fs::File; use std::io::{self, Write}; use std::sync::{Arc, Mutex, RwLock}; -use std::thread::JoinHandle; +use std::thread::{self, JoinHandle}; use std::time::Duration; use anyhow::{Context, Result}; @@ -149,10 +149,11 @@ fn new_pipe_info(id: TerminalId, pid: u32, request: CreatePipe) -> ProcessInfo { } } -/// The platform reader and waiter, each spawning its named worker thread. -struct Threads { - reader: Box io::Result>>, - waiter: Box) -> io::Result>>, +/// The waiter's result, and something dropped only after the exit message is +/// sent (Unix starts the reader's drain by dropping a pipe writer). +struct Waiter { + exit: io::Result, + after: Box, } /// Registers a spawned pipe process with its actor, then runs the platform's @@ -163,9 +164,9 @@ fn start_pipe( order: u64, request: CreatePipe, process: Arc, - sink: File, cancel: Box, - threads: Threads, + reader: impl FnOnce(Sender) + Send + 'static, + waiter: impl FnOnce() -> Waiter + Send + 'static, ) -> Result { let info = Arc::new(RwLock::new(new_pipe_info(id, process.pid(), request))); // Nothing is ever written to a pipe process; a disconnected queue @@ -196,21 +197,33 @@ fn start_pipe( thread, } = actor; let mut joins = vec![thread]; - let reader = (threads.reader)(OutputSink::new(sink, actor_tx.clone())); + let reader_actor_tx = actor_tx.clone(); + let reader = thread::Builder::new() + .name(format!("opencode-pty-reader-{id}")) + .spawn(move || reader(reader_actor_tx)) + .context("failed to spawn terminal reader"); let reader = match reader { Ok(reader) => reader, Err(error) => { stop(shutdown_tx, cancel, &process, joins); - return Err(error).context("failed to spawn terminal reader"); + return Err(error); } }; joins.push(reader); - let waiter = (threads.waiter)(actor_tx.clone()); + let wait_actor_tx = actor_tx.clone(); + let waiter = thread::Builder::new() + .name(format!("opencode-pty-wait-{id}")) + .spawn(move || { + let Waiter { exit, after } = waiter(); + let _ = wait_actor_tx.send(exit_message(exit)); + drop(after); + }) + .context("failed to spawn terminal child waiter"); let waiter = match waiter { Ok(waiter) => waiter, Err(error) => { stop(shutdown_tx, cancel, &process, joins); - return Err(error).context("failed to spawn terminal child waiter"); + return Err(error); } }; joins.push(waiter); diff --git a/packages/process-daemon/src/service/pipe/unix.rs b/packages/process-daemon/src/service/pipe/unix.rs index 234be40fd33a..5b7016257604 100644 --- a/packages/process-daemon/src/service/pipe/unix.rs +++ b/packages/process-daemon/src/service/pipe/unix.rs @@ -20,14 +20,13 @@ use std::os::unix::fs::OpenOptionsExt; use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex, PoisonError, RwLock}; -use std::thread; use std::time::Instant; use anyhow::{Context, Result, bail}; use nix::errno::Errno; use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; -use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe}; +use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, start_pipe}; use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId}; /// Serializes pipe creation against `spawn`. macOS has no `pipe2`, so std @@ -127,32 +126,18 @@ impl TerminalHandle { // Dropping `Child` neither waits nor kills; `Process` reaps it. drop(child); - let reader_id = id; - let waiter_id = id; + let pid = process.pid; start_pipe( id, order, request, Arc::clone(&process), - sink, Box::new(cancel_writer), - super::Threads { - reader: Box::new(move |sink| { - thread::Builder::new() - .name(format!("opencode-pty-reader-{reader_id}")) - .spawn(move || read_output(output, sink, cancel, exited)) - }), - waiter: Box::new(move |actor| { - let pid = process.pid; - // Spawned last: the waiter must be joined before `reap`. - thread::Builder::new() - .name(format!("opencode-pty-wait-{waiter_id}")) - .spawn(move || { - let _ = actor.send(exit_message(wait_exit(pid))); - // Starts the reader's drain deadline. - drop(exited_writer); - }) - }), + move |actor| read_output(output, OutputSink::new(sink, actor), cancel, exited), + move || super::Waiter { + exit: wait_exit(pid), + // Starts the reader's drain deadline, after the exit message. + after: Box::new(exited_writer), }, ) } diff --git a/packages/process-daemon/src/service/pipe/windows.rs b/packages/process-daemon/src/service/pipe/windows.rs index aba6c620d86f..2d55e6768dd9 100644 --- a/packages/process-daemon/src/service/pipe/windows.rs +++ b/packages/process-daemon/src/service/pipe/windows.rs @@ -9,35 +9,32 @@ use std::cmp::Ordering; use std::collections::HashMap; -use std::ffi::{OsStr, c_void}; -use std::fs::File; +use std::ffi::c_void; +use std::fs::{File, OpenOptions}; use std::io; +use std::marker::PhantomData; use std::mem::{size_of, size_of_val}; -use std::os::windows::ffi::OsStrExt; +use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; use std::os::windows::io::{AsRawHandle, OwnedHandle}; use std::path::Path; use std::ptr::{null, null_mut}; use std::sync::{Arc, Mutex, PoisonError}; -use std::thread; use std::time::Instant; use anyhow::{Context, Result, bail}; use windows_sys::Win32::Foundation::{ DUPLICATE_SAME_ACCESS, DuplicateHandle, ERROR_ACCESS_DENIED, ERROR_BROKEN_PIPE, - ERROR_IO_INCOMPLETE, ERROR_IO_PENDING, ERROR_NO_DATA, ERROR_OPERATION_ABORTED, - ERROR_PIPE_CONNECTED, ERROR_PIPE_NOT_CONNECTED, GENERIC_READ, GENERIC_WRITE, HANDLE, - WAIT_OBJECT_0, WAIT_TIMEOUT, + ERROR_IO_PENDING, ERROR_NO_DATA, ERROR_OPERATION_ABORTED, ERROR_PIPE_NOT_CONNECTED, + GENERIC_READ, GENERIC_WRITE, HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT, }; use windows_sys::Win32::Globalization::{ CSTR_EQUAL, CSTR_GREATER_THAN, CSTR_LESS_THAN, CompareStringOrdinal, }; use windows_sys::Win32::Security::SECURITY_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::{ - BY_HANDLE_FILE_INFORMATION, CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_REPARSE_POINT, - FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_FLAG_OVERLAPPED, - FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, - GetFileInformationByHandle, OPEN_ALWAYS, OPEN_EXISTING, PIPE_ACCESS_INBOUND, ReadFile, - SetEndOfFile, + CreateFileW, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_FIRST_PIPE_INSTANCE, + FILE_FLAG_OPEN_REPARSE_POINT, FILE_FLAG_OVERLAPPED, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, + FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, PIPE_ACCESS_INBOUND, ReadFile, }; use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED}; use windows_sys::Win32::System::JobObjects::{ @@ -46,8 +43,7 @@ use windows_sys::Win32::System::JobObjects::{ SetInformationJobObject, TerminateJobObject, }; use windows_sys::Win32::System::Pipes::{ - ConnectNamedPipe, CreateNamedPipeW, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, - PIPE_TYPE_BYTE, PIPE_WAIT, + CreateNamedPipeW, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_WAIT, }; use windows_sys::Win32::System::Threading::{ CREATE_NO_WINDOW, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList, @@ -58,10 +54,10 @@ use windows_sys::Win32::System::Threading::{ WaitForSingleObject, }; -use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe}; +use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, Waiter, start_pipe}; use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId}; use crate::transport::retained::Retained; -use crate::transport::windows::{event, owned_handle, security::PrivateSecurity}; +use crate::transport::windows::{event, owned_handle, security::PrivateSecurity, wide}; /// Cancel is first so a pipe that is always readable cannot starve it. const CANCEL_READY: u32 = WAIT_OBJECT_0; @@ -85,32 +81,27 @@ impl TerminalHandle { // clean up; the reader is the file's only writer. let sink = open_output(&request.output_path)?; let job = Job::new(id); - let process = Arc::new(spawn(id, &request, job.as_ref(), client)?); - let cancel = Cancel::new()?; - let reader = Arc::clone(&server); + let cancel = CancelOnDrop::new()?; + let process = Arc::new(spawn(id, &request, job, client)?); + let reader_cancel = Arc::clone(&cancel.0); let reader_process = Arc::clone(&process); - let reader_cancel = cancel.clone(); start_pipe( id, order, request, Arc::clone(&process), - sink, Box::new(cancel), - super::Threads { - reader: Box::new(move |sink| { - thread::Builder::new() - .name(format!("opencode-pty-reader-{id}")) - .spawn(move || read_output(reader, sink, reader_cancel, reader_process)) - }), - waiter: Box::new(move |actor| { - // Spawned last: the waiter must be joined before `reap`. - thread::Builder::new() - .name(format!("opencode-pty-wait-{id}")) - .spawn(move || { - let _ = actor.send(exit_message(wait_exit(process))); - }) - }), + move |actor| { + read_output( + server, + OutputSink::new(sink, actor), + reader_cancel, + reader_process, + ) + }, + move || Waiter { + exit: wait_exit(process), + after: Box::new(()), }, ) } @@ -121,16 +112,21 @@ impl TerminalHandle { #[derive(Debug)] pub(in crate::service) struct Process { pid: u32, + state: Mutex, +} + +#[derive(Debug)] +struct State { /// Taken by `reap`, which closes both handles. - handles: Mutex>, + handles: Option, /// The signal recorded by `kill`/`signal` before terminating the tree. - killed: Mutex>, + killed: Option<&'static str>, } #[derive(Debug)] struct Handles { process: Arc, - job: Option>, + job: Option, } impl Process { @@ -138,22 +134,24 @@ impl Process { self.pid } + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + /// The process object, kept open until `reap` so its PID cannot be reused. fn process_handle(&self) -> Option> { - self.handles - .lock() - .unwrap_or_else(PoisonError::into_inner) + self.lock() + .handles .as_ref() .map(|handles| Arc::clone(&handles.process)) } /// Kills the process tree. Never terminates after `reap`. pub(super) fn kill(&self) { - let handles = self.handles.lock().unwrap_or_else(PoisonError::into_inner); - let Some(handles) = handles.as_ref() else { + let mut state = self.lock(); + let Some(handles) = record_kill(&mut state, "SIGKILL") else { return; }; - self.record_kill("SIGKILL", handles); let _ = terminate(handles); } @@ -166,43 +164,36 @@ impl Process { ProcessSignal::Int => "SIGINT", ProcessSignal::Kill => "SIGKILL", }; - let handles = self.handles.lock().unwrap_or_else(PoisonError::into_inner); - let Some(handles) = handles.as_ref() else { + let mut state = self.lock(); + let Some(handles) = record_kill(&mut state, name) else { bail!("process has been reaped"); }; - self.record_kill(name, handles); terminate(handles).context("failed to signal process") } /// Call only after the waiter has returned: closes the process and job /// handles. Closing the job alone kills anything still in it. pub(super) fn reap(&self) { - self.handles - .lock() - .unwrap_or_else(PoisonError::into_inner) - .take(); + self.lock().handles.take(); } - /// Records the signal only while the process still runs, so a process that - /// exited on its own keeps its own exit code, as on Unix. - fn record_kill(&self, name: &'static str, handles: &Handles) { - // SAFETY: the handles lock keeps the process handle open. - if unsafe { WaitForSingleObject(handles.process.as_raw_handle(), 0) } == WAIT_TIMEOUT { - // Termination is asynchronous: the first signal that reached the - // running process is the one the client should see. - self.killed - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get_or_insert(name); - } + fn take_signal(&self) -> Option<&'static str> { + self.lock().killed.take() } +} - fn take_signal(&self) -> Option<&'static str> { - self.killed - .lock() - .unwrap_or_else(PoisonError::into_inner) - .take() +/// Records the signal while the process still runs, so a process that exited on +/// its own keeps its exit code, and returns the handles, or `None` after +/// `reap`. +fn record_kill<'a>(state: &'a mut State, name: &'static str) -> Option<&'a Handles> { + let handles = state.handles.as_ref()?; + // SAFETY: the state lock keeps the process handle open. + if !is_signalled(&handles.process) { + // Termination is asynchronous: the first signal that reached the + // running process is the one the client should see. + state.killed.get_or_insert(name); } + Some(handles) } /// Terminates the whole tree. @@ -230,34 +221,50 @@ fn terminate(handles: &Handles) -> io::Result<()> { fn spawn( id: TerminalId, request: &CreatePipe, - job: Option<&Job>, + job: Option, client: OwnedHandle, ) -> Result { - let process = match create_process(request, job, &client) { - Ok(process) => process, + let (created, job) = match create_process(request, job.as_ref(), &client) { + Ok(created) => (created, job), Err(error) if job.is_some() && error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => { // An outer job with UI restrictions refuses new members. Run the // command anyway; only the main process can be killed then. - let process = create_process(request, None, &client) + let created = create_process(request, None, &client) .with_context(|| format!("failed to spawn {}", request.program))?; eprintln!( "pipe process {id}: cannot join the job object, killing only the main process: {error}" ); - process + drop(job); + (created, None) } Err(error) => return Err(error).context(format!("failed to spawn {}", request.program)), }; // The daemon's copy of the child's write end: holding it open would keep // the pipe from ever breaking. drop(client); - Ok(process) + Ok(Process { + pid: created.pid, + state: Mutex::new(State { + handles: Some(Handles { + process: Arc::new(created.process), + job: job.map(|job| job.0), + }), + killed: None, + }), + }) +} + +/// A created process, before it is registered with its job and signal state. +struct Spawned { + pid: u32, + process: OwnedHandle, } fn create_process( request: &CreatePipe, job: Option<&Job>, client: &OwnedHandle, -) -> io::Result { +) -> io::Result { let stdin = null_handle()?; // A child that closes one of stdout or stderr must still write to the // other, so stderr gets its own handle to the same pipe. @@ -268,19 +275,7 @@ fn create_process( stderr.as_raw_handle(), ]; let jobs = job.map(|job| [job.handle()]); - let mut entries = vec![( - PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize, - handles.as_ptr().cast::(), - size_of_val(&handles), - )]; - entries.extend(jobs.as_ref().map(|jobs| { - ( - PROC_THREAD_ATTRIBUTE_JOB_LIST as usize, - jobs.as_ptr().cast::(), - size_of_val(jobs), - ) - })); - let attributes = Attributes::new(&entries)?; + let attributes = Attributes::new(&handles, jobs.as_ref().map(|jobs| jobs.as_slice()))?; let mut command = command_line(&request.program, &request.args)?; let environment = environment_block(&request.env)?; let directory = wide(request.cwd.as_os_str())?; @@ -316,13 +311,9 @@ fn create_process( // handle is not needed. let process = owned_handle(info.hProcess)?; drop(owned_handle(info.hThread)?); - Ok(Process { + Ok(Spawned { pid: info.dwProcessId, - handles: Mutex::new(Some(Handles { - process: Arc::new(process), - job: job.map(|job| Arc::clone(&job.0)), - })), - killed: Mutex::new(None), + process, }) } @@ -347,27 +338,16 @@ fn wait_exit(process: Arc) -> io::Result { }) } -/// Signals the reader to stop. Every clone can signal; the first drop sets the -/// event, and later ones are harmless. -#[derive(Clone)] -struct Cancel(Arc); +/// Sets the reader's cancel event when dropped. +struct CancelOnDrop(Arc); -impl Cancel { +impl CancelOnDrop { fn new() -> io::Result { event().map(|event| Self(Arc::new(event))) } - - fn handle(&self) -> HANDLE { - self.0.as_raw_handle() - } - - fn signalled(&self) -> bool { - // SAFETY: the shared event stays open through the call. - unsafe { WaitForSingleObject(self.0.as_raw_handle(), 0) == WAIT_OBJECT_0 } - } } -impl Drop for Cancel { +impl Drop for CancelOnDrop { fn drop(&mut self) { // SAFETY: the shared event stays open through the call. unsafe { @@ -385,12 +365,12 @@ struct Read { overlapped: Retained, buffer: Retained<[u8; READ_BYTES]>, event: OwnedHandle, - pipe: Arc, + pipe: OwnedHandle, pending: bool, } impl Read { - fn new(pipe: Arc) -> io::Result { + fn new(pipe: OwnedHandle) -> io::Result { let event = event()?; Ok(Self { overlapped: Retained::new(OVERLAPPED { @@ -435,8 +415,8 @@ impl Read { Ok(None) } - /// Reaps the completion. Waiting is required once the event is signalled: - /// the kernel may still be finishing the operation. + /// Reaps the completion. Waiting guarantees the kernel is done with the + /// buffers whether the read succeeded or failed. fn complete(&mut self) -> io::Result { let mut count = 0; // SAFETY: this operation was submitted and its buffers are live. @@ -448,18 +428,11 @@ impl Read { 1, ) }; - if completed != 0 { - self.pending = false; - return Ok(count as usize); - } - let error = io::Error::last_os_error(); - if error.raw_os_error() == Some(ERROR_IO_INCOMPLETE as i32) { - // Only possible without waiting; keep the operation pending so - // dropping `Read` cancels and reaps it. - return Err(error); - } self.pending = false; - Err(error) + if completed == 0 { + return Err(io::Error::last_os_error()); + } + Ok(count as usize) } /// The bytes of a completed read. @@ -498,8 +471,14 @@ impl Drop for Read { } /// Reads output until every writer is gone, until [`DRAIN_AFTER_EXIT`] after -/// the process exits, or until [`Cancel`] fires. -fn read_output(pipe: Arc, sink: OutputSink, cancel: Cancel, process: Arc) { +/// the process exits, or until the cancel event fires. Dropping `Read` cancels +/// and reaps a pending read and closes the pipe. +fn read_output( + pipe: OwnedHandle, + sink: OutputSink, + cancel: Arc, + process: Arc, +) { let mut sink = sink; let Some(process_object) = process.process_handle() else { return; @@ -512,112 +491,105 @@ fn read_output(pipe: Arc, sink: OutputSink, cancel: Cancel, process } }; // The process may have exited before the reader started. - let mut exited = process_exited(&process_object); + let mut exited = is_signalled(&process_object); let mut deadline = exited.then(|| Instant::now() + DRAIN_AFTER_EXIT); loop { // Cancellation and the exit win over output, so a descendant that // writes without pause cannot keep the reader from noticing them. - if cancel.signalled() { - sink.eof(); + if is_signalled(&cancel) { + // Like Unix, shutdown is not an EOF the actor needs to observe. return; } - if !exited && process_exited(&process_object) { + if !exited && is_signalled(&process_object) { exited = true; deadline = Some(Instant::now() + DRAIN_AFTER_EXIT); } if deadline.is_some_and(|deadline| Instant::now() >= deadline) { - // Dropping `read` cancels and reaps a pending operation. + // Close the pipe before reporting EOF. + drop(read); sink.eof(); return; } - if !read.is_pending() { - match read.submit() { - Ok(Some(0)) => { + let completed = if read.is_pending() { + let timeout = match deadline { + None => INFINITE, + Some(deadline) => { + let left = deadline.saturating_duration_since(Instant::now()); + // Round up: a sub-millisecond remainder must not be a busy 0. + left.as_nanos().div_ceil(1_000_000).min(u32::MAX as u128) as u32 + } + }; + // Cancel is first: WaitForMultipleObjects reports the lowest + // signalled index, so an always-readable pipe cannot starve it. + let handles = [ + cancel.as_raw_handle(), + read.event(), + process_object.as_raw_handle(), + ]; + // Once the exit is seen, stop waiting on its signalled handle. + let count = if exited { 2 } else { 3 }; + // SAFETY: every handle stays live through the wait. + match unsafe { WaitForMultipleObjects(count, handles.as_ptr(), 0, timeout) } { + CANCEL_READY => return, + READ_READY => Some(read.complete()), + PROCESS_READY => { + exited = true; + deadline = Some(Instant::now() + DRAIN_AFTER_EXIT); + None + } + WAIT_TIMEOUT => { + // The drain deadline passed with a descendant still holding the pipe open. + drop(read); sink.eof(); return; } - Ok(Some(length)) => { - // Check cancel, the exit and the deadline again before - // reading more. - if !sink.write(read.bytes(length)) { - return; - } - continue; - } - Ok(None) => {} - Err(error) => { - end_on_read_error(sink, error); + _ => { + let error = io::Error::last_os_error(); + drop(read); + sink.failed(error.to_string()); return; } } - } - let timeout = match deadline { - None => INFINITE, - Some(deadline) => { - let left = deadline.saturating_duration_since(Instant::now()); - // Round up: a sub-millisecond remainder must not become a busy 0. - left.as_nanos().div_ceil(1_000_000).min(u32::MAX as u128) as u32 + } else { + match read.submit() { + Ok(Some(length)) => Some(Ok(length)), + Ok(None) => None, + Err(error) => Some(Err(error)), } }; - // Cancel is first: WaitForMultipleObjects reports the lowest signalled - // index, so an always-readable pipe cannot starve it. - let handles = [ - cancel.handle(), - read.event(), - process_object.as_raw_handle(), - ]; - // Once the exit is seen, stop waiting on its signalled handle. - let count = if exited { 2 } else { 3 }; - // SAFETY: every handle stays live through the wait. - match unsafe { WaitForMultipleObjects(count, handles.as_ptr(), 0, timeout) } { - CANCEL_READY => { + let Some(result) = completed else { + continue; + }; + match result { + Ok(0) => { + drop(read); sink.eof(); return; } - READ_READY => match read.complete() { - Ok(0) => { - sink.eof(); - return; - } - Ok(length) => { - if !sink.write(read.bytes(length)) { - return; - } - } - Err(error) => { - end_on_read_error(sink, error); + Ok(length) => { + // The next iteration checks cancel, the exit and the deadline + // again before reading more. + if !sink.write(read.bytes(length)) { return; } - }, - PROCESS_READY => { - exited = true; - deadline = Some(Instant::now() + DRAIN_AFTER_EXIT); - } - WAIT_TIMEOUT => { - // The drain deadline passed with a descendant still writing. - sink.eof(); - return; } - _ => { - let error = io::Error::last_os_error(); - sink.failed(error.to_string()); + Err(error) => { + drop(read); + if is_end_of_output(&error) { + sink.eof(); + } else { + sink.failed(error.to_string()); + } return; } } } } -fn process_exited(process: &OwnedHandle) -> bool { - // SAFETY: the process handle stays open for the whole read. - unsafe { WaitForSingleObject(process.as_raw_handle(), 0) == WAIT_OBJECT_0 } -} - -fn end_on_read_error(sink: OutputSink, error: io::Error) { - if is_end_of_output(&error) { - sink.eof(); - } else { - sink.failed(error.to_string()); - } +/// Whether `handle` is signalled. +fn is_signalled(handle: &OwnedHandle) -> bool { + // SAFETY: the handle stays open through the zero-timeout wait. + unsafe { WaitForSingleObject(handle.as_raw_handle(), 0) == WAIT_OBJECT_0 } } fn is_end_of_output(error: &io::Error) -> bool { @@ -634,7 +606,7 @@ fn is_end_of_output(error: &io::Error) -> bool { /// The daemon's read end and the child's inheritable write end. struct OutputPipe { - server: Arc, + server: OwnedHandle, client: OwnedHandle, } @@ -659,11 +631,12 @@ fn output_pipe() -> Result { &security.attributes(), ) }; - let server = Arc::new(owned_handle(server).context("failed to create output pipe")?); + let server = owned_handle(server).context("failed to create output pipe")?; + // The client connects by opening the single instance; no ConnectNamedPipe + // is needed, as with Rust's anonymous pipes. Read attributes are included + // so clients that fstat their stdout (Git Bash, Python, Go) can query it. // SAFETY: the same NUL-terminated name; only the returned handle is - // inheritable, and it is the only handle of this open. Read attributes - // are included so clients that fstat their stdout (Git Bash, Python, Go) - // can query the pipe. + // inheritable, and it is the only handle of this open. let client = unsafe { CreateFileW( name.as_ptr(), @@ -676,48 +649,12 @@ fn output_pipe() -> Result { ) }; let client = owned_handle(client).context("failed to connect output pipe")?; - let connect_event = event()?; - let overlapped = Retained::new(OVERLAPPED { - hEvent: connect_event.as_raw_handle(), - ..Default::default() - }); - // The client end is already open, so the connect normally completes at - // once with ERROR_PIPE_CONNECTED instead of waiting. - if unsafe { ConnectNamedPipe(server.as_raw_handle(), overlapped.as_ptr()) } == 0 { - let error = io::Error::last_os_error(); - match error.raw_os_error() { - Some(code) if code == ERROR_PIPE_CONNECTED as i32 => {} - Some(code) if code == ERROR_IO_PENDING as i32 => { - let mut count = 0; - // SAFETY: the handle and the Retained OVERLAPPED stay live. - if unsafe { - GetOverlappedResult(server.as_raw_handle(), overlapped.as_ptr(), &mut count, 1) - } == 0 - { - let error = io::Error::last_os_error(); - // Never return while the kernel might still own the - // OVERLAPPED: cancel and reap the completion. - unsafe { - CancelIoEx(server.as_raw_handle(), overlapped.as_ptr()); - GetOverlappedResult( - server.as_raw_handle(), - overlapped.as_ptr(), - &mut count, - 1, - ); - } - return Err(error).context("failed to connect output pipe"); - } - } - _ => return Err(error).context("failed to connect output pipe"), - } - } Ok(OutputPipe { server, client }) } /// A kill-on-close job: terminating it kills every descendant, and a crashed /// daemon closes it and kills them too. -struct Job(Arc); +struct Job(OwnedHandle); impl Job { fn new(id: TerminalId) -> Option { @@ -750,7 +687,7 @@ impl Job { warn_no_job(id, &io::Error::last_os_error()); return None; } - Some(Self(Arc::new(job))) + Some(Self(job)) } fn handle(&self) -> HANDLE { @@ -766,35 +703,24 @@ fn warn_no_job(id: TerminalId, error: &io::Error) { /// to clean up. Truncates through the handle without following a reparse point /// planted at the final component. fn open_output(path: &Path) -> Result { - let name = wide(path.as_os_str())?; let message = format!("failed to open output file {}", path.display()); - // SAFETY: the name is NUL-terminated; the returned handle is inherited by - // nothing and adopted at once. - let handle = unsafe { - CreateFileW( - name.as_ptr(), - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - null(), - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, - null_mut(), - ) - }; - let file = File::from(owned_handle(handle).with_context(|| message.clone())?); - let mut info = BY_HANDLE_FILE_INFORMATION::default(); - // SAFETY: the file owns a live handle and info is valid writable output. - if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 { - return Err(io::Error::last_os_error()).with_context(|| message); - } - if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + let file = OpenOptions::new() + .write(true) + .create(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) + .with_context(|| message.clone())?; + if file + .metadata() + .with_context(|| message.clone())? + .file_attributes() + & FILE_ATTRIBUTE_REPARSE_POINT + != 0 + { bail!("{message}: output path is a reparse point"); } - // SAFETY: the handle has write access and the position is at the start - // after opening. - if unsafe { SetEndOfFile(file.as_raw_handle()) } == 0 { - return Err(io::Error::last_os_error()).with_context(|| message); - } + file.set_len(0).with_context(|| message)?; Ok(file) } @@ -923,23 +849,16 @@ fn environment_block(env: &HashMap) -> io::Result> { value.encode_utf16().collect::>(), )); } - // Sort deterministically before collapsing case variants, so the same - // request always produces the same block; the last variant wins. - entries.sort(); - entries.sort_by(|a, b| compare_keys(&a.0, &b.0)); - let mut unique: Vec<(Vec, Vec)> = Vec::with_capacity(entries.len()); - for entry in entries { - match unique.last_mut() { - Some(last) if compare_keys(&last.0, &entry.0) == Ordering::Equal => *last = entry, - _ => unique.push(entry), - } - } + // Case-insensitive order, with the ordinal-largest variant first so that + // deduplication keeps it: the same request always produces the same block. + entries.sort_by(|a, b| compare_keys(&a.0, &b.0).then_with(|| b.cmp(a))); + entries.dedup_by(|a, b| compare_keys(&a.0, &b.0) == Ordering::Equal); let mut block = Vec::new(); - // An empty environment is signalled by a null, like Rust std. - if unique.is_empty() { + // An empty environment is an empty entry before the terminating NUL. + if entries.is_empty() { block.push(0); } - for (key, value) in unique { + for (key, value) in entries { block.extend(key); block.push('=' as u16); block.extend(value); @@ -964,29 +883,31 @@ fn compare_keys(a: &[u16], b: &[u16]) -> Ordering { } } -fn wide(value: &OsStr) -> io::Result> { - let mut wide = value.encode_wide().collect::>(); - if wide.contains(&0) { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "path contains a NUL", - )); - } - wide.push(0); - Ok(wide) -} - /// An initialized process-attribute list and the buffer it points into, freed -/// in the right order. -struct Attributes { +/// in the right order. The lifetime ties it to the handle and job arrays its +/// values point into. +struct Attributes<'a> { // Never read: the list points into this allocation, which must stay put // and alive for the list's lifetime. _buffer: Vec, list: *mut c_void, + _attached: PhantomData<&'a ()>, } -impl Attributes { - fn new(entries: &[(usize, *const c_void, usize)]) -> io::Result { +impl<'a> Attributes<'a> { + fn new(handles: &'a [HANDLE], jobs: Option<&'a [HANDLE]>) -> io::Result { + let mut entries = vec![( + PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize, + handles.as_ptr().cast::(), + size_of_val(handles), + )]; + entries.extend(jobs.map(|jobs| { + ( + PROC_THREAD_ATTRIBUTE_JOB_LIST as usize, + jobs.as_ptr().cast::(), + size_of_val(jobs), + ) + })); let mut bytes = 0; // SAFETY: the first call only reports the required size. unsafe { @@ -1007,8 +928,9 @@ impl Attributes { let this = Self { _buffer: buffer, list, + _attached: PhantomData, }; - for &(attribute, value, length) in entries { + for &(attribute, value, length) in &entries { // SAFETY: the list was initialized for exactly `entries.len()` // attributes; every value outlives the list. if unsafe { @@ -1034,7 +956,7 @@ impl Attributes { } } -impl Drop for Attributes { +impl Drop for Attributes<'_> { fn drop(&mut self) { // SAFETY: the list was successfully initialized and is unused after. unsafe { @@ -1120,7 +1042,7 @@ mod tests { ]); let block = environment_block(&env).unwrap(); let block = text(&block); - // The last variant in ordinal order wins, deterministically. + // The ordinal-largest case variant wins, deterministically. assert_eq!(block, "=C:=C:\\work\0Path=lower\0\0"); for invalid in [("", "x"), ("=", "x"), ("A=B", "x"), ("A\0B", "x")] { @@ -1142,30 +1064,31 @@ mod tests { } #[test] - fn a_jobless_spawn_runs_the_command_and_reports_its_exit() { - let request = test_request("cmd.exe", &["/d", "/c", "exit /b 5"]); + fn signal_kills_a_jobless_child() { + let request = test_request("ping.exe", &["-n", "30", "127.0.0.1"]); let OutputPipe { client, .. } = output_pipe().unwrap(); let process = Arc::new(spawn(1, &request, None, client).unwrap()); + assert!(!is_signalled(&process.process_handle().unwrap())); + process.signal(ProcessSignal::Kill).unwrap(); assert!(matches!( wait_exit(Arc::clone(&process)).unwrap(), - Exit::Code(5) + Exit::Signal(name) if name == "SIGKILL" )); process.reap(); } - #[test] - fn a_job_handle_without_assign_access_falls_back_to_a_jobless_spawn() { - let job = Job::new(2).unwrap(); - let mut restricted = null_mut(); - // JOB_OBJECT_QUERY only: joining a job needs JOB_OBJECT_ASSIGN_PROCESS. + /// A duplicate of `job` with only query access: joining it needs + /// JOB_OBJECT_ASSIGN_PROCESS. + fn query_only_job(job: HANDLE) -> OwnedHandle { const JOB_OBJECT_QUERY: u32 = 4; + let mut restricted = null_mut(); // SAFETY: both process handles are pseudo-handles for this process and // the job handle is live; the duplicate is adopted below. assert_ne!( unsafe { DuplicateHandle( GetCurrentProcess(), - job.handle(), + job, GetCurrentProcess(), &mut restricted, JOB_OBJECT_QUERY, @@ -1175,17 +1098,24 @@ mod tests { }, 0 ); - let job = Job(Arc::new(owned_handle(restricted).unwrap())); + owned_handle(restricted).unwrap() + } + + #[test] + fn a_job_handle_without_assign_access_falls_back_to_a_jobless_spawn() { + let job = Job::new(2).unwrap(); + let query = query_only_job(job.handle()); + let restricted = Job(query_only_job(job.handle())); let request = test_request("cmd.exe", &["/d", "/c", "exit /b 5"]); let OutputPipe { client, .. } = output_pipe().unwrap(); - let process = Arc::new(spawn(2, &request, Some(&job), client).unwrap()); + let process = Arc::new(spawn(2, &request, Some(restricted), client).unwrap()); let mut in_job = 0; // SAFETY: the process handle stays open until `reap` and the job is live. assert_ne!( unsafe { IsProcessInJob( process.process_handle().unwrap().as_raw_handle(), - job.handle(), + query.as_raw_handle(), &mut in_job, ) }, diff --git a/packages/process-daemon/src/transport/windows.rs b/packages/process-daemon/src/transport/windows.rs index 7a7149a0d9a8..7d8f7221e610 100644 --- a/packages/process-daemon/src/transport/windows.rs +++ b/packages/process-daemon/src/transport/windows.rs @@ -2,6 +2,7 @@ //! its OVERLAPPED/event and is cancelled and reaped before its buffer is released. //! No FlushFileBuffers: it can wait indefinitely for an uncooperative client. +use std::ffi::OsStr; use std::io::{self, Read, Write}; use std::os::windows::ffi::OsStrExt; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; @@ -545,6 +546,19 @@ pub(crate) fn event() -> io::Result { owned_handle(unsafe { CreateEventW(null(), 1, 0, null()) }) } +/// A NUL-terminated UTF-16 copy of `value`, refusing an embedded NUL. +pub(crate) fn wide(value: &OsStr) -> io::Result> { + let mut wide = value.encode_wide().collect::>(); + if wide.contains(&0) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "path contains a NUL", + )); + } + wide.push(0); + Ok(wide) +} + pub(crate) fn owned_handle(handle: HANDLE) -> io::Result { if handle.is_null() || handle == INVALID_HANDLE_VALUE { return Err(io::Error::last_os_error()); diff --git a/packages/process-daemon/tests/pipe_windows.rs b/packages/process-daemon/tests/pipe_windows.rs index f93c47348f74..8589c5c9d877 100644 --- a/packages/process-daemon/tests/pipe_windows.rs +++ b/packages/process-daemon/tests/pipe_windows.rs @@ -206,6 +206,52 @@ fn batch(name: &str, lines: &[String]) -> TempPath { path } +/// A long-lived PowerShell grandchild in the job that writes its PID, and the +/// batch parent that starts it (staying alive when asked). +struct GrandchildTree { + /// The script must outlive the child that runs it. + _inner: Script, + pid_file: TempPath, + outer: TempPath, +} + +impl GrandchildTree { + fn start(&self, service: &TerminalService) -> (ProcessInfo, TempPath) { + start(service, |file| { + cmd(&self.outer.0.display().to_string(), file) + }) + } +} + +fn grandchild_tree(name: &str, keep_parent_alive: bool) -> GrandchildTree { + let pid_file = TempPath::new(&format!("{name}-pid")); + let inner = Script::powershell( + &format!("{name}-grandchild"), + &format!( + r#" + [System.IO.File]::WriteAllText('{}', "$PID") + Start-Sleep -Seconds 60 + "#, + ps_path(&pid_file.0) + ), + ); + let mut lines = vec![ + "@echo off".to_string(), + format!( + "start /b powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{}\"", + inner.0.0.display() + ), + ]; + if keep_parent_alive { + lines.push("ping -n 60 127.0.0.1".to_string()); + } + GrandchildTree { + _inner: inner, + pid_file, + outer: batch(&format!("{name}-outer"), &lines), + } +} + #[test] fn reports_ordered_output_and_exit_code_without_a_terminal() { let service = TerminalService::default(); @@ -358,7 +404,7 @@ fn rejected_requests_never_touch_the_output_file_or_run() { let link = TempPath::new("link"); let reparse = match std::os::windows::fs::symlink_file(&target.0, &link.0) { Ok(()) => { - cases.push((cmd(&touch, &link.0), "failed to open output file")); + cases.push((cmd(&touch, &link.0), "reparse point")); true } // Symbolic link creation needs Developer Mode or an elevated account. @@ -463,8 +509,7 @@ fn wait_blocks_until_the_exit_and_answers_every_waiter() { #[test] fn terminate_ends_a_pending_wait_with_an_error() { let service = TerminalService::default(); - let script = Script::powershell("sleep", "Start-Sleep -Seconds 30"); - let (info, _file) = start(&service, |file| script.request(file, base_env())); + let (info, _file) = start(&service, |file| cmd("ping -n 30 127.0.0.1 >nul", file)); let wait = service.wait(info.id).unwrap(); service.terminate(info.id).unwrap(); assert_eq!(wait.recv().unwrap_err().to_string(), "terminated"); @@ -473,14 +518,9 @@ fn terminate_ends_a_pending_wait_with_an_error() { #[test] fn signal_stops_a_process_and_keeps_its_record() { let service = TerminalService::default(); - let script = Script::powershell( - "signal", - r#" - [Console]::Out.WriteLine("started") - Start-Sleep -Seconds 30 - "#, - ); - let (info, file) = start(&service, |file| script.request(file, base_env())); + let (info, file) = start(&service, |file| { + cmd("echo started&ping -n 30 127.0.0.1 >nul", file) + }); first_line(&file); service.signal(info.id, ProcessSignal::Term).unwrap(); let exit = service.wait(info.id).unwrap().recv().unwrap(); @@ -503,30 +543,9 @@ fn signal_stops_a_process_and_keeps_its_record() { #[test] fn signal_reaches_a_grandchild_in_the_job() { let service = TerminalService::default(); - let pid_file = TempPath::new("grandchild-pid"); - let inner = Script::powershell( - "grandchild", - &format!( - r#" - [System.IO.File]::WriteAllText('{}', "$PID") - Start-Sleep -Seconds 60 - "#, - ps_path(&pid_file.0) - ), - ); - let outer = batch( - "grandchild-outer", - &[ - "@echo off".to_string(), - format!( - "start /b powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{}\"", - inner.0.0.display() - ), - "ping -n 60 127.0.0.1".to_string(), - ], - ); - let (info, _file) = start(&service, |file| cmd(&outer.0.display().to_string(), file)); - let grandchild = read_pid(&pid_file.0); + let tree = grandchild_tree("grandchild", true); + let (info, _file) = tree.start(&service); + let grandchild = read_pid(&tree.pid_file.0); assert!(alive(grandchild)); service.signal(info.id, ProcessSignal::Term).unwrap(); let exit = service.wait(info.id).unwrap().recv().unwrap(); @@ -535,48 +554,12 @@ fn signal_reaches_a_grandchild_in_the_job() { service.terminate(info.id).unwrap(); } -#[test] -fn a_grandchild_holding_the_pipe_delays_the_exit_by_at_most_the_drain() { - let service = TerminalService::default(); - let (info, file) = start(&service, |file| cmd("start /b ping -n 60 127.0.0.1", file)); - let finished = run(&service, info.id, &file); - assert_eq!(finished.exit.exit_code, Some(0)); - assert!( - finished.elapsed < Duration::from_secs(10), - "{:?}", - finished.elapsed - ); - // Terminate kills the rest of the job. - service.terminate(info.id).unwrap(); -} - #[test] fn terminate_does_not_hang_on_a_grandchild() { let service = TerminalService::default(); - let pid_file = TempPath::new("terminate-pid"); - let inner = Script::powershell( - "terminate-grandchild", - &format!( - r#" - [System.IO.File]::WriteAllText('{}', "$PID") - Start-Sleep -Seconds 60 - "#, - ps_path(&pid_file.0) - ), - ); - let outer = batch( - "terminate-outer", - &[ - "@echo off".to_string(), - format!( - "start /b powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{}\"", - inner.0.0.display() - ), - "ping -n 60 127.0.0.1".to_string(), - ], - ); - let (info, _file) = start(&service, |file| cmd(&outer.0.display().to_string(), file)); - let grandchild = read_pid(&pid_file.0); + let tree = grandchild_tree("terminate", true); + let (info, _file) = tree.start(&service); + let grandchild = read_pid(&tree.pid_file.0); assert!(alive(grandchild)); let started = Instant::now(); service.terminate(info.id).unwrap(); @@ -639,30 +622,17 @@ fn a_noisy_grandchild_still_exits_after_the_drain() { #[test] fn signal_after_a_normal_exit_kills_a_leftover_grandchild() { let service = TerminalService::default(); - let pid_file = TempPath::new("leftover-pid"); - let inner = Script::powershell( - "leftover-grandchild", - &format!( - r#" - [System.IO.File]::WriteAllText('{}', "$PID") - Start-Sleep -Seconds 60 - "#, - ps_path(&pid_file.0) - ), - ); - let outer = batch( - "leftover-outer", - &[ - "@echo off".to_string(), - format!( - "start /b powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{}\"", - inner.0.0.display() - ), - ], - ); - let (info, _file) = start(&service, |file| cmd(&outer.0.display().to_string(), file)); - let grandchild = read_pid(&pid_file.0); + let tree = grandchild_tree("leftover", false); + let (info, _file) = tree.start(&service); + let grandchild = read_pid(&tree.pid_file.0); + // A descendant holds the pipe, so the exit waits for at most the drain. + let started = Instant::now(); let exit = service.wait(info.id).unwrap().recv().unwrap(); + assert!( + started.elapsed() < Duration::from_secs(10), + "{:?}", + started.elapsed() + ); assert_eq!(exit.exit_code, Some(0)); assert_eq!(exit.signal, None); // The process keeps its record after the exit; the grandchild still runs. @@ -763,14 +733,9 @@ if ($window -eq [IntPtr]::Zero) { #[test] fn the_output_file_can_be_read_and_deleted_while_open() { let service = TerminalService::default(); - let script = Script::powershell( - "shared", - r#" - [Console]::Out.WriteLine("started") - Start-Sleep -Seconds 30 - "#, - ); - let (info, file) = start(&service, |file| script.request(file, base_env())); + let (info, file) = start(&service, |file| { + cmd("echo started&ping -n 30 127.0.0.1 >nul", file) + }); first_line(&file); assert!(fs::read_to_string(&file.0).unwrap().starts_with("started")); fs::remove_file(&file.0).unwrap(); diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 94162dec4a20..f77de62f84d8 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -10179,7 +10179,8 @@ "installation.update-available", "vcs.branch.updated", "mcp.status.changed", - "mcp.resources.changed" + "mcp.resources.changed", + "experimental.mcp.event" ] }, { @@ -10289,7 +10290,8 @@ "installation.update-available", "vcs.branch.updated", "mcp.status.changed", - "mcp.resources.changed" + "mcp.resources.changed", + "experimental.mcp.event" ] }, { @@ -25652,6 +25654,9 @@ { "$ref": "#/components/schemas/mcp.resources.changed" }, + { + "$ref": "#/components/schemas/experimental.mcp.event" + }, { "$ref": "#/components/schemas/V2Event.rpc" }, @@ -26364,6 +26369,72 @@ "required": ["id", "created", "type", "data"], "additionalProperties": false }, + "experimental.mcp.event": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Event.ID" + }, + "created": { + "type": "number" + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": ["experimental.mcp.event"] + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "server": { + "type": "string" + }, + "name": { + "type": "string" + }, + "eventId": { + "type": "string" + }, + "timestamp": { + "type": "string" + }, + "data": {}, + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "truncated": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + }, + "required": ["id", "server", "name", "eventId", "timestamp", "data", "cursor"], + "additionalProperties": false + } + }, + "required": ["id", "created", "type", "data"], + "additionalProperties": false + }, "filesystem.changed": { "type": "object", "properties": { diff --git a/packages/schema/src/event-manifest.ts b/packages/schema/src/event-manifest.ts index f0c5bd30e01a..425fb26bb9e4 100644 --- a/packages/schema/src/event-manifest.ts +++ b/packages/schema/src/event-manifest.ts @@ -79,6 +79,7 @@ export const ServerDefinitions = Event.inventory( ...VcsEvent.Definitions, McpEvent.StatusChanged, McpEvent.ResourcesChanged, + McpEvent.ExperimentalEvent, ) export const Server = Event.latest(ServerDefinitions) export type ServerEvent = Schema.Schema.Type<(typeof ServerDefinitions)[number]> diff --git a/packages/schema/src/mcp-event.ts b/packages/schema/src/mcp-event.ts index 5e53ce0c78bf..dc11ee20acd5 100644 --- a/packages/schema/src/mcp-event.ts +++ b/packages/schema/src/mcp-event.ts @@ -26,4 +26,38 @@ export const StatusChanged = Event.ephemeral({ }, }) -export const Definitions = Event.inventory(ToolsChanged, ResourcesChanged, StatusChanged) +// Experimental: MCP Events is a draft extension; may change without compatibility guarantees. + +/** One event from an MCP Events subscription. Delivery is at least once: dedupe on `id` and `eventId`. */ +export const ExperimentalEvent = Event.ephemeral({ + type: "experimental.mcp.event", + schema: { + /** The subscription that received it. */ + id: Schema.String, + server: Schema.String, + name: Schema.String, + eventId: Schema.String, + timestamp: Schema.String, + data: Schema.Json, + /** Where the subscription resumes from after this event; null when the event type has no replay. */ + cursor: Schema.NullOr(Schema.String), + /** The server skipped events before this one, which it could not replay. */ + truncated: Schema.optional(Schema.Boolean), + }, +}) + +/** A subscription's status changed; read it with the MCP service's `subscriptions`. */ +export const ExperimentalSubscriptionChanged = Event.ephemeral({ + type: "experimental.mcp.subscription.changed", + schema: { + id: Schema.String, + }, +}) + +export const Definitions = Event.inventory( + ToolsChanged, + ResourcesChanged, + StatusChanged, + ExperimentalEvent, + ExperimentalSubscriptionChanged, +) diff --git a/packages/schema/src/mcp.ts b/packages/schema/src/mcp.ts index 003bf930a83a..b653421800ca 100644 --- a/packages/schema/src/mcp.ts +++ b/packages/schema/src/mcp.ts @@ -95,6 +95,23 @@ export const Status = Schema.Union([Connected, Pending, Disabled, Failed, NeedsA Schema.toTaggedUnion("status"), ) +/** + * An MCP Events subscription: `pending` until its server confirms the stream, `active` while it does, and `ended` when + * the server terminated or rejected it, or no longer offers events. Pending covers a server that is not connected. + * Experimental: MCP Events is a draft extension; may change without compatibility guarantees. + */ +export const SubscriptionStatus = Schema.Union([ + Schema.Struct({ status: Schema.Literal("pending") }), + Schema.Struct({ status: Schema.Literal("active") }), + Schema.Struct({ status: Schema.Literal("ended"), reason: Schema.Literal("unavailable") }), + Schema.Struct({ + status: Schema.Literal("ended"), + reason: Schema.Literals(["terminated", "rejected"]), + error: Schema.Struct({ code: Schema.Number, message: Schema.String }), + }), +]).annotate({ identifier: "Mcp.SubscriptionStatus" }) +export type SubscriptionStatus = typeof SubscriptionStatus.Type + export interface Server extends Schema.Schema.Type {} export const Server = Schema.Struct({ name: Schema.String, diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 81053e74b83c..c766ea8b3d4f 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -37,6 +37,8 @@ describe("public event manifest", () => { expect(EventManifest.Latest.get("agent.updated")).toBe(Agent.Event.Updated) expect(EventManifest.Server.get("mcp.status.changed")).toBe(McpEvent.StatusChanged) expect(EventManifest.Server.get("mcp.resources.changed")).toBe(McpEvent.ResourcesChanged) + expect(EventManifest.Server.get("experimental.mcp.event")).toBe(McpEvent.ExperimentalEvent) + expect(EventManifest.Server.has("experimental.mcp.subscription.changed")).toBe(false) expect(EventManifest.Server.get("session.created")).toBe(SessionEvent.Created) expect(EventManifest.Server.get("session.deleted")).toBe(SessionEvent.Deleted) expect(EventManifest.Server.get("project.updated")).toBe(Project.Event.Updated) @@ -68,7 +70,13 @@ describe("public event manifest", () => { ]) expect(Form.Event.Definitions).toEqual([Form.Event.Created, Form.Event.Replied, Form.Event.Cancelled]) expect(Reference.Event.Definitions).toEqual([Reference.Event.Updated]) - expect(McpEvent.Definitions).toEqual([McpEvent.ToolsChanged, McpEvent.ResourcesChanged, McpEvent.StatusChanged]) + expect(McpEvent.Definitions).toEqual([ + McpEvent.ToolsChanged, + McpEvent.ResourcesChanged, + McpEvent.StatusChanged, + McpEvent.ExperimentalEvent, + McpEvent.ExperimentalSubscriptionChanged, + ]) expect(EventManifest.Latest.has("mcp.browser.open.failed")).toBe(false) expect(EventManifest.Durable.get("session.step.ended.1")).toBe(SessionEvent.Step.Ended) expect(EventManifest.Durable.has("session.step.ended.2")).toBe(false) diff --git a/packages/server/package.json b/packages/server/package.json index 88929f3ac5b4..b6b2b0e02e13 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -37,7 +37,7 @@ "effect": "catalog:" }, "devDependencies": { - "@opencode/pty": "0.5.0", + "@opencode/pty": "0.5.2", "@opencode/client": "workspace:*", "@opencode/plugin": "workspace:*", "@tsconfig/bun": "catalog:", diff --git a/packages/server/test/session-diff.test.ts b/packages/server/test/session-diff.test.ts index 07c24b69e7df..bafcfa07b263 100644 --- a/packages/server/test/session-diff.test.ts +++ b/packages/server/test/session-diff.test.ts @@ -49,7 +49,6 @@ it.live("serves turn diffs by user message with range validation", () => }), interrupt: () => Effect.succeed(false), awaitIdle: () => Effect.void, - periodStartSeq: () => Effect.succeed(undefined), }) }), ) diff --git a/packages/session-ui/src/storybook/current-session-fixtures.ts b/packages/session-ui/src/storybook/current-session-fixtures.ts index e7aa60975f38..30d06b26f391 100644 --- a/packages/session-ui/src/storybook/current-session-fixtures.ts +++ b/packages/session-ui/src/storybook/current-session-fixtures.ts @@ -1085,12 +1085,32 @@ export const compactionCancelledDocument = document([ }, ] satisfies SessionMessageInfo[]) +export type SubagentReport = { + childID: string + agent: string + state: "completed" | "error" | "cancelled" + description: string + body: string +} + +export function subagentReport(id: string, created: number, report: SubagentReport): SessionMessageInfo { + return { + id, + type: "synthetic", + description: report.description, + text: `\n${report.body}\n`, + metadata: { source: "subagent", childID: report.childID, agent: report.agent, state: report.state }, + time: { created }, + } +} + export const subagentDocument = document( [ user("msg_user_subagent", "Delegate the fixture review and report the result.", 70_000), assistant({ id: "msg_assistant_subagent", offset: 71_000, + completed: 74_000, agent: "build", content: [ completedTool({ @@ -1102,10 +1122,10 @@ export const subagentDocument = document( description: "Review current Session fixtures", prompt: "Check the current Session fixtures for protocol accuracy and report findings.", }, - output: "The fixtures use fixed current protocol messages and nested tool states.", - metadata: { sessionID: "session_child_review", status: "completed" }, + output: "The subagent is working in the background.", + metadata: { sessionID: "session_child_review", status: "running" }, }), - runningTool({ + completedTool({ id: "tool_subagent_tests", name: "subagent", offset: 73_000, @@ -1114,10 +1134,18 @@ export const subagentDocument = document( description: "Check the Storybook scenarios", prompt: "Run the focused Storybook scenario checks and report any failures.", }, - metadata: { sessionId: "session_child_tests" }, + output: "The subagent is working in the background.", + metadata: { sessionID: "session_child_tests", status: "running" }, }), ], }), + subagentReport("msg_review_report", STORY_TIME + 75_000, { + childID: "session_child_review", + agent: "review", + state: "completed", + description: "Review current Session fixtures", + body: "The fixtures use fixed current protocol messages and nested tool states.", + }), ] satisfies SessionMessageInfo[], { type: "busy" }, ) diff --git a/packages/session-ui/src/storybook/index.ts b/packages/session-ui/src/storybook/index.ts index 2ce70c9ec9e2..d360ab125f0d 100644 --- a/packages/session-ui/src/storybook/index.ts +++ b/packages/session-ui/src/storybook/index.ts @@ -31,6 +31,7 @@ export { standaloneShellRunningDocument, streamingDocument, subagentDocument, + subagentReport, terminalFailedDocument, terminalPassedDocument, terminalRunningDocument, diff --git a/packages/session-ui/src/timeline-next/events.ts b/packages/session-ui/src/timeline-next/events.ts index 52890fc1df1c..d4d159f23bbe 100644 --- a/packages/session-ui/src/timeline-next/events.ts +++ b/packages/session-ui/src/timeline-next/events.ts @@ -45,8 +45,8 @@ export const launchKeys = { const decodeText = Schema.decodeUnknownOption(Schema.NonEmptyString) /** - * What a call says happened. A call still being written has nothing to count yet. A subagent that returns while it - * keeps running was started in the background; one that returned with its work done ran in the foreground. + * What a call says happened. A call still being written has nothing to count yet. Older sessions marked a + * foreground subagent's result as completed; current subagent calls only launch the work. */ export function toolEvent(tool: SessionMessageAssistantTool): TimelineEvent | undefined { const kind = toolRule(tool).name === "shell" ? "shell" : "subagent" @@ -66,10 +66,10 @@ export function toolEvent(tool: SessionMessageAssistantTool): TimelineEvent | un if (state.status === "running") return { ...item, verb: "started", failed: false } - const background = metadata.status === "running" || input.background === true + const background = + kind === "subagent" ? metadata.status !== "completed" : metadata.status === "running" || input.background === true if (state.status === "error") { - // An interrupted turn stops the work it was waiting on. if (state.error.type === "aborted") return { ...item, verb: "stopped", failed: false } return { ...item, verb: background ? "started" : "ran", failed: true } diff --git a/packages/session-ui/src/timeline-next/rules.test.ts b/packages/session-ui/src/timeline-next/rules.test.ts index 124037a72fd4..a69a11a44541 100644 --- a/packages/session-ui/src/timeline-next/rules.test.ts +++ b/packages/session-ui/src/timeline-next/rules.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test" import type { SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise" import { timelinePresets, type TimelineDetail } from "../timeline/detail" +import { toolEvent } from "./events" import { contentGroup, contentOpens, @@ -12,16 +13,21 @@ import { toolStopped, userShellOpens, } from "./rules" +import { timelineStatus } from "./status" const preset = (id: string) => timelinePresets.find((item) => item.id === id)!.value const custom = (overrides: Partial): TimelineDetail => ({ ...preset("compact"), ...overrides }) -const tool = (name: string, input: { [key: string]: string | boolean } = {}): SessionMessageAssistantTool => ({ +const tool = ( + name: string, + input: { [key: string]: string | boolean } = {}, + metadata: { [key: string]: string } = {}, +): SessionMessageAssistantTool => ({ id: name, type: "tool", name, - state: { status: "completed", input, content: [{ type: "text", text: "" }], metadata: {} }, + state: { status: "completed", input, content: [{ type: "text", text: "" }], metadata }, time: { created: 0 }, }) @@ -47,6 +53,21 @@ const report = (source: "shell" | "subagent", state = "completed") => }) satisfies SessionMessageInfo describe("starting work that runs on follows its own setting", () => { + test("a subagent launch leaves the parent working unless approval is pending", () => { + const content = [{ ...tool("subagent"), state: { status: "running" as const, input: {}, metadata: {} } }] + + expect(timelineStatus({ content })).toBe("working") + expect(timelineStatus({ content, blocked: "approval" })).toBe("waitingApproval") + }) + + test("a failed subagent launch says Started; a stored foreground result says Ran", () => { + expect( + toolEvent(errored("subagent", { type: "ToolExecutionError", message: "Failed to prompt subagent" })), + ).toMatchObject({ verb: "started", failed: true }) + expect(toolEvent(tool("subagent", { background: true }))).toMatchObject({ verb: "started" }) + expect(toolEvent(tool("subagent", {}, { status: "completed" }))).toMatchObject({ verb: "ran", failed: false }) + }) + test("a background shell joins the activity group where shells are grouped, and stands alone where separate", () => { expect(contentGroup(preset("compact"), backgroundShell, new Set())).toBe("context") expect(contentGroup(preset("everything"), backgroundShell, new Set())).toBe("events") diff --git a/packages/session-ui/src/timeline-next/status.ts b/packages/session-ui/src/timeline-next/status.ts index a6d26e26c391..ad15e44f8b41 100644 --- a/packages/session-ui/src/timeline-next/status.ts +++ b/packages/session-ui/src/timeline-next/status.ts @@ -4,17 +4,10 @@ import { liveThinkingShows, toolRule } from "./rules" type Content = SessionMessageAssistant["content"][number] -export type TimelineStatus = - | "waitingApproval" - | "waitingAnswer" - | "waitingShell" - | "waitingAgent" - | "waitingAgents" - | "working" +export type TimelineStatus = "waitingApproval" | "waitingAnswer" | "waitingShell" | "working" /** - * What the status line below a working turn says. It names what the turn waits on, the user or a command or subagent - * it started, and otherwise says Working: what the agent does shows in the timeline above it. + * The status line says Working unless the turn is waiting on the user or a shell command. */ export function timelineStatus(input: { /** A permission or a question waits on the user. */ @@ -28,21 +21,8 @@ export function timelineStatus(input: { const last = input.content.at(-1) if (last?.type !== "tool" || (last.state.status !== "running" && last.state.status !== "streaming")) return "working" - const name = toolRule(last).name - if (name === "shell") return "waitingShell" - - if (name !== "subagent") return "working" - - // Subagents started together run side by side, so the line counts every one still running. - const running = input.content.filter( - (item) => - item.type === "tool" && - toolRule(item).name === "subagent" && - (item.state.status === "running" || item.state.status === "streaming"), - ) - - return running.length > 1 ? "waitingAgents" : "waitingAgent" + return toolRule(last).name === "shell" ? "waitingShell" : "working" } /** Whether the model is writing a thought that shows, which then stands in for the status line's Working. */ diff --git a/packages/session-ui/src/timeline-next/stories/compare.stories.tsx b/packages/session-ui/src/timeline-next/stories/compare.stories.tsx index ee5b6b7ecf7e..87a2e8863d0c 100644 --- a/packages/session-ui/src/timeline-next/stories/compare.stories.tsx +++ b/packages/session-ui/src/timeline-next/stories/compare.stories.tsx @@ -56,8 +56,6 @@ const statusLabels = { waitingApproval: "Waiting for approval", waitingAnswer: "Waiting for your answer", waitingShell: "Waiting for shell", - waitingAgent: "Waiting for subagent", - waitingAgents: "Waiting for subagents", working: "Working", } as const diff --git a/packages/session-ui/src/timeline-next/stories/playground.stories.tsx b/packages/session-ui/src/timeline-next/stories/playground.stories.tsx index e4e48ebfcc5a..ea60e8ee290a 100644 --- a/packages/session-ui/src/timeline-next/stories/playground.stories.tsx +++ b/packages/session-ui/src/timeline-next/stories/playground.stories.tsx @@ -32,8 +32,6 @@ const statusLabels = { waitingApproval: "Waiting for approval", waitingAnswer: "Waiting for your answer", waitingShell: "Waiting for shell", - waitingAgent: "Waiting for subagent", - waitingAgents: "Waiting for subagents", working: "Working", } as const diff --git a/packages/session-ui/src/timeline-next/stories/session-replay.ts b/packages/session-ui/src/timeline-next/stories/session-replay.ts index 7632173e0a5d..002924d794b3 100644 --- a/packages/session-ui/src/timeline-next/stories/session-replay.ts +++ b/packages/session-ui/src/timeline-next/stories/session-replay.ts @@ -6,7 +6,12 @@ import type { } from "@opencode/client/promise" import { createTwoFilesPatch, diffLines } from "diff" import type { SessionDocument } from "../../document" -import { CURRENT_SESSION_ID, STORY_MODEL } from "../../storybook/current-session-fixtures" +import { + CURRENT_SESSION_ID, + STORY_MODEL, + subagentReport, + type SubagentReport, +} from "../../storybook/current-session-fixtures" /** * A scripted session is a list of beats. Each beat takes one or more steps of the playhead: a tool call starts and then @@ -18,15 +23,13 @@ export type Beat = | { kind: "shell"; command: string; output: string; exit: number } | { kind: "goal"; objective: string } /** A background subagent or shell reporting back, as the server delivers it. */ + | ({ kind: "report"; source: "subagent" } & SubagentReport) | { kind: "report" - source: "subagent" | "shell" + source: "shell" state: "completed" | "error" | "cancelled" description: string - agent?: string - /** The subagent's session or the shell that reports, which the timeline links to. */ - childID?: string - shellID?: string + shellID: string } | { kind: "model"; id: string } | { kind: "step" } @@ -463,8 +466,17 @@ const featureWork: Beat[] = [ kind: "tool", name: "subagent", input: { agent: "review", description: "Review the dark mode change", prompt: "Review the diff." }, - output: "Looks good. One nit: name the store setter `setScheme`.", - metadata: { sessionID: "session_child_review", status: "completed" }, + output: "The subagent is working in the background.", + metadata: { sessionID: "session_child_review", status: "running" }, + }, + { + kind: "report", + source: "subagent", + state: "completed", + description: "Review the dark mode change", + agent: "review", + childID: "session_child_review", + body: "Looks good. One nit: name the store setter `setScheme`.", }, { kind: "tool", name: "shell", input: { command: "bun run build", description: "Build the app" }, hold: true }, { kind: "interrupt" }, @@ -614,10 +626,18 @@ const everyTool: Beat[] = [ kind: "tool", name: "subagent", input: { agent: "review", description: "Review the scheme fix", prompt: "Review the diff." }, - error: "The subagent stopped: the model is overloaded", - metadata: { sessionID: "session_child_review_failed" }, + output: "The subagent is working in the background.", + metadata: { sessionID: "session_child_review_failed", status: "running" }, + }, + { + kind: "report", + source: "subagent", + state: "error", + description: "Review the scheme fix", + agent: "review", + childID: "session_child_review_failed", + body: "The model is overloaded.", }, - { kind: "step" }, { kind: "say", text: "Filed **DES-418** and fixed the flash: the scheme now applies before the first paint. Tests pass; lint flags one stray `console` call.", @@ -625,20 +645,20 @@ const everyTool: Beat[] = [ { kind: "idle" }, ] -// Subagents and shells the agent starts in the background, how they report back, and subagents it waits on. +// Subagents and shells the agent starts in the background, and how they report back. const backgroundWork: Beat[] = [ { kind: "user", text: "Review the theme code and check the docs while you keep the dev server running." }, { kind: "tool", name: "subagent", - input: { agent: "review", description: "Review the theme store", prompt: "Review it.", background: true }, + input: { agent: "review", description: "Review the theme store", prompt: "Review it." }, output: "The subagent is working in the background.", metadata: { sessionID: "session_child_store", status: "running" }, }, { kind: "tool", name: "subagent", - input: { agent: "explore", description: "Check the theme docs", prompt: "Check them.", background: true }, + input: { agent: "explore", description: "Check the theme docs", prompt: "Check them." }, output: "The subagent is working in the background.", metadata: { sessionID: "session_child_docs", status: "running" }, }, @@ -663,6 +683,7 @@ const backgroundWork: Beat[] = [ description: "Review the theme store", agent: "review", childID: "session_child_store", + body: "Nothing to change in the theme store.", }, { kind: "report", @@ -671,26 +692,45 @@ const backgroundWork: Beat[] = [ description: "Check the theme docs", agent: "explore", childID: "session_child_docs", + body: "The docs check failed.", }, { kind: "say", - text: "The store review found nothing to change. The docs check failed, so I'll run both checks again and wait for them.", + text: "The store review found nothing to change. I'll retry the docs check and ask for a review of the toggle.", }, { kind: "tool", name: "subagent", input: { agent: "explore", description: "Check the theme docs", prompt: "Check them." }, - output: "The docs describe the scheme setting correctly.", - metadata: { sessionID: "session_child_docs_again", status: "completed" }, + output: "The subagent is working in the background.", + metadata: { sessionID: "session_child_docs_again", status: "running" }, }, { kind: "tool", name: "subagent", input: { agent: "review", description: "Review the toggle", prompt: "Review it." }, - output: "The toggle reads the scheme in an effect, which is right.", - metadata: { sessionID: "session_child_toggle", status: "completed" }, + output: "The subagent is working in the background.", + metadata: { sessionID: "session_child_toggle", status: "running" }, + }, + { kind: "idle" }, + { + kind: "report", + source: "subagent", + state: "completed", + description: "Check the theme docs", + agent: "explore", + childID: "session_child_docs_again", + body: "The docs describe the scheme setting correctly.", + }, + { + kind: "report", + source: "subagent", + state: "completed", + description: "Review the toggle", + agent: "review", + childID: "session_child_toggle", + body: "The toggle reads the scheme in an effect, which is right.", }, - { kind: "step" }, { kind: "say", text: "Both checks pass: the docs are accurate and the toggle reads the scheme correctly." }, { kind: "idle" }, { kind: "report", source: "shell", state: "cancelled", description: "bun run dev", shellID: "shell_dev" }, @@ -833,25 +873,20 @@ export function replayScript(script: Beat[], limit: number, start: number) { state.busy = true } - if (beat.kind === "report") { + if (beat.kind === "report" && beat.source === "subagent") { + closeStep() + messages.push(subagentReport(id("msg_report"), at(), beat)) + state.busy = true + } + + if (beat.kind === "report" && beat.source === "shell") { closeStep() messages.push({ id: id("msg_report"), type: "synthetic", text: `${beat.source} ${beat.state}: ${beat.description}`, description: beat.description, - metadata: { - source: beat.source, - state: beat.state, - // Only the fields the report carries, as core writes them. - ...Object.fromEntries( - [ - ["agent", beat.agent], - ["childID", beat.childID], - ["shellID", beat.shellID], - ].flatMap(([key, value]) => (value ? [[key, value]] : [])), - ), - }, + metadata: { source: beat.source, state: beat.state, shellID: beat.shellID }, time: { created: at() }, }) } diff --git a/packages/session-ui/src/timeline-next/timeline-next.css b/packages/session-ui/src/timeline-next/timeline-next.css index 9dcd78dd6c04..83dba6cc5847 100644 --- a/packages/session-ui/src/timeline-next/timeline-next.css +++ b/packages/session-ui/src/timeline-next/timeline-next.css @@ -416,8 +416,9 @@ position: absolute; inset-inline: 0; top: 100%; - height: 20px; - margin-top: 8px; + height: 28px; + margin-top: 0; + padding-top: 8px; } } @@ -488,7 +489,14 @@ margin-top: 0; } - /* The agent's last words in a turn keep their actions in the large gap below them, as the user's message does. */ + /* A reply's footer sits below the line box, as in the current timeline, so its last line keeps the bottom half-leading. */ + [data-component="text-part"]:has(> [data-slot="text-part-footer"], > [data-slot="text-part-copy-wrapper"]) + [data-component="markdown"] { + text-box: trim-start text; + } + + /* The agent's last words in a turn keep their actions in the large gap below them, as the user's message does. The + gap above the actions is their own padding, so the pointer stays over the message while it crosses to them. */ [data-component="text-part"]:has(> [data-slot="text-part-copy-wrapper"]) { position: relative; @@ -496,6 +504,9 @@ position: absolute; inset-inline: 0; top: 100%; + height: 28px; + margin-top: 0; + padding-top: 8px; } } diff --git a/packages/session-ui/src/timeline/research-and-agents.stories.tsx b/packages/session-ui/src/timeline/research-and-agents.stories.tsx index 29d51b374e09..86e85d9fdd32 100644 --- a/packages/session-ui/src/timeline/research-and-agents.stories.tsx +++ b/packages/session-ui/src/timeline/research-and-agents.stories.tsx @@ -1,4 +1,4 @@ -import type { JsonValue, SessionMessageAssistant, SessionMessageAssistantTool } from "@opencode/client/promise" +import type { SessionMessageAssistant, SessionMessageAssistantTool } from "@opencode/client/promise" import { createMemo } from "solid-js" import { createStore } from "solid-js/store" import type { SessionDocument } from "../document" @@ -134,11 +134,9 @@ function CodebaseExplorationStory() { state: completed ? { status: "completed", input, content: [{ type: "text", text: "Complete" }], metadata: {} } : { status: "running", input, metadata: {} }, - time: { - created: STORY_TIME, - ran: STORY_TIME + 100, - ...(completed ? { completed: STORY_TIME + 200 } : {}), - }, + time: completed + ? { created: STORY_TIME, ran: STORY_TIME + 100, completed: STORY_TIME + 200 } + : { created: STORY_TIME, ran: STORY_TIME + 100 }, } satisfies SessionMessageAssistantTool } @@ -154,7 +152,9 @@ function CodebaseExplorationStory() { agent: "build", model: STORY_MODEL, content: [tool("read", state.read), tool("glob", state.glob)], - time: { created: STORY_TIME, ...(state.read && state.glob ? { completed: STORY_TIME + 300 } : {}) }, + time: state.read && state.glob + ? { created: STORY_TIME, completed: STORY_TIME + 300 } + : { created: STORY_TIME }, } satisfies SessionMessageAssistant, ], status: { type: state.read && state.glob ? "idle" : "busy" }, @@ -327,7 +327,7 @@ const RecoverFromToolFailures = { render: () => { const names = ["shell", "edit", "write", "patch", "webfetch", "websearch", "subagent", "skill", "mcp_probe"] - const input = (name: string): Record => { + const input = (name: string) => { if (name === "shell") return { command: "exit 1" } if (name === "edit" || name === "write") return { path: "src/error.ts", content: "" } @@ -423,7 +423,7 @@ const StartingBackgroundWork = { "tool_notice_background", "subagent", "running", - { description: "Inspect code", background: true }, + { description: "Inspect code" }, { metadata: { status: "running" }, }, @@ -452,5 +452,8 @@ const researchScenarios = { export const AgentResearch = { args: { scenario: "workflow" }, argTypes: { scenario: { control: "select", options: Object.keys(researchScenarios) } }, - render: (args: { scenario: string }) => researchScenarios[args.scenario as keyof typeof researchScenarios].render(), + render: (args: { scenario: string }) => + Object.entries(researchScenarios) + .find(([name]) => name === args.scenario)?.[1] + .render() ?? researchScenarios.workflow.render(), } diff --git a/packages/session-ui/src/tools/run-machine.test.ts b/packages/session-ui/src/tools/run-machine.test.ts index 85eacaa9f750..d2d7a146e2cf 100644 --- a/packages/session-ui/src/tools/run-machine.test.ts +++ b/packages/session-ui/src/tools/run-machine.test.ts @@ -137,37 +137,34 @@ describe("transitionSubagentRun", () => { return transitionSubagentRun(state, { type: "sync", props: subagentRunProps(tool, childBusy) }) } - test("a subagent handed to the background runs until its child session goes idle", () => { + test("a subagent runs until its child session goes idle", () => { const delegating = step(INITIAL_SUBAGENT_RUN_STATE, { status: "streaming", metadata: {} }) expect(delegating).toBe(INITIAL_SUBAGENT_RUN_STATE) expect(viewSubagentRun(delegating)).toMatchObject({ delegating: true, running: true }) - const foreground = step(delegating, { status: "running", metadata: {} }, true) + const running = step(delegating, { status: "running", metadata: {} }, true) - expect(viewSubagentRun(foreground)).toEqual({ + expect(viewSubagentRun(running)).toEqual({ delegating: false, running: true, basicStatus: "running", - background: false, }) - // The call completes with `status: "running"` once the subagent moved to the background. + // The call completes with `status: "running"` while the child keeps working in the background. const handoff = { status: "completed", metadata: { ...child, status: "running" } } - const background = step(foreground, handoff, true) + const background = step(running, handoff, true) expect(viewSubagentRun(background)).toEqual({ delegating: false, running: true, basicStatus: "running", - background: true, }) expect(step(background, handoff, true)).toBe(background) expect(viewSubagentRun(step(background, handoff))).toEqual({ delegating: false, running: false, basicStatus: "completed", - background: true, }) }) diff --git a/packages/session-ui/src/tools/run-machine.ts b/packages/session-ui/src/tools/run-machine.ts index 03f8b68ba84e..3232b4cb7c1f 100644 --- a/packages/session-ui/src/tools/run-machine.ts +++ b/packages/session-ui/src/tools/run-machine.ts @@ -138,22 +138,18 @@ export function stoppedShell(tool: { /** A subagent call as the renderer decoded it. */ type SubagentTool = { readonly status: string | undefined - readonly metadata: { readonly status?: string; readonly background?: boolean } + readonly metadata: { readonly status?: string } } export type SubagentRunProps = { readonly status: string | undefined - readonly background: boolean - /** The child session is busy, which outlives the call when the subagent runs in the background. */ + /** The child session is busy, which outlives the call because every subagent runs in the background. */ readonly childBusy: boolean } export function subagentRunProps(tool: SubagentTool, childBusy: boolean): SubagentRunProps { return { status: tool.status, - // A completed call whose result reports `running` handed the subagent off to the background. - background: - tool.metadata.background === true || (tool.status === "completed" && tool.metadata.status === "running"), childBusy, } } @@ -161,7 +157,7 @@ export function subagentRunProps(tool: SubagentTool, childBusy: boolean): Subage /** The model is writing the delegation, or the subagent runs, finished or failed. */ export type SubagentRunState = | { readonly status: "delegating" } - | { readonly status: "running" | "completed" | "error"; readonly background: boolean } + | { readonly status: "running" | "completed" | "error" } export type SubagentRunEvent = { readonly type: "sync"; readonly props: SubagentRunProps } @@ -175,9 +171,9 @@ export function transitionSubagentRun(state: SubagentRunState, event: SubagentRu const status = props.status === "running" || props.childBusy ? "running" : props.status === "error" ? "error" : "completed" - if (state.status === status && state.background === props.background) return state + if (state.status === status) return state - return { status, background: props.background } + return { status } } export function viewSubagentRun(state: SubagentRunState) { @@ -185,6 +181,5 @@ export function viewSubagentRun(state: SubagentRunState) { delegating: state.status === "delegating", running: state.status === "delegating" || state.status === "running", basicStatus: state.status === "delegating" ? "streaming" : state.status, - background: state.status !== "delegating" && state.background, } } diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index b700af944890..66d56646609f 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -163,7 +163,6 @@ export const toolMetadata = Schema.decodeUnknownSync( command: optional(Schema.String), shellID: optional(Schema.String), status: optional(Schema.String), - background: optional(Schema.Boolean), interrupted: optional(Schema.Boolean), notice: optional(Schema.String), count: optional(Schema.Finite), @@ -1771,15 +1770,7 @@ ToolRegistry.register({ const view = createMemo(() => viewSubagentRun(run())) - const subtitle = createMemo(() => { - const value = input().description || childSessionId() - - if (!value) return value - - if (view().background) return `${value} (background)` - - return value - }) + const subtitle = createMemo(() => input().description || childSessionId()) const href = createMemo(() => sessionLink(childSessionId(), data.sessionHref)) const clickable = createMemo(() => !!(childSessionId() && (data.navigateToSession || href()))) diff --git a/packages/tui/src/component/dialog-session-list.tsx b/packages/tui/src/component/dialog-session-list.tsx index f251a2b65350..db0c3d07f990 100644 --- a/packages/tui/src/component/dialog-session-list.tsx +++ b/packages/tui/src/component/dialog-session-list.tsx @@ -227,6 +227,7 @@ export function DialogSessionList() { options={options()} skipFilter={true} current={currentSessionID()} + focusCurrent={false} onFilter={(query) => { setFilter(query) setSearch(query) diff --git a/packages/tui/src/mini/demo.ts b/packages/tui/src/mini/demo.ts index 1e26ea0da8e1..64a5767f27ab 100644 --- a/packages/tui/src/mini/demo.ts +++ b/packages/tui/src/mini/demo.ts @@ -504,19 +504,24 @@ function emitPatch(state: State): void { }) } +function subagentLaunch(sessionID: string) { + return { + output: [ + `The subagent is working in the background (sessionID: ${sessionID}). You will receive a message when it goes idle, and again after each later round of work.`, + "DO NOT sleep, poll for progress, ask the subagent for status, or duplicate this subagent's work; avoid working with the same files or topics it is using.", + "Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.", + "To send it follow-ups or change its instructions while it runs, call subagent again with this sessionID.", + ].join("\n"), + metadata: { sessionID, status: "running" }, + } +} + function emitTask(state: State): void { const ref = make(state, "subagent", { description: "Scan run/* for reducer touchpoints", agent: "explore", }) - doneTool(state, ref, { - output: "", - metadata: { - sessionID: "ses_demo_child", - status: "completed", - output: "", - }, - }) + doneTool(state, ref, subagentLaunch("ses_demo_child")) const part = { type: "tool", id: "sub_demo_call_1", @@ -666,14 +671,7 @@ function emitPermission(state: State, kind: PermissionKind = "edit"): void { permission: "subagent", patterns: ["explore"], always: ["*"], - done: { - output: "", - metadata: { - sessionID: "sub_demo_perm_1", - status: "completed", - output: "", - }, - }, + done: subagentLaunch("sub_demo_perm_1"), }) return } @@ -713,10 +711,7 @@ function emitPermission(state: State, kind: PermissionKind = "edit"): void { permission: "doom_loop", patterns: ["*"], always: ["*"], - done: { - output: "Continuing after repeated failures.\n", - metadata: {}, - }, + done: subagentLaunch("sub_demo_doom_1"), }) return } diff --git a/packages/tui/src/mini/footer.ts b/packages/tui/src/mini/footer.ts index eb868d991147..36b1cd69423f 100644 --- a/packages/tui/src/mini/footer.ts +++ b/packages/tui/src/mini/footer.ts @@ -100,7 +100,6 @@ type RunFooterOptions = { onModelSelect?: (model: NonNullable) => CycleResult | void | Promise onVariantSelect?: (variant: string | undefined) => CycleResult | void | Promise onInterrupt?: () => void - onBackground?: () => void onQueuedPromptAction?: (action: QueuedPromptAction, inboxID: string) => Promise onEditorOpen: (input: { value: string }) => Promise onSubagentSelect?: (sessionID: string | undefined) => void @@ -358,7 +357,6 @@ export class RunFooter implements FooterApi { onFormCancel: footer.handleFormCancel, onCycle: footer.handleCycle, onInterrupt: footer.handleInterrupt, - onBackground: options.onBackground, onQueuedPromptAction: options.onQueuedPromptAction, onEditorOpen: (input) => { footer.finishStartup() diff --git a/packages/tui/src/mini/footer.view.tsx b/packages/tui/src/mini/footer.view.tsx index 21771043b20c..405e770ee28a 100644 --- a/packages/tui/src/mini/footer.view.tsx +++ b/packages/tui/src/mini/footer.view.tsx @@ -108,7 +108,6 @@ type RunFooterViewProps = { onFormCancel: (input: FormCancel) => void | Promise onCycle: () => void onInterrupt: () => boolean - onBackground?: () => void onQueuedPromptAction?: (action: QueuedPromptAction, inboxID: string) => Promise onEditorOpen: (input: { value: string }) => Promise onInputClear: () => void @@ -185,7 +184,6 @@ export function RunFooterView(props: RunFooterViewProps) { return tabs().findIndex((item) => item.sessionID === sessionID) + 1 }) - const foregroundSubagents = createMemo(() => activeTabs().some((item) => !item.background)) const model = createMemo(() => { const current = props.currentModel() return current ? modelInfo(props.providers(), current) : undefined @@ -199,7 +197,6 @@ export function RunFooterView(props: RunFooterViewProps) { const command = () => shortcut("command.palette.show") const subagentShortcut = () => shortcut("session.child.first") const queuedShortcut = () => shortcut("session.queued_prompts") - const backgroundShortcut = () => shortcut("session.background") const subagentInterruptShortcut = () => shortcut("composer.subagent.interrupt") const interrupt = () => shortcut("session.interrupt") const variantCycle = () => monoShortcut(shortcuts.all("variant.cycle") ?? "", props.mono) @@ -452,8 +449,7 @@ export function RunFooterView(props: RunFooterViewProps) { return [] } - const items: Array<{ id: "queued" | "subagents" | "background"; key: string; label: string; expanded?: string }> = - [] + const items: Array<{ id: "queued" | "subagents"; key: string; label: string; expanded?: string }> = [] if (queuedPrompts().length > 0 && queuedShortcut()) { items.push({ id: "queued", key: queuedShortcut(), label: `${queuedPrompts().length} pending` }) } @@ -465,9 +461,6 @@ export function RunFooterView(props: RunFooterViewProps) { expanded: `${activeTabs().length} subagent${activeTabs().length === 1 ? "" : "s"}`, }) } - if (foregroundSubagents() && backgroundShortcut()) { - items.push({ id: "background", key: backgroundShortcut(), label: "bg", expanded: "background" }) - } return items }) const commandHint = createMemo(() => { @@ -575,19 +568,6 @@ export function RunFooterView(props: RunFooterViewProps) { ], })) - Keymap.createLayer(() => ({ - enabled: active().type === "prompt" && route().type === "composer" && foregroundSubagents() && !!props.onBackground, - priority: 1, - commands: [ - { - id: "session.background", - title: "Background subagents", - group: "Session", - run: () => props.onBackground?.(), - }, - ], - })) - Keymap.createLayer(() => ({ enabled: active().type === "prompt" && route().type === "composer" && tabs().length > 0, commands: [ diff --git a/packages/tui/src/mini/footer.width.ts b/packages/tui/src/mini/footer.width.ts index 8d839ade69d8..795ce3bc3ff5 100644 --- a/packages/tui/src/mini/footer.width.ts +++ b/packages/tui/src/mini/footer.width.ts @@ -14,7 +14,6 @@ export type FooterStatuslineGroup = { | "escape" | "queued" | "subagents" - | "background" | "agent" | "model" | "context" @@ -29,7 +28,7 @@ export function footerStatuslinePolicy(input: { mono?: boolean status?: { text: string; expanded?: string } escape?: FooterAction - work: Array + work: Array model?: { name: string; variant?: string } agent?: string context?: { compact: string; full: string } @@ -69,7 +68,6 @@ export function footerStatuslinePolicy(input: { "escape", "queued", "subagents", - "background", "agent", "model", "context", diff --git a/packages/tui/src/mini/runtime.lifecycle.ts b/packages/tui/src/mini/runtime.lifecycle.ts index 934766699fd2..880ca0830765 100644 --- a/packages/tui/src/mini/runtime.lifecycle.ts +++ b/packages/tui/src/mini/runtime.lifecycle.ts @@ -77,7 +77,6 @@ export type LifecycleInput = { onModelSelect?: (model: NonNullable) => CycleResult | void | Promise onVariantSelect?: (variant: string | undefined) => CycleResult | void | Promise onInterrupt?: () => void - onBackground?: () => void onQueuedPromptAction?: (action: QueuedPromptAction, inboxID: string) => Promise onSubagentSelect?: (sessionID: string | undefined) => void onSubagentInterrupt?: (sessionID: string) => void @@ -249,7 +248,6 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise { if (closed || renderer.isDestroyed) { diff --git a/packages/tui/src/mini/runtime.ts b/packages/tui/src/mini/runtime.ts index a140271a541f..2d1e4fdb7677 100644 --- a/packages/tui/src/mini/runtime.ts +++ b/packages/tui/src/mini/runtime.ts @@ -383,14 +383,6 @@ async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDep ).catch(() => {}) return true }, - onBackground: () => { - if (!state.sessionID) { - return - } - - log?.write("send.background", { sessionID: state.sessionID }) - void state.sdk.session.background({ sessionID: state.sessionID }).catch(() => {}) - }, onQueuedPromptAction: async (action, inboxID) => { if (!state.sessionID) return log?.write(`send.pending.${action}`, { sessionID: state.sessionID, inboxID }) diff --git a/packages/tui/src/mini/stream-v2.subagent.ts b/packages/tui/src/mini/stream-v2.subagent.ts index 0feddffdc945..0f290f27aad4 100644 --- a/packages/tui/src/mini/stream-v2.subagent.ts +++ b/packages/tui/src/mini/stream-v2.subagent.ts @@ -12,9 +12,7 @@ // and reconnect, then continue from live deltas using the same // projected-prefix dedup the parent transport uses. // -// Per-child interruption uses `v2.session.interrupt(childID)`. Per-child -// backgrounding is intentionally absent: subagent jobs block the parent -// session, so only whole-session `v2.session.background(parentID)` exists. +// Per-child interruption uses `v2.session.interrupt(childID)`. import type { EventSubscribeOutput, OpenCodeClient, @@ -106,7 +104,6 @@ type ChildState = { label: string description: string status: FooterSubagentTab["status"] - background: boolean title?: string lastUpdatedAt: number frames: Frame[] @@ -195,7 +192,6 @@ function tab(child: ChildState): FooterSubagentTab { label: child.label, description: child.description || child.title || "", status: child.status, - background: child.background ? true : undefined, title: child.title, } } @@ -233,7 +229,6 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac label: FALLBACK_LABEL, description: "", status: "running", - background: false, lastUpdatedAt: 0, frames: [], fragments: createFragmentReconciler(), @@ -286,7 +281,6 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac if (agent) child.label = Locale.titlecase(agent) const description = text(meta.description) if (description) child.description = description - if (meta.background === true) child.background = true } const userFrame = (child: ChildState, messageID: string, prompt: Pick) => { @@ -943,7 +937,6 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac const child = admitChild(found.sessionID) if (!child) return applyMeta(child, record(tool.state.input)) - if (tool.state.status === "completed" && found.running) child.background = true if (child.status === "running") { const running = found.running && (!active || found.sessionID in active) child.status = running ? "running" : "completed" @@ -989,10 +982,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac const child = admitChild(found.sessionID) if (!child) return applyMeta(child, pending) - if (event.type === "session.tool.success" && found.running) { - child.background = true - child.status = "running" - } + if (event.type === "session.tool.success" && found.running) child.status = "running" if (event.type === "session.tool.success" && !found.running && child.status === "running") child.status = "completed" touch(child, event.created) diff --git a/packages/tui/src/mini/tool.ts b/packages/tui/src/mini/tool.ts index e911aef2ecb8..83ce7f24ecf1 100644 --- a/packages/tui/src/mini/tool.ts +++ b/packages/tui/src/mini/tool.ts @@ -1342,7 +1342,7 @@ export function toolEntryBody( return undefined } - if (commit.phase === "final" && ctx.status === "completed") { + if (commit.phase === "final" && ctx.status === "completed" && ctx.meta.status !== "running") { const result = taskResult(ctx.output) if (result) { return markdownBody(result) diff --git a/packages/tui/src/mini/types.ts b/packages/tui/src/mini/types.ts index f93e9e5579ce..4519a2a91402 100644 --- a/packages/tui/src/mini/types.ts +++ b/packages/tui/src/mini/types.ts @@ -316,7 +316,6 @@ export type FooterSubagentTab = { label: string description: string status: "running" | "completed" | "cancelled" | "error" - background?: boolean title?: string } diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index fb3573801bcb..b8b4262ba884 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1908,8 +1908,7 @@ function BackgroundToolHint(props: { messages: SessionMessageInfo[] }) { ) const part = current?.content.find((part): part is SessionMessageAssistantTool => { if (part.type !== "tool" || part.state.status !== "running") return false - const name = canonicalToolName(part.name) - return name === "shell" || name === "subagent" + return canonicalToolName(part.name) === "shell" }) if (!current || !part) return return { key: `${current.id}:${part.id}`, started: part.time.ran ?? part.time.created } @@ -3340,11 +3339,6 @@ function Subagent(props: ToolProps) { const id = sessionID() if (id) navigate({ type: "session", sessionID: id }) }} - status={ - isBackgroundSubagent(props.metadata, props.part.state.status) ? ( - Background - ) : undefined - } > {`${continuation() ? "Continue subagent" : `${Locale.titlecase(stringValue(props.input.agent) ?? stringValue(props.input.subagent_type) ?? "General")} Subagent`} — ${description() ?? "Subagent"}${model() ? ` · ${model()}` : ""}`} @@ -3364,13 +3358,6 @@ export function subagentModelLabel( return `${name ?? reference}${variant ? ` (${variant})` : ""}` } -export function isBackgroundSubagent( - metadata: Record, - status: SessionMessageAssistantTool["state"]["status"], -) { - return status === "completed" && metadata.status === "running" -} - export { executeCallSummary } function ExecuteCallView(props: { call: Accessor }) { diff --git a/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx b/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx index bf2c303bf7fd..661e9c4a13b9 100644 --- a/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx +++ b/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx @@ -5,7 +5,6 @@ import { InlineToolRow, executeCallSummary, genericToolSummary, - isBackgroundSubagent, parseApplyPatchFiles, parseDiagnostics, parseQuestionAnswers, @@ -231,13 +230,6 @@ describe("TUI inline tool wrapping", () => { ).toEqual([{ message: "valid", range: { start: { line: 2, character: 3 } } }]) }) - test("labels only detached or async subagents as background", () => { - expect(isBackgroundSubagent({ status: "running" }, "running")).toBeFalse() - expect(isBackgroundSubagent({ status: "running" }, "completed")).toBeTrue() - expect(isBackgroundSubagent({ status: "running" }, "error")).toBeFalse() - expect(isBackgroundSubagent({ status: "completed" }, "completed")).toBeFalse() - }) - test("labels only explicit subagent model overrides", () => { const models = [{ providerID: "anthropic", id: "claude-opus-4-1", name: "Claude Opus 4.1" }] expect(subagentModelLabel(undefined, models)).toBeUndefined() diff --git a/packages/tui/test/mini/entry.body.test.ts b/packages/tui/test/mini/entry.body.test.ts index 42b53ecc6c55..5ff5af2f7e40 100644 --- a/packages/tui/test/mini/entry.body.test.ts +++ b/packages/tui/test/mini/entry.body.test.ts @@ -234,7 +234,23 @@ describe("run entry body", () => { }) }) - test("promotes subagent results to markdown and falls back to structured summaries", () => { + test("renders a task card for a completed background subagent launch", () => { + const launch = toolCommit({ + tool: "subagent", + state: { + status: "completed", + input: { description: "Inspect reducer", agent: "explore" }, + metadata: { sessionID: "ses-child-1", status: "running" }, + content: [{ type: "text", text: "The subagent is working in the background (sessionID: ses-child-1)." }], + }, + }) + expect(entryBody(launch)).toEqual({ + type: "structured", + snapshot: { kind: "task", title: "# Explore Subagent", rows: ["Inspect reducer"], tail: "" }, + }) + }) + + test("promotes legacy subagent results to markdown and falls back to structured summaries", () => { const result = toolCommit({ tool: "subagent", state: { diff --git a/packages/tui/test/mini/footer.view.test.tsx b/packages/tui/test/mini/footer.view.test.tsx index 6eb1381db415..6609d4eee24c 100644 --- a/packages/tui/test/mini/footer.view.test.tsx +++ b/packages/tui/test/mini/footer.view.test.tsx @@ -1760,7 +1760,7 @@ test("direct footer counts queued and steering work while running", async () => const frame = app.captureCharFrame() const transparent = RGBA.fromValues(0, 0, 0, 0).toInts() const statusline = footerStatusline(app.renderer.root) - expect(frame).toContain("esc stop · ctrl+x q 2 pending · ↓ 1 subagent · ctrl+b background · Build") + expect(frame).toContain("ctrl+x q 2 pending · ↓ 1 subagent · Build") expect(frame).toMatch(/opencode · ctrl\+p menu *$/m) expect(frame).not.toContain("1 agent") expect(statusline.backgroundColor.toInts()).toEqual(transparent) @@ -1990,7 +1990,6 @@ test.each(["ctrl+g", "none"])("context actions use only configured bindings (%s) "session.interrupt": "ctrl+i", "session.queued_prompts": queued, "session.child.first": "ctrl+j", - "session.background": "none", "command.palette.show": "ctrl+y", }, }), @@ -2034,7 +2033,7 @@ test("identity and context precede the provider and a non-fitting provider block } }) -test("direct footer keeps compact work, model detail, and context ahead of cost and rich labels", async () => { +test("direct footer keeps work, model detail, context, and cost in priority order", async () => { const app = await renderFooter({ currentAgent: "Plan", subagents: { @@ -2055,7 +2054,7 @@ test("direct footer keeps compact work, model detail, and context ahead of cost await app.renderOnce() const statusline = footerStatusline(app.renderer.root) expect(app.captureCharFrame().split("\n")[statusline.y].trimEnd()).toBe( - "\u25aa esc stop · ↓ 1 sub · ctrl+b bg · Plan · a-model-name-long-enough… · 16% ctx", + "\u25aa esc stop · ↓ 1 sub · Plan · a-model-name-long-enough… · 159.6K (16%) · $4.23", ) } finally { app.cleanup() @@ -2186,7 +2185,7 @@ test("direct footer reserves the working indicator beside complete status text", } }) -test("direct footer always offers backgrounding for a foreground subagent", async () => { +test("direct footer never offers backgrounding for a subagent", async () => { const app = await renderFooter({ subagents: { tabs: [subagent({ sessionID: "s-1", label: "Explore", description: "Inspect auth flow" })], @@ -2201,7 +2200,8 @@ test("direct footer always offers backgrounding for a foreground subagent", asyn await app.renderOnce() const frame = app.captureCharFrame() - expect(frame).toContain("↓ 1 subagent · ctrl+b background · Build · gpt-5 · ctrl+p menu") + expect(frame).toContain("↓ 1 subagent · Build · gpt-5 · ctrl+p menu") + expect(frame).not.toContain("ctrl+b") expect(frame).not.toContain("queued") } finally { app.cleanup() diff --git a/packages/tui/test/mini/footer.width.test.ts b/packages/tui/test/mini/footer.width.test.ts index 59795d8563f7..d761d63a9ba9 100644 --- a/packages/tui/test/mini/footer.width.test.ts +++ b/packages/tui/test/mini/footer.width.test.ts @@ -31,7 +31,6 @@ describe("run footer width", () => { work: [ { id: "queued", key: "ctrl+x q", label: "12 queued" }, { id: "subagents", key: mono ? "down" : "\u2193", label: "2 sub", expanded: "2 subagents" }, - { id: "background", key: "ctrl+b", label: "bg", expanded: "background" }, ], }, { work: [], status: { text: "Shell" }, escape: { key: "esc", label: "normal" }, context: screenshot.context }, diff --git a/packages/tui/test/mini/stream-v2.transport.test.ts b/packages/tui/test/mini/stream-v2.transport.test.ts index 77abc8649216..79b3f4f4775f 100644 --- a/packages/tui/test/mini/stream-v2.transport.test.ts +++ b/packages/tui/test/mini/stream-v2.transport.test.ts @@ -3789,7 +3789,6 @@ describe("V2 mini transport", () => { label: "Explore", description: "Inspect progress", status: "running", - background: undefined, }, ]) @@ -4559,7 +4558,7 @@ describe("V2 mini transport", () => { model: { providerID: "test", id: "model" }, }, }) - // Parent's background subagent tool.success adopts the child mid-discovery. + // Parent's subagent tool.success adopts the child mid-discovery. events.push({ id: "evt_parent_input", created: 0, @@ -4581,7 +4580,7 @@ describe("V2 mini transport", () => { sessionID: "ses_1", assistantMessageID: "msg_parent_a", id: "call_sub", - input: { agent: "explore", description: "Find things", prompt: "go", background: true }, + input: { agent: "explore", description: "Find things", prompt: "go" }, executed: true, }, }) diff --git a/services/data/cloudflare.config.ts b/services/data/cloudflare.config.ts index 778a2dc23c0d..5adf9eef8298 100644 --- a/services/data/cloudflare.config.ts +++ b/services/data/cloudflare.config.ts @@ -1,7 +1,7 @@ import { bindings, defineConfig, triggers } from "cf/config" import { LOCALES } from "../../packages/data/app/src/lib/language" import { ogWorkerName } from "./og.config" -import { stage, stageHost } from "./stage" +import { stage, stageAccount, stageHost } from "./stage" // The data site (packages/data/app, SolidStart) at /data and //data on the main host. `--mode dev` deploys // opencode-data-dev on dev.opencode.ai and `--mode production` opencode-data-production on opencode.ai; any other @@ -14,7 +14,7 @@ export default defineConfig(({ mode }) => { const host = stageHost(current) return { // Anomaly - accountId: "15d29c8639fd3733b1b5486a2acfd968", + accountId: stageAccount(current), worker: { name: `opencode-data-${current}`, compatibilityDate: "2026-07-25", @@ -33,7 +33,7 @@ export default defineConfig(({ mode }) => { DATA_DATABASE_PASSWORD: bindings.secret(), }, triggers: ["data", ...LOCALES.map((locale) => `${locale}/data`)].map((prefix) => - triggers.fetch({ pattern: `${host}/${prefix}*`, zone: "opencode.ai" }), + triggers.fetch({ pattern: `${host}/${prefix}*`, zone: host }), ), workersDev: false, previewUrls: false, diff --git a/services/data/og.config.ts b/services/data/og.config.ts index 923ec01c803f..db6e21cb1329 100644 --- a/services/data/og.config.ts +++ b/services/data/og.config.ts @@ -1,5 +1,5 @@ import { defineConfig } from "cf/config" -import { stage } from "./stage" +import { stage, stageAccount } from "./stage" export const ogWorkerName = (mode: string | undefined) => `opencode-data-og-${stage(mode)}` @@ -8,7 +8,7 @@ export const ogWorkerName = (mode: string | undefined) => `opencode-data-og-${st // Worker doesn't load the Wasm engines and fonts it ships as modules (script/build.ts). export default defineConfig(({ mode }) => ({ // Anomaly - accountId: "15d29c8639fd3733b1b5486a2acfd968", + accountId: stageAccount(stage(mode)), worker: { name: ogWorkerName(mode), compatibilityDate: "2026-07-01", diff --git a/services/data/stage.ts b/services/data/stage.ts index 6500e1dc435e..fd5075ae9e4c 100644 --- a/services/data/stage.ts +++ b/services/data/stage.ts @@ -16,3 +16,7 @@ export function stage(mode: string | undefined): Stage { export function stageHost(value: Stage) { return hosts[value] } + +export function stageAccount(value: Stage) { + return value === "dev" ? "d8e944f537ceef3f06a5bd3aec1d7a53" : "15d29c8639fd3733b1b5486a2acfd968" +} diff --git a/services/data/sync.config.ts b/services/data/sync.config.ts index 8d7985c9dde5..7f33cc77a574 100644 --- a/services/data/sync.config.ts +++ b/services/data/sync.config.ts @@ -1,5 +1,5 @@ import { bindings, defineConfig, exports, triggers } from "cf/config" -import { stage } from "./stage" +import { stage, stageAccount } from "./stage" // The Worker that syncs R2 SQL aggregates into the data database (packages/data/server/src/worker.ts): the // DataSyncWorkflow, and the cron handler that starts its runs. The schedules must match @@ -9,7 +9,7 @@ export default defineConfig(({ mode }) => { const name = `opencode-data-sync-${current}` return { // Anomaly - accountId: "15d29c8639fd3733b1b5486a2acfd968", + accountId: stageAccount(current), worker: { name, compatibilityDate: "2026-07-25", @@ -24,6 +24,7 @@ export default defineConfig(({ mode }) => { env: { DataSyncWorkflow: bindings.workflow({ name, worker: name, exportName: "DataSyncWorkflow" }), STAGE: bindings.text(current), + ...(current === "dev" && { R2_SQL_ACCOUNT_ID: bindings.text(stageAccount(current)) }), // Set from AWS Secrets Manager (opencode//*) by the deploy job. DATA_DATABASE_HOST: bindings.secret(), DATA_DATABASE_USERNAME: bindings.secret(), diff --git a/services/files/wrangler.jsonc b/services/files/wrangler.jsonc index 8ea83447e810..3860221bc2be 100644 --- a/services/files/wrangler.jsonc +++ b/services/files/wrangler.jsonc @@ -8,8 +8,9 @@ "env": { "dev": { "name": "opencode-dev-files", + "account_id": "d8e944f537ceef3f06a5bd3aec1d7a53", "vars": { "STAGE": "dev" }, - "routes": [{ "pattern": "dev.opencode.ai/files/*", "zone_name": "opencode.ai" }], + "routes": [{ "pattern": "dev.opencode.ai/files/*", "zone_name": "dev.opencode.ai" }], "r2_buckets": [{ "binding": "FILES", "bucket_name": "opencode-dev-files" }], }, "production": { diff --git a/services/legacy/README.md b/services/legacy/README.md index 8aeb75cda19d..2e1f40f91c1b 100644 --- a/services/legacy/README.md +++ b/services/legacy/README.md @@ -9,13 +9,13 @@ One Worker that answers by hostname: Session sharing was retired in #55716 and V2 has no sharing. They serve the "Session sharing has been discontinued" page, and the old `/api/share` endpoints still answer so V1 clients keep working (`src/share.ts`). -- `api.opencode.ai` (production) and `api.dev.opencode.ai` (development) exchange a GitHub Actions +- `api.opencode.ai` (production) exchanges a GitHub Actions OIDC token for a GitHub App installation token for the V1 GitHub Action - (`POST /exchange_github_app_token`, `src/api.ts`). + (`POST /exchange_github_app_token`, `src/api.ts`). The dev endpoint returns 503. `cloudflare.config.ts` defines the Worker. `deploy:dev` and `deploy:production` deploy it with `cf` -from `.github/workflows/deploy.yml`. The deploy job reads the `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` Worker -secrets from AWS Secrets Manager (`opencode//GITHUB_APP_*`) and uploads them with +from `.github/workflows/deploy.yml`. The production deploy reads the `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` Worker +secrets from AWS Secrets Manager (`opencode/production/GITHUB_APP_*`) and uploads them with `--secrets-file`. | Environment | Worker | Hostnames | diff --git a/services/legacy/cloudflare.config.ts b/services/legacy/cloudflare.config.ts index 425342b6df7a..6455c5604e63 100644 --- a/services/legacy/cloudflare.config.ts +++ b/services/legacy/cloudflare.config.ts @@ -9,7 +9,7 @@ export default defineConfig(({ mode }) => { const dev = mode === "dev" return { // Anomaly - accountId: "15d29c8639fd3733b1b5486a2acfd968", + accountId: dev ? "d8e944f537ceef3f06a5bd3aec1d7a53" : "15d29c8639fd3733b1b5486a2acfd968", worker: { name: dev ? "opencode-legacy-dev" : "opencode-legacy-production", compatibilityDate: "2026-07-25", @@ -17,14 +17,14 @@ export default defineConfig(({ mode }) => { compatibilityFlags: ["nodejs_compat"], entrypoint: "./src/index.ts", domains: dev ? ["dev.opncd.ai", "api.dev.opencode.ai"] : ["opncd.ai", "api.opencode.ai"], - // Set from AWS Secrets Manager (opencode//GITHUB_APP_*) by the deploy job with --secrets-file. - env: { + // The production deploy supplies these from AWS Secrets Manager with --secrets-file. + env: mode !== "production" ? undefined : { GITHUB_APP_ID: bindings.secret(), GITHUB_APP_PRIVATE_KEY: bindings.secret(), }, workersDev: false, previewUrls: false, - logpush: true, + logpush: !dev, observability: { enabled: true }, }, } diff --git a/services/legacy/src/api.ts b/services/legacy/src/api.ts index 7a2503b64f62..d56729d0559b 100644 --- a/services/legacy/src/api.ts +++ b/services/legacy/src/api.ts @@ -5,8 +5,8 @@ import { Octokit } from "@octokit/rest" import { parseRepositoryClaim } from "./github" export interface Env { - GITHUB_APP_ID: string - GITHUB_APP_PRIVATE_KEY: string + GITHUB_APP_ID?: string + GITHUB_APP_PRIVATE_KEY?: string } export default new Hono<{ Bindings: Env }>() @@ -15,6 +15,10 @@ export default new Hono<{ Bindings: Env }>() * Used by the GitHub action to get GitHub installation access token given the OIDC token */ .post("/exchange_github_app_token", async (c) => { + if (!c.env.GITHUB_APP_ID || !c.env.GITHUB_APP_PRIVATE_KEY) { + const dev = new URL(c.req.url).hostname === "api.dev.opencode.ai" + return c.json({ error: dev ? "not configured on dev" : "GitHub App not configured" }, 503) + } const EXPECTED_AUDIENCE = "opencode-github-action" const GITHUB_ISSUER = "https://token.actions.githubusercontent.com" const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks` diff --git a/services/site/MEDIA.md b/services/site/MEDIA.md index f195681c58e1..562eaab3df7d 100644 --- a/services/site/MEDIA.md +++ b/services/site/MEDIA.md @@ -9,6 +9,7 @@ The site's heavy media (product videos, arcade sounds, 3D models and download zi - The build (`script/build.ts`) drops every `mediaFile` from the Worker's assets, so a local copy in `public/` never ships. - In development, `vite dev` proxies `/files` to `https://dev.opencode.ai`, so pages play the dev bucket's copies. - Images (`png`, `jpg`, `webp`, `avif`, `svg`), posters, fonts and the 3D decoders (`arcade3d/draco`, `arcade3d/basis`) stay in git and in the static assets. +- The link-card videos in `og/` (`og:video`, from `script/og.ts`) are the exception: they are small and ship as static assets with their cards. - `videoSources()` offers a video's AV1 and HEVC copies (`media/....mp4`, listed in `src/component/site/media-manifest.json`) before the H.264 original. The manifest lists only copies that are in the bucket; a video without copies plays its original. | Folder | Files | diff --git a/services/site/cloudflare.config.ts b/services/site/cloudflare.config.ts index fd1d50b2be19..515ce62e952b 100644 --- a/services/site/cloudflare.config.ts +++ b/services/site/cloudflare.config.ts @@ -15,7 +15,7 @@ export default defineConfig(({ mode }) => { const host = dev ? "dev.opencode.ai" : "opencode.ai" return { // Anomaly - accountId: "15d29c8639fd3733b1b5486a2acfd968", + accountId: dev ? "d8e944f537ceef3f06a5bd3aec1d7a53" : "15d29c8639fd3733b1b5486a2acfd968", worker: { name: dev ? "opencode-site-dev" : "opencode-site-production", compatibilityDate: "2026-07-25", @@ -39,8 +39,8 @@ export default defineConfig(({ mode }) => { triggers: dev || productionOwnsRoot ? [ - triggers.fetch({ pattern: host, zone: "opencode.ai" }), - triggers.fetch({ pattern: `${host}/*`, zone: "opencode.ai" }), + triggers.fetch({ pattern: host, zone: host }), + triggers.fetch({ pattern: `${host}/*`, zone: host }), ] : [], // The bare host is a custom domain (it also supplies the DNS record), and cf detaches any domain diff --git a/services/site/script/build.ts b/services/site/script/build.ts index 08db04c61883..3a0759047636 100644 --- a/services/site/script/build.ts +++ b/services/site/script/build.ts @@ -14,7 +14,7 @@ import { writeWorkerConfig, } from "@cloudflare/build-output-utils" import { resolveAndParseConfig } from "@cloudflare/config" -import { mediaFile } from "../src/lib/media" +import { inBucket } from "../src/lib/media" import { stageHeaders } from "../src/lib/noindex" import { retainAssets } from "./retain-assets" @@ -57,10 +57,11 @@ await writeRootConfig( // Heavy media is never a Worker asset; it is served from the files bucket (src/lib/media.ts). const assets = path.join(root, "dist", "assets") +const output = path.join(root, ".output", "public") await rm(assets, { recursive: true, force: true }) -await cp(path.join(root, ".output", "public"), assets, { +await cp(output, assets, { recursive: true, - filter: (file) => !mediaFile.test(file), + filter: (file) => !inBucket(path.relative(output, file)), }) const shipped = await Array.fromAsync(new Bun.Glob("**/*").scan({ cwd: assets, dot: true })) // Every opencode.json and V1 TUI config names these as its $schema; /openapi.json is the protocol's. diff --git a/services/site/script/og.ts b/services/site/script/og.ts index b49498cb3118..d5828da16f32 100644 --- a/services/site/script/og.ts +++ b/services/site/script/og.ts @@ -4,6 +4,10 @@ // title, image or template gives it a new URL and link previews refresh. Cards are English at // every locale. // +// OG Studio (a local design tool) can replace any card. It writes finished files and a manifest to +// src/asset/og-studio/: for each page an English PNG, an optional MP4 for og:video and an optional +// PNG for each locale. Pages in that manifest use its files; every other page renders here. +// // This file is the cards' source of truth. The layout is David's template frame in Paper (the // "OG images" file, frame "/ — dark"): a grid of #2e2e2e lines at x 72, 900 and 1128 and y 72, // 557 and 629, the logo icon in the top-left cell, the title and a description of at most two @@ -19,6 +23,7 @@ import { decompress } from "wawoff2" const root = path.resolve(import.meta.dir, "..") const out = path.join(root, "public/og") +const STUDIO = "src/asset/og-studio" const W = 1200 const H = 630 @@ -97,13 +102,6 @@ const cards: Card[] = [ shows: "TypeScript code that creates an OpenCode client with the SDK, at an angle", shot: angled(`${covers}/sdk.webp`, [100, 420, 964, 440], 300), }, - { - path: "/ide", - title: "IDE extensions", - description: "Open OpenCode in VS Code, Cursor, Windsurf, Zed and JetBrains IDEs.", - shows: "the OpenCode terminal UI that the extensions open beside your code, at an angle", - shot: angled("public/product-videos/heroes/terminal-landscape-dark.webp", [430, 380, 1100, 560], 270), - }, { path: "/mini", title: "Mini", @@ -202,8 +200,27 @@ const fonts = [ ] await mkdir(out, { recursive: true }) -const manifest: Record = {} -for (const card of cards) { +const manifest: Record = {} +const studio = await readStudio() +for (const [page, entry] of Object.entries(studio?.cards ?? {})) { + const files = [entry.image, entry.video, ...Object.values(entry.locales ?? {}).map((l) => l.image)].filter( + (file): file is string => Boolean(file), + ) + await Promise.all(files.map((file) => Bun.write(path.join(out, file), Bun.file(path.join(root, STUDIO, file))))) + manifest[page] = { + src: `/og/${entry.image}`, + alt: entry.alt, + ...(entry.video ? { video: `/og/${entry.video}` } : {}), + ...(entry.locales + ? { + locales: Object.fromEntries( + Object.entries(entry.locales).map(([locale, l]) => [locale, { src: `/og/${l.image}`, alt: l.alt }]), + ), + } + : {}), + } +} +for (const card of cards.filter((card) => !manifest[card.path])) { await checkDescription(card) const image = card.shot === "orb" ? await orb() : await project(card.shot) const svg = await satori(plate(card, image), { width: W, height: H, fonts }) @@ -216,12 +233,30 @@ for (const card of cards) { alt: `OpenCode link card: “${card.title}” and “${card.description}” beside ${card.shows}.`, } } -const keep = new Set(Object.values(manifest).map((card) => path.basename(card.src))) +const keep = new Set( + Object.values(manifest).flatMap((card) => + [card.src, card.video, ...Object.values(card.locales ?? {}).map((l) => l.src)] + .filter((src): src is string => Boolean(src)) + .map((src) => path.basename(src)), + ), +) await Promise.all( (await readdir(out)).filter((file) => !keep.has(file)).map((file) => rm(path.join(out, file), { force: true })), ) await Bun.write(path.join(root, "src/lib/og-images.json"), JSON.stringify(manifest, null, 2) + "\n") -console.log(`og: ${cards.length} cards in public/og`) +console.log(`og: ${Object.keys(manifest).length} cards in public/og (${Object.keys(studio?.cards ?? {}).length} from OG Studio)`) + +type OgEntry = { src: string; alt: string; video?: string; locales?: Record } + +type Studio = { + cards: Record }> +} + +async function readStudio() { + const file = Bun.file(path.join(root, STUDIO, "manifest.json")) + if (!(await file.exists())) return undefined + return (await file.json()) as Studio +} function plate(card: Card, image: string) { const size = titleSize(card.title) diff --git a/services/site/script/stylesheet-groups.ts b/services/site/script/stylesheet-groups.ts index 8b24d9a8d2ad..f2077377ad6a 100644 --- a/services/site/script/stylesheet-groups.ts +++ b/services/site/script/stylesheet-groups.ts @@ -2,7 +2,7 @@ import type { PluginOption } from "vite" // Pages that share a layout share a stylesheet: the product pages with the changelog (both show // release notes), and otherwise each section of the site (the route's first path segment). -const productPages = /^(product|desktop|terminal|mobile|sdk|ide|mini|changelog)(\/|$)/ +const productPages = /^(product|desktop|terminal|mobile|sdk|mini|changelog)(\/|$)/ const shell = /[\\/]src[\\/](app|component[\\/]site[\\/]site)\.tsx$/ /** diff --git a/services/site/script/upload-media.ts b/services/site/script/upload-media.ts index 14be56b77960..32a1c456a549 100644 --- a/services/site/script/upload-media.ts +++ b/services/site/script/upload-media.ts @@ -1,4 +1,4 @@ -// Uploads the heavy media in public/ (src/lib/media.ts `mediaFile`) to the existing files bucket, +// Uploads the heavy media in public/ (src/lib/media.ts `inBucket`) to the existing files bucket, // which the /files route serves (services/files), under site/2026-11 at the same path, and writes // media-manifest.txt. Not part of the build. // @@ -11,7 +11,7 @@ import { createHash } from "node:crypto" import path from "node:path" import { Glob } from "bun" -import { mediaBase, mediaFile } from "../src/lib/media" +import { inBucket, mediaBase } from "../src/lib/media" const root = path.resolve(import.meta.dir, "..") const publicDir = path.join(root, "public") @@ -21,9 +21,7 @@ const prefix = mediaBase.replace(/^\/files\//, "") const run = process.argv.includes("--run") const writeManifest = process.argv.includes("--manifest") -const files = (await Array.fromAsync(new Glob("**/*").scan({ cwd: publicDir }))) - .filter((file) => mediaFile.test(file)) - .sort() +const files = (await Array.fromAsync(new Glob("**/*").scan({ cwd: publicDir }))).filter(inBucket).sort() const types: Record = { mp4: "video/mp4", diff --git a/services/site/src/app.tsx b/services/site/src/app.tsx index 98e244919c95..4440c3c2bd19 100644 --- a/services/site/src/app.tsx +++ b/services/site/src/app.tsx @@ -25,7 +25,6 @@ const shareImagePages = [ "/terminal", "/mobile", "/sdk", - "/ide", "/mini", "/product/browse", "/product", diff --git a/services/site/src/asset/og-studio/brand-4e61968505.png b/services/site/src/asset/og-studio/brand-4e61968505.png new file mode 100644 index 000000000000..683ed611ad2b Binary files /dev/null and b/services/site/src/asset/og-studio/brand-4e61968505.png differ diff --git a/services/site/src/asset/og-studio/brand-9a58b5052b.mp4 b/services/site/src/asset/og-studio/brand-9a58b5052b.mp4 new file mode 100644 index 000000000000..842230597894 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-9a58b5052b.mp4 differ diff --git a/services/site/src/asset/og-studio/brand-ar-e187032cd0.png b/services/site/src/asset/og-studio/brand-ar-e187032cd0.png new file mode 100644 index 000000000000..9ad837fd6117 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-ar-e187032cd0.png differ diff --git a/services/site/src/asset/og-studio/brand-br-3681ae5782.png b/services/site/src/asset/og-studio/brand-br-3681ae5782.png new file mode 100644 index 000000000000..09706d39b0c8 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-br-3681ae5782.png differ diff --git a/services/site/src/asset/og-studio/brand-da-7742cbb96d.png b/services/site/src/asset/og-studio/brand-da-7742cbb96d.png new file mode 100644 index 000000000000..680b391d423e Binary files /dev/null and b/services/site/src/asset/og-studio/brand-da-7742cbb96d.png differ diff --git a/services/site/src/asset/og-studio/brand-de-f966de83b2.png b/services/site/src/asset/og-studio/brand-de-f966de83b2.png new file mode 100644 index 000000000000..24b793c2a9b5 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-de-f966de83b2.png differ diff --git a/services/site/src/asset/og-studio/brand-es-bc04e49810.png b/services/site/src/asset/og-studio/brand-es-bc04e49810.png new file mode 100644 index 000000000000..ab96147df6aa Binary files /dev/null and b/services/site/src/asset/og-studio/brand-es-bc04e49810.png differ diff --git a/services/site/src/asset/og-studio/brand-fr-7e3c48cfb2.png b/services/site/src/asset/og-studio/brand-fr-7e3c48cfb2.png new file mode 100644 index 000000000000..b7d2e6d1a073 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-fr-7e3c48cfb2.png differ diff --git a/services/site/src/asset/og-studio/brand-it-58abfa8752.png b/services/site/src/asset/og-studio/brand-it-58abfa8752.png new file mode 100644 index 000000000000..b0ab8dbda2ba Binary files /dev/null and b/services/site/src/asset/og-studio/brand-it-58abfa8752.png differ diff --git a/services/site/src/asset/og-studio/brand-ja-9cdf8661f4.png b/services/site/src/asset/og-studio/brand-ja-9cdf8661f4.png new file mode 100644 index 000000000000..6ea58d9ac067 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-ja-9cdf8661f4.png differ diff --git a/services/site/src/asset/og-studio/brand-ko-ab18888ef9.png b/services/site/src/asset/og-studio/brand-ko-ab18888ef9.png new file mode 100644 index 000000000000..b212165bff44 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-ko-ab18888ef9.png differ diff --git a/services/site/src/asset/og-studio/brand-no-e44bce8749.png b/services/site/src/asset/og-studio/brand-no-e44bce8749.png new file mode 100644 index 000000000000..422239ef662f Binary files /dev/null and b/services/site/src/asset/og-studio/brand-no-e44bce8749.png differ diff --git a/services/site/src/asset/og-studio/brand-pl-4c3904aa47.png b/services/site/src/asset/og-studio/brand-pl-4c3904aa47.png new file mode 100644 index 000000000000..5d3a3e06df31 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-pl-4c3904aa47.png differ diff --git a/services/site/src/asset/og-studio/brand-ru-3bbf5faf69.png b/services/site/src/asset/og-studio/brand-ru-3bbf5faf69.png new file mode 100644 index 000000000000..b245fad74314 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-ru-3bbf5faf69.png differ diff --git a/services/site/src/asset/og-studio/brand-th-6a64e2e42f.png b/services/site/src/asset/og-studio/brand-th-6a64e2e42f.png new file mode 100644 index 000000000000..bb98858a5d29 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-th-6a64e2e42f.png differ diff --git a/services/site/src/asset/og-studio/brand-tr-b939ad63b2.png b/services/site/src/asset/og-studio/brand-tr-b939ad63b2.png new file mode 100644 index 000000000000..0a103705960e Binary files /dev/null and b/services/site/src/asset/og-studio/brand-tr-b939ad63b2.png differ diff --git a/services/site/src/asset/og-studio/brand-uk-7ee60e7ba3.png b/services/site/src/asset/og-studio/brand-uk-7ee60e7ba3.png new file mode 100644 index 000000000000..56a0d140404d Binary files /dev/null and b/services/site/src/asset/og-studio/brand-uk-7ee60e7ba3.png differ diff --git a/services/site/src/asset/og-studio/brand-zh-dcc60b4c81.png b/services/site/src/asset/og-studio/brand-zh-dcc60b4c81.png new file mode 100644 index 000000000000..77dd83caa502 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-zh-dcc60b4c81.png differ diff --git a/services/site/src/asset/og-studio/brand-zht-2bef6d786d.png b/services/site/src/asset/og-studio/brand-zht-2bef6d786d.png new file mode 100644 index 000000000000..327ed7528223 Binary files /dev/null and b/services/site/src/asset/og-studio/brand-zht-2bef6d786d.png differ diff --git a/services/site/src/asset/og-studio/changelog-9e6442949d.mp4 b/services/site/src/asset/og-studio/changelog-9e6442949d.mp4 new file mode 100644 index 000000000000..fae6dc4d45a9 Binary files /dev/null and b/services/site/src/asset/og-studio/changelog-9e6442949d.mp4 differ diff --git a/services/site/src/asset/og-studio/changelog-a404a3db2b.png b/services/site/src/asset/og-studio/changelog-a404a3db2b.png new file mode 100644 index 000000000000..421ea5f00f87 Binary files /dev/null and b/services/site/src/asset/og-studio/changelog-a404a3db2b.png differ diff --git a/services/site/src/asset/og-studio/desktop-ar-388d8017c4.png b/services/site/src/asset/og-studio/desktop-ar-388d8017c4.png new file mode 100644 index 000000000000..56b031497efc Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-ar-388d8017c4.png differ diff --git a/services/site/src/asset/og-studio/desktop-br-fb89a41fdd.png b/services/site/src/asset/og-studio/desktop-br-fb89a41fdd.png new file mode 100644 index 000000000000..9225b4c25fc1 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-br-fb89a41fdd.png differ diff --git a/services/site/src/asset/og-studio/desktop-da-d09be44295.png b/services/site/src/asset/og-studio/desktop-da-d09be44295.png new file mode 100644 index 000000000000..e18602e8eaee Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-da-d09be44295.png differ diff --git a/services/site/src/asset/og-studio/desktop-de-9406d53da1.png b/services/site/src/asset/og-studio/desktop-de-9406d53da1.png new file mode 100644 index 000000000000..c035a5e4548a Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-de-9406d53da1.png differ diff --git a/services/site/src/asset/og-studio/desktop-es-8f9bc611c9.png b/services/site/src/asset/og-studio/desktop-es-8f9bc611c9.png new file mode 100644 index 000000000000..d6d5f34dbce8 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-es-8f9bc611c9.png differ diff --git a/services/site/src/asset/og-studio/desktop-f98d91d47d.png b/services/site/src/asset/og-studio/desktop-f98d91d47d.png new file mode 100644 index 000000000000..29a45d8c52cd Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-f98d91d47d.png differ diff --git a/services/site/src/asset/og-studio/desktop-fd77cfeffc.mp4 b/services/site/src/asset/og-studio/desktop-fd77cfeffc.mp4 new file mode 100644 index 000000000000..2008740e0f46 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-fd77cfeffc.mp4 differ diff --git a/services/site/src/asset/og-studio/desktop-fr-77596c43cb.png b/services/site/src/asset/og-studio/desktop-fr-77596c43cb.png new file mode 100644 index 000000000000..c71155ec2e40 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-fr-77596c43cb.png differ diff --git a/services/site/src/asset/og-studio/desktop-it-44bbc6db83.png b/services/site/src/asset/og-studio/desktop-it-44bbc6db83.png new file mode 100644 index 000000000000..a5d22d2c84a7 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-it-44bbc6db83.png differ diff --git a/services/site/src/asset/og-studio/desktop-ja-7f55912afd.png b/services/site/src/asset/og-studio/desktop-ja-7f55912afd.png new file mode 100644 index 000000000000..f4ba0a08ef2d Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-ja-7f55912afd.png differ diff --git a/services/site/src/asset/og-studio/desktop-ko-0f5228f239.png b/services/site/src/asset/og-studio/desktop-ko-0f5228f239.png new file mode 100644 index 000000000000..8625846103fa Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-ko-0f5228f239.png differ diff --git a/services/site/src/asset/og-studio/desktop-no-cc2b6484dc.png b/services/site/src/asset/og-studio/desktop-no-cc2b6484dc.png new file mode 100644 index 000000000000..bcc88cc0edda Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-no-cc2b6484dc.png differ diff --git a/services/site/src/asset/og-studio/desktop-pl-90701984e4.png b/services/site/src/asset/og-studio/desktop-pl-90701984e4.png new file mode 100644 index 000000000000..b053f7c84504 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-pl-90701984e4.png differ diff --git a/services/site/src/asset/og-studio/desktop-ru-247a36b9b4.png b/services/site/src/asset/og-studio/desktop-ru-247a36b9b4.png new file mode 100644 index 000000000000..982fd01e5788 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-ru-247a36b9b4.png differ diff --git a/services/site/src/asset/og-studio/desktop-th-f7dd62da10.png b/services/site/src/asset/og-studio/desktop-th-f7dd62da10.png new file mode 100644 index 000000000000..a5ab04b767f9 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-th-f7dd62da10.png differ diff --git a/services/site/src/asset/og-studio/desktop-tr-82d26cda7b.png b/services/site/src/asset/og-studio/desktop-tr-82d26cda7b.png new file mode 100644 index 000000000000..3cbce9324dda Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-tr-82d26cda7b.png differ diff --git a/services/site/src/asset/og-studio/desktop-uk-90ba41627f.png b/services/site/src/asset/og-studio/desktop-uk-90ba41627f.png new file mode 100644 index 000000000000..e83829e4ce43 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-uk-90ba41627f.png differ diff --git a/services/site/src/asset/og-studio/desktop-zh-50547b564e.png b/services/site/src/asset/og-studio/desktop-zh-50547b564e.png new file mode 100644 index 000000000000..5af9fb8d32ab Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-zh-50547b564e.png differ diff --git a/services/site/src/asset/og-studio/desktop-zht-0932f029e6.png b/services/site/src/asset/og-studio/desktop-zht-0932f029e6.png new file mode 100644 index 000000000000..acf038b7a383 Binary files /dev/null and b/services/site/src/asset/og-studio/desktop-zht-0932f029e6.png differ diff --git a/services/site/src/asset/og-studio/docs-40387ee840.mp4 b/services/site/src/asset/og-studio/docs-40387ee840.mp4 new file mode 100644 index 000000000000..3c16b8e0b287 Binary files /dev/null and b/services/site/src/asset/og-studio/docs-40387ee840.mp4 differ diff --git a/services/site/src/asset/og-studio/docs-e416d17432.png b/services/site/src/asset/og-studio/docs-e416d17432.png new file mode 100644 index 000000000000..ec65e4ee18f1 Binary files /dev/null and b/services/site/src/asset/og-studio/docs-e416d17432.png differ diff --git a/services/site/src/asset/og-studio/font-f345dc0fb4.png b/services/site/src/asset/og-studio/font-f345dc0fb4.png new file mode 100644 index 000000000000..7ee01f48a058 Binary files /dev/null and b/services/site/src/asset/og-studio/font-f345dc0fb4.png differ diff --git a/services/site/src/asset/og-studio/font-f768cba1a4.mp4 b/services/site/src/asset/og-studio/font-f768cba1a4.mp4 new file mode 100644 index 000000000000..8ecc6abfe095 Binary files /dev/null and b/services/site/src/asset/og-studio/font-f768cba1a4.mp4 differ diff --git a/services/site/src/asset/og-studio/home-98637499f6.png b/services/site/src/asset/og-studio/home-98637499f6.png new file mode 100644 index 000000000000..42e6ab434d13 Binary files /dev/null and b/services/site/src/asset/og-studio/home-98637499f6.png differ diff --git a/services/site/src/asset/og-studio/home-ar-b920e0ad64.png b/services/site/src/asset/og-studio/home-ar-b920e0ad64.png new file mode 100644 index 000000000000..4de2110bab79 Binary files /dev/null and b/services/site/src/asset/og-studio/home-ar-b920e0ad64.png differ diff --git a/services/site/src/asset/og-studio/home-br-b231c2eeda.png b/services/site/src/asset/og-studio/home-br-b231c2eeda.png new file mode 100644 index 000000000000..31ea809a81df Binary files /dev/null and b/services/site/src/asset/og-studio/home-br-b231c2eeda.png differ diff --git a/services/site/src/asset/og-studio/home-da-45a88d4705.png b/services/site/src/asset/og-studio/home-da-45a88d4705.png new file mode 100644 index 000000000000..88f0e96d9bf1 Binary files /dev/null and b/services/site/src/asset/og-studio/home-da-45a88d4705.png differ diff --git a/services/site/src/asset/og-studio/home-de-7ab9fafeea.png b/services/site/src/asset/og-studio/home-de-7ab9fafeea.png new file mode 100644 index 000000000000..2f338b3e272e Binary files /dev/null and b/services/site/src/asset/og-studio/home-de-7ab9fafeea.png differ diff --git a/services/site/src/asset/og-studio/home-ec8331a4d6.mp4 b/services/site/src/asset/og-studio/home-ec8331a4d6.mp4 new file mode 100644 index 000000000000..2641151ff153 Binary files /dev/null and b/services/site/src/asset/og-studio/home-ec8331a4d6.mp4 differ diff --git a/services/site/src/asset/og-studio/home-es-f7763c256a.png b/services/site/src/asset/og-studio/home-es-f7763c256a.png new file mode 100644 index 000000000000..31a9288606db Binary files /dev/null and b/services/site/src/asset/og-studio/home-es-f7763c256a.png differ diff --git a/services/site/src/asset/og-studio/home-fr-8d71106c36.png b/services/site/src/asset/og-studio/home-fr-8d71106c36.png new file mode 100644 index 000000000000..1abf455a7683 Binary files /dev/null and b/services/site/src/asset/og-studio/home-fr-8d71106c36.png differ diff --git a/services/site/src/asset/og-studio/home-it-5cf7f568ab.png b/services/site/src/asset/og-studio/home-it-5cf7f568ab.png new file mode 100644 index 000000000000..93cb669766eb Binary files /dev/null and b/services/site/src/asset/og-studio/home-it-5cf7f568ab.png differ diff --git a/services/site/src/asset/og-studio/home-ja-587ab3cf42.png b/services/site/src/asset/og-studio/home-ja-587ab3cf42.png new file mode 100644 index 000000000000..551056683df2 Binary files /dev/null and b/services/site/src/asset/og-studio/home-ja-587ab3cf42.png differ diff --git a/services/site/src/asset/og-studio/home-ko-e2105c0c9d.png b/services/site/src/asset/og-studio/home-ko-e2105c0c9d.png new file mode 100644 index 000000000000..b21646ab8bf4 Binary files /dev/null and b/services/site/src/asset/og-studio/home-ko-e2105c0c9d.png differ diff --git a/services/site/src/asset/og-studio/home-no-f022750ce7.png b/services/site/src/asset/og-studio/home-no-f022750ce7.png new file mode 100644 index 000000000000..da6932acd531 Binary files /dev/null and b/services/site/src/asset/og-studio/home-no-f022750ce7.png differ diff --git a/services/site/src/asset/og-studio/home-pl-f087f2cf92.png b/services/site/src/asset/og-studio/home-pl-f087f2cf92.png new file mode 100644 index 000000000000..e0a4c8ac1c87 Binary files /dev/null and b/services/site/src/asset/og-studio/home-pl-f087f2cf92.png differ diff --git a/services/site/src/asset/og-studio/home-ru-a3b2207018.png b/services/site/src/asset/og-studio/home-ru-a3b2207018.png new file mode 100644 index 000000000000..8f93da8a2ed4 Binary files /dev/null and b/services/site/src/asset/og-studio/home-ru-a3b2207018.png differ diff --git a/services/site/src/asset/og-studio/home-th-6c04ac9833.png b/services/site/src/asset/og-studio/home-th-6c04ac9833.png new file mode 100644 index 000000000000..a8606b3f5650 Binary files /dev/null and b/services/site/src/asset/og-studio/home-th-6c04ac9833.png differ diff --git a/services/site/src/asset/og-studio/home-tr-47a272dcfc.png b/services/site/src/asset/og-studio/home-tr-47a272dcfc.png new file mode 100644 index 000000000000..db337873d7cf Binary files /dev/null and b/services/site/src/asset/og-studio/home-tr-47a272dcfc.png differ diff --git a/services/site/src/asset/og-studio/home-uk-7dbf00d466.png b/services/site/src/asset/og-studio/home-uk-7dbf00d466.png new file mode 100644 index 000000000000..2312654bd880 Binary files /dev/null and b/services/site/src/asset/og-studio/home-uk-7dbf00d466.png differ diff --git a/services/site/src/asset/og-studio/home-zh-df85e49f5d.png b/services/site/src/asset/og-studio/home-zh-df85e49f5d.png new file mode 100644 index 000000000000..9ff067d62e45 Binary files /dev/null and b/services/site/src/asset/og-studio/home-zh-df85e49f5d.png differ diff --git a/services/site/src/asset/og-studio/home-zht-98c8b3339f.png b/services/site/src/asset/og-studio/home-zht-98c8b3339f.png new file mode 100644 index 000000000000..5914c2218ebc Binary files /dev/null and b/services/site/src/asset/og-studio/home-zht-98c8b3339f.png differ diff --git a/services/site/src/asset/og-studio/legal-84723c3950.png b/services/site/src/asset/og-studio/legal-84723c3950.png new file mode 100644 index 000000000000..de9a6cb67d1d Binary files /dev/null and b/services/site/src/asset/og-studio/legal-84723c3950.png differ diff --git a/services/site/src/asset/og-studio/legal-b1b3009c7e.mp4 b/services/site/src/asset/og-studio/legal-b1b3009c7e.mp4 new file mode 100644 index 000000000000..93705b34fdc8 Binary files /dev/null and b/services/site/src/asset/og-studio/legal-b1b3009c7e.mp4 differ diff --git a/services/site/src/asset/og-studio/manifest.json b/services/site/src/asset/og-studio/manifest.json new file mode 100644 index 000000000000..f4b2505a441a --- /dev/null +++ b/services/site/src/asset/og-studio/manifest.json @@ -0,0 +1,703 @@ +{ + "version": 1, + "generator": "og-studio", + "width": 1200, + "height": 630, + "cards": { + "/": { + "image": "home-98637499f6.png", + "alt": "OpenCode link card: “The open source coding agent”.", + "video": "home-ec8331a4d6.mp4", + "locales": { + "de": { + "image": "home-de-7ab9fafeea.png", + "alt": "OpenCode link card: “Der Open-Source-Coding-Agent”." + }, + "ko": { + "image": "home-ko-e2105c0c9d.png", + "alt": "OpenCode link card: “오픈 소스 코딩 에이전트”." + }, + "es": { + "image": "home-es-f7763c256a.png", + "alt": "OpenCode link card: “El agente de programación de código abierto”." + }, + "zh": { + "image": "home-zh-df85e49f5d.png", + "alt": "OpenCode link card: “开源编程代理”." + }, + "zht": { + "image": "home-zht-98c8b3339f.png", + "alt": "OpenCode link card: “開源編碼代理”." + }, + "fr": { + "image": "home-fr-8d71106c36.png", + "alt": "OpenCode link card: “L'agent de code open source”." + }, + "it": { + "image": "home-it-5cf7f568ab.png", + "alt": "OpenCode link card: “L'agente di coding open source”." + }, + "da": { + "image": "home-da-45a88d4705.png", + "alt": "OpenCode link card: “Open source-kodningsagenten”." + }, + "pl": { + "image": "home-pl-f087f2cf92.png", + "alt": "OpenCode link card: “Agent do kodowania open source”." + }, + "ja": { + "image": "home-ja-587ab3cf42.png", + "alt": "OpenCode link card: “オープンソースのコーディング​エージェント”." + }, + "ru": { + "image": "home-ru-a3b2207018.png", + "alt": "OpenCode link card: “Агент с открытым кодом для программирования”." + }, + "uk": { + "image": "home-uk-7dbf00d466.png", + "alt": "OpenCode link card: “Відкритий агент для кодування”." + }, + "no": { + "image": "home-no-f022750ce7.png", + "alt": "OpenCode link card: “Kodeagenten med åpen kildekode”." + }, + "ar": { + "image": "home-ar-b920e0ad64.png", + "alt": "OpenCode link card: “وكيل برمجة مفتوح المصدر”." + }, + "br": { + "image": "home-br-b231c2eeda.png", + "alt": "OpenCode link card: “O agente de codificação de código aberto”." + }, + "th": { + "image": "home-th-6c04ac9833.png", + "alt": "OpenCode link card: “เอเจนต์เขียนโค้ดแบบโอเพนซอร์ส”." + }, + "tr": { + "image": "home-tr-47a272dcfc.png", + "alt": "OpenCode link card: “Açık kaynaklı kodlama ajanı”." + } + } + }, + "/brand": { + "image": "brand-4e61968505.png", + "alt": "OpenCode link card: “Brand guidelines” and “Resources and assets to help you work with the OpenCode brand.”.", + "video": "brand-9a58b5052b.mp4", + "locales": { + "zh": { + "image": "brand-zh-dcc60b4c81.png", + "alt": "OpenCode link card: “品牌指南” and “帮助您使用 OpenCode 品牌的资源和资产。”." + }, + "zht": { + "image": "brand-zht-2bef6d786d.png", + "alt": "OpenCode link card: “品牌指南” and “協助你使用 OpenCode 品牌的資源與素材。”." + }, + "ko": { + "image": "brand-ko-ab18888ef9.png", + "alt": "OpenCode link card: “브랜드 가이드라인” and “OpenCode 브랜드를 활용하는 데 도움이 되는 리소스와 자산입니다.”." + }, + "de": { + "image": "brand-de-f966de83b2.png", + "alt": "OpenCode link card: “Markenrichtlinien” and “Die Markenrichtlinien von OpenCode”." + }, + "es": { + "image": "brand-es-bc04e49810.png", + "alt": "OpenCode link card: “Guías de marca” and “Recursos y activos para ayudarte a trabajar con la marca OpenCode.”." + }, + "fr": { + "image": "brand-fr-7e3c48cfb2.png", + "alt": "OpenCode link card: “Guide de marque” and “La charte de marque OpenCode”." + }, + "it": { + "image": "brand-it-58abfa8752.png", + "alt": "OpenCode link card: “Linee guida del brand” and “Risorse e asset per aiutarti a lavorare con il brand OpenCode.”." + }, + "da": { + "image": "brand-da-7742cbb96d.png", + "alt": "OpenCode link card: “Brandretningslinjer” and “OpenCodes brandretningslinjer”." + }, + "ja": { + "image": "brand-ja-9cdf8661f4.png", + "alt": "OpenCode link card: “ブランドガイドライン” and “OpenCodeブランドを扱うためのリソースと素材です。”." + }, + "pl": { + "image": "brand-pl-4c3904aa47.png", + "alt": "OpenCode link card: “Wytyczne marki” and “Zasoby i aktywa, które pomogą Ci pracować z marką OpenCode.”." + }, + "ru": { + "image": "brand-ru-3bbf5faf69.png", + "alt": "OpenCode link card: “Гайдлайны бренда” and “Ресурсы и активы, которые помогут вам работать с брендом OpenCode.”." + }, + "uk": { + "image": "brand-uk-7ee60e7ba3.png", + "alt": "OpenCode link card: “Рекомендації щодо бренду” and “Ресурси та матеріали для роботи з брендом OpenCode.”." + }, + "ar": { + "image": "brand-ar-e187032cd0.png", + "alt": "OpenCode link card: “إرشادات العلامة التجارية” and “موارد وأصول لمساعدتك في العمل مع العلامة التجارية لـ OpenCode.”." + }, + "br": { + "image": "brand-br-3681ae5782.png", + "alt": "OpenCode link card: “Diretrizes da marca” and “Recursos e ativos para ajudá-lo a trabalhar com a marca OpenCode.”." + }, + "no": { + "image": "brand-no-e44bce8749.png", + "alt": "OpenCode link card: “Retningslinjer for merkevare” and “Ressurser og assets som hjelper deg å jobbe med OpenCode-brandet.”." + }, + "th": { + "image": "brand-th-6a64e2e42f.png", + "alt": "OpenCode link card: “แนวทางการใช้แบรนด์” and “ทรัพยากรและแอสเซทเพื่อช่วยให้คุณใช้งานแบรนด์ OpenCode”." + }, + "tr": { + "image": "brand-tr-b939ad63b2.png", + "alt": "OpenCode link card: “Marka kılavuzu” and “OpenCode marka kuralları”." + } + } + }, + "/changelog": { + "image": "changelog-a404a3db2b.png", + "alt": "OpenCode link card: “Changelog” and “New updates and improvements to OpenCode”.", + "video": "changelog-9e6442949d.mp4" + }, + "/desktop": { + "image": "desktop-f98d91d47d.png", + "alt": "OpenCode link card: “Desktop” and “Run several agents at once, each session in its own tab”.", + "video": "desktop-fd77cfeffc.mp4", + "locales": { + "zh": { + "image": "desktop-zh-50547b564e.png", + "alt": "OpenCode link card: “Desktop” and “同时运行多个代理,每个会话都有独立的标签页”." + }, + "de": { + "image": "desktop-de-9406d53da1.png", + "alt": "OpenCode link card: “Desktop” and “Lass mehrere Agents gleichzeitig laufen, jede Session in einem eigenen Tab”." + }, + "ko": { + "image": "desktop-ko-0f5228f239.png", + "alt": "OpenCode link card: “Desktop” and “여러 에이전트를 동시에 실행하고, 세션마다 각자의 탭을 쓰세요”." + }, + "zht": { + "image": "desktop-zht-0932f029e6.png", + "alt": "OpenCode link card: “Desktop” and “同時執行多個代理,每個工作階段都有獨立的分頁”." + }, + "es": { + "image": "desktop-es-8f9bc611c9.png", + "alt": "OpenCode link card: “Desktop” and “Ejecuta varios agentes a la vez, cada sesión en su propia pestaña”." + }, + "fr": { + "image": "desktop-fr-77596c43cb.png", + "alt": "OpenCode link card: “Desktop” and “Lancez plusieurs agents à la fois, chaque session dans son propre onglet”." + }, + "it": { + "image": "desktop-it-44bbc6db83.png", + "alt": "OpenCode link card: “Desktop” and “Esegui più agenti insieme, ogni sessione nella sua scheda”." + }, + "da": { + "image": "desktop-da-d09be44295.png", + "alt": "OpenCode link card: “Desktop” and “Kør flere agenter på én gang, hver session i sin egen fane”." + }, + "ja": { + "image": "desktop-ja-7f55912afd.png", + "alt": "OpenCode link card: “Desktop” and “複数のエージェントを同時に実行し、セッションごとに専用のタブで管理できます”." + }, + "pl": { + "image": "desktop-pl-90701984e4.png", + "alt": "OpenCode link card: “Desktop” and “Uruchamiaj kilku agentów naraz, każdą sesję w osobnej karcie”." + }, + "ru": { + "image": "desktop-ru-247a36b9b4.png", + "alt": "OpenCode link card: “Desktop” and “Запускайте несколько агентов сразу, каждую сессию в своей вкладке”." + }, + "uk": { + "image": "desktop-uk-90ba41627f.png", + "alt": "OpenCode link card: “Desktop” and “Запускайте кілька агентів одночасно, кожну сесію у своїй вкладці”." + }, + "ar": { + "image": "desktop-ar-388d8017c4.png", + "alt": "OpenCode link card: “Desktop” and “شغّل عدة وكلاء معًا، وكل جلسة في علامة تبويب خاصة”." + }, + "no": { + "image": "desktop-no-cc2b6484dc.png", + "alt": "OpenCode link card: “Desktop” and “Kjør flere agenter samtidig, hver sesjon i sin egen fane”." + }, + "tr": { + "image": "desktop-tr-82d26cda7b.png", + "alt": "OpenCode link card: “Desktop” and “Birden fazla ajanı aynı anda, her oturumu kendi sekmesinde çalıştırın”." + }, + "br": { + "image": "desktop-br-fb89a41fdd.png", + "alt": "OpenCode link card: “Desktop” and “Rode vários agentes ao mesmo tempo, cada sessão na sua própria aba”." + }, + "th": { + "image": "desktop-th-f7dd62da10.png", + "alt": "OpenCode link card: “Desktop” and “รันเอเจนต์ OpenCode พร้อมกันได้มากเท่าที่ต้องการ ดูทุกการเปลี่ยนแปลงในเบราว์เซอร์ข้างๆ และทำต่อได้บนทุกอุปกรณ์ สำหรับ macOS, Windows และ Linux”." + } + } + }, + "/docs": { + "image": "docs-e416d17432.png", + "alt": "OpenCode link card: “Docs” and “Guides and reference for every part of OpenCode, in one place”.", + "video": "docs-40387ee840.mp4" + }, + "/font": { + "image": "font-f345dc0fb4.png", + "alt": "OpenCode link card: “OpenCode Font” and “A typeface cut from the OpenCode wordmark, with infinite combinations”.", + "video": "font-f768cba1a4.mp4" + }, + "/legal": { + "image": "legal-84723c3950.png", + "alt": "OpenCode link card: “Legal” and “The legal documents for the OpenCode website and hosted services.”.", + "video": "legal-b1b3009c7e.mp4" + }, + "/mini": { + "image": "mini-8925d0cfb2.png", + "alt": "OpenCode link card: “Mini” and “A minimal terminal interface”.", + "video": "mini-40b065f853.mp4", + "locales": { + "zht": { + "image": "mini-zht-92ff4b74c6.png", + "alt": "OpenCode link card: “Mini” and “OpenCode 的極簡終端機介面”." + }, + "zh": { + "image": "mini-zh-d93b26b0f0.png", + "alt": "OpenCode link card: “Mini” and “OpenCode 的极简终端界面”." + }, + "de": { + "image": "mini-de-7bb140b7ce.png", + "alt": "OpenCode link card: “Mini” and “Ein minimales Terminal-Interface für OpenCode”." + }, + "es": { + "image": "mini-es-7fe7879e9f.png", + "alt": "OpenCode link card: “Mini” and “Una interfaz de terminal mínima para OpenCode”." + }, + "ko": { + "image": "mini-ko-bcfac56878.png", + "alt": "OpenCode link card: “Mini” and “OpenCode를 위한 미니멀한 터미널 인터페이스입니다”." + }, + "fr": { + "image": "mini-fr-28ba3b5c4b.png", + "alt": "OpenCode link card: “Mini” and “Une interface terminal minimale pour OpenCode”." + }, + "it": { + "image": "mini-it-9337e405db.png", + "alt": "OpenCode link card: “Mini” and “Un'interfaccia da terminale minimale per OpenCode”." + }, + "ja": { + "image": "mini-ja-4b20294714.png", + "alt": "OpenCode link card: “Mini” and “OpenCodeのための最小限のターミナルインターフェース”." + }, + "pl": { + "image": "mini-pl-9c504fe22b.png", + "alt": "OpenCode link card: “Mini” and “Minimalny interfejs terminalowy dla OpenCode”." + }, + "da": { + "image": "mini-da-4276a15528.png", + "alt": "OpenCode link card: “Mini” and “En minimal terminalbrugerflade til OpenCode”." + }, + "ru": { + "image": "mini-ru-cf5249f206.png", + "alt": "OpenCode link card: “Mini” and “Минимальный терминальный интерфейс для OpenCode”." + }, + "uk": { + "image": "mini-uk-b1a0ce7ada.png", + "alt": "OpenCode link card: “Mini” and “Мінімальний термінальний інтерфейс для OpenCode”." + }, + "ar": { + "image": "mini-ar-d7e44843fb.png", + "alt": "OpenCode link card: “Mini” and “واجهة طرفية بسيطة لـ OpenCode”." + }, + "no": { + "image": "mini-no-77c2f54b76.png", + "alt": "OpenCode link card: “Mini” and “Et minimalt terminalgrensesnitt for OpenCode”." + }, + "th": { + "image": "mini-th-44230e6a55.png", + "alt": "OpenCode link card: “Mini” and “Mini รัน OpenCode ในอินเทอร์เฟซเทอร์มินัลแบบมินิมอล คำตอบจะพิมพ์ลงใน scrollback ของเทอร์มินัลเอง และมีเพียงพรอมต์กับบรรทัดสถานะอยู่ด้านล่าง”." + }, + "br": { + "image": "mini-br-e02808797d.png", + "alt": "OpenCode link card: “Mini” and “Uma interface de terminal mínima para o OpenCode”." + }, + "tr": { + "image": "mini-tr-902044f5b1.png", + "alt": "OpenCode link card: “Mini” and “OpenCode için minimal bir terminal arayüzü”." + } + } + }, + "/mobile": { + "image": "mobile-5d6ef9e218.png", + "alt": "OpenCode link card: “Mobile” and “Start and steer sessions from your phone, wherever you are”.", + "video": "mobile-3078f52f0b.mp4", + "locales": { + "zh": { + "image": "mobile-zh-efbc913b2d.png", + "alt": "OpenCode link card: “Mobile” and “无论身在何处,都能在手机上启动并引导会话”." + }, + "zht": { + "image": "mobile-zht-40ad44a7bc.png", + "alt": "OpenCode link card: “Mobile” and “無論身在何處,都能在手機上啟動並引導工作階段”." + }, + "ko": { + "image": "mobile-ko-8006f2c551.png", + "alt": "OpenCode link card: “Mobile” and “어디서든 휴대폰에서 세션을 시작하고 조작하세요”." + }, + "it": { + "image": "mobile-it-9b75162215.png", + "alt": "OpenCode link card: “Mobile” and “Avvia e guida sessioni dal telefono, ovunque tu sia”." + }, + "es": { + "image": "mobile-es-150c9bc64d.png", + "alt": "OpenCode link card: “Mobile” and “Inicia y dirige sesiones desde el móvil, estés donde estés”." + }, + "de": { + "image": "mobile-de-4333c9568f.png", + "alt": "OpenCode link card: “Mobile” and “Starte und steuere Sessions vom Smartphone aus, wo immer du bist”." + }, + "fr": { + "image": "mobile-fr-426ec197eb.png", + "alt": "OpenCode link card: “Mobile” and “Lancez et pilotez des sessions OpenCode depuis votre téléphone”." + }, + "da": { + "image": "mobile-da-95ed46fc52.png", + "alt": "OpenCode link card: “Mobile” and “Start og styr sessioner fra din telefon, hvor du end er”." + }, + "ru": { + "image": "mobile-ru-a427270345.png", + "alt": "OpenCode link card: “Mobile” and “Запускайте сеансы и управляйте ими с телефона, где бы вы ни были”." + }, + "ja": { + "image": "mobile-ja-3b2f77645f.png", + "alt": "OpenCode link card: “Mobile” and “どこにいても、スマートフォンからセッションを開始して操作できます”." + }, + "pl": { + "image": "mobile-pl-fb5b61ee83.png", + "alt": "OpenCode link card: “Mobile” and “Uruchamiaj i prowadź sesje z telefonu, gdziekolwiek jesteś”." + }, + "ar": { + "image": "mobile-ar-375257861f.png", + "alt": "OpenCode link card: “Mobile” and “ابدأ الجلسات وقُدها من هاتفك أينما كنت”." + }, + "uk": { + "image": "mobile-uk-d51e745314.png", + "alt": "OpenCode link card: “Mobile” and “Запускайте сеанси й керуйте ними з телефона, де б ви не були”." + }, + "no": { + "image": "mobile-no-ee27348e57.png", + "alt": "OpenCode link card: “Mobile” and “Start og styr økter fra telefonen, uansett hvor du er”." + }, + "br": { + "image": "mobile-br-d4805263f3.png", + "alt": "OpenCode link card: “Mobile” and “Inicie e conduza sessões pelo celular, onde você estiver”." + }, + "tr": { + "image": "mobile-tr-502c613f4d.png", + "alt": "OpenCode link card: “Mobile” and “Nerede olursanız olun oturumları telefonunuzdan başlatın ve yönetin”." + }, + "th": { + "image": "mobile-th-a689afa7d7.png", + "alt": "OpenCode link card: “Mobile” and “เริ่มและควบคุมเซสชัน OpenCode จากโทรศัพท์ของคุณ พูดคุยกับเอเจนต์ขณะที่มันทำงานบนคอมพิวเตอร์ของคุณ”." + } + } + }, + "/press": { + "image": "press-7302275958.png", + "alt": "OpenCode link card: “Press” and “Facts, brand assets and contacts for writing about OpenCode and Anomaly.”.", + "video": "press-e1999bf877.mp4", + "locales": { + "zh": { + "image": "press-zh-64d48f25c7.png", + "alt": "OpenCode link card: “媒体” and “报道 OpenCode 和 Anomaly 所需的信息、品牌资产和联系方式。”." + }, + "zht": { + "image": "press-zht-9fd76be7af.png", + "alt": "OpenCode link card: “媒體” and “報導 OpenCode 和 Anomaly 所需的資訊、品牌素材和聯絡方式。”." + }, + "de": { + "image": "press-de-6ea8ec3da2.png", + "alt": "OpenCode link card: “Presse” and “Fakten, Marken-Assets und Kontakte für Berichte über OpenCode und Anomaly.”." + }, + "ko": { + "image": "press-ko-14af5ff28a.png", + "alt": "OpenCode link card: “언론” and “OpenCode와 Anomaly에 관해 쓰기 위한 정보, 브랜드 자산, 연락처.”." + }, + "fr": { + "image": "press-fr-335aaac834.png", + "alt": "OpenCode link card: “Presse” and “Informations, ressources de marque et contacts pour écrire sur OpenCode et Anomaly.”." + }, + "es": { + "image": "press-es-6c94963b28.png", + "alt": "OpenCode link card: “Prensa” and “Datos, recursos de marca y contactos para escribir sobre OpenCode y Anomaly.”." + }, + "da": { + "image": "press-da-f8576fc87c.png", + "alt": "OpenCode link card: “Presse” and “Fakta, brand-assets og kontakter til at skrive om OpenCode og Anomaly.”." + }, + "it": { + "image": "press-it-36a3ec1056.png", + "alt": "OpenCode link card: “Stampa” and “Dati, asset del brand e contatti per scrivere di OpenCode e Anomaly.”." + }, + "pl": { + "image": "press-pl-ecd83e566f.png", + "alt": "OpenCode link card: “Prasa” and “Fakty, zasoby marki i kontakty dla piszących o OpenCode i Anomaly.”." + }, + "ja": { + "image": "press-ja-1da88d40a5.png", + "alt": "OpenCode link card: “プレス” and “OpenCodeとAnomalyについて書くための情報、ブランド素材、連絡先。”." + }, + "ru": { + "image": "press-ru-21f9d654c1.png", + "alt": "OpenCode link card: “Пресса” and “Факты, материалы бренда и контакты для тех, кто пишет об OpenCode и Anomaly.”." + }, + "uk": { + "image": "press-uk-c641acaaa2.png", + "alt": "OpenCode link card: “Преса” and “Факти, матеріали бренду й контакти для тих, хто пише про OpenCode і Anomaly.”." + }, + "no": { + "image": "press-no-dd4dd40f57.png", + "alt": "OpenCode link card: “Presse” and “Fakta, merkevareressurser og kontakter for deg som skriver om OpenCode og Anomaly.”." + }, + "ar": { + "image": "press-ar-c93124613c.png", + "alt": "OpenCode link card: “الصحافة” and “حقائق وأصول العلامة وجهات اتصال للكتابة عن OpenCode وAnomaly.”." + }, + "br": { + "image": "press-br-3a70f6deeb.png", + "alt": "OpenCode link card: “Imprensa” and “Dados, ativos da marca e contatos para escrever sobre o OpenCode e a Anomaly.”." + }, + "th": { + "image": "press-th-d380e8e759.png", + "alt": "OpenCode link card: “สื่อมวลชน” and “ข้อมูล แอสเซทแบรนด์ และช่องทางติดต่อสำหรับการเขียนถึง OpenCode และ Anomaly”." + }, + "tr": { + "image": "press-tr-f35943d004.png", + "alt": "OpenCode link card: “Basın” and “OpenCode basın kiti”." + } + } + }, + "/product": { + "image": "product-7c9ecd8a39.png", + "alt": "OpenCode link card: “Product” and “One agent, every surface”.", + "video": "product-c179b05171.mp4", + "locales": { + "zh": { + "image": "product-zh-8d8bc557f4.png", + "alt": "OpenCode link card: “产品” and “一个代理,覆盖所有界面”." + }, + "ko": { + "image": "product-ko-4fc8d9b1d6.png", + "alt": "OpenCode link card: “제품” and “하나의 에이전트, 모든 화면”." + }, + "zht": { + "image": "product-zht-06d0c500b3.png", + "alt": "OpenCode link card: “產品” and “一個代理,涵蓋所有介面”." + }, + "de": { + "image": "product-de-827b14e025.png", + "alt": "OpenCode link card: “Produkt” and “Ein Agent auf jeder Oberfläche”." + }, + "fr": { + "image": "product-fr-0bebf29659.png", + "alt": "OpenCode link card: “Produit” and “Un agent, partout”." + }, + "it": { + "image": "product-it-8ae226ef99.png", + "alt": "OpenCode link card: “Prodotto” and “Un agente, ovunque”." + }, + "es": { + "image": "product-es-340a74e4fc.png", + "alt": "OpenCode link card: “Producto” and “Un agente, en todas partes”." + }, + "da": { + "image": "product-da-f4f586f9dc.png", + "alt": "OpenCode link card: “Produkt” and “Én agent, alle flader”." + }, + "ja": { + "image": "product-ja-2d38926c36.png", + "alt": "OpenCode link card: “製品” and “1つのエージェントを、あらゆる場所で”." + }, + "pl": { + "image": "product-pl-4e06d0a0b6.png", + "alt": "OpenCode link card: “Produkt” and “Jeden agent, wszędzie”." + }, + "ru": { + "image": "product-ru-411e66278c.png", + "alt": "OpenCode link card: “Продукт” and “Один агент на всех устройствах”." + }, + "uk": { + "image": "product-uk-7878aeafca.png", + "alt": "OpenCode link card: “Продукт” and “Один агент на всіх пристроях”." + }, + "ar": { + "image": "product-ar-4e66be4d55.png", + "alt": "OpenCode link card: “المنتج” and “وكيل واحد على كل الشاشات”." + }, + "no": { + "image": "product-no-4a2be52aea.png", + "alt": "OpenCode link card: “Produkt” and “Én agent, alle flater”." + }, + "br": { + "image": "product-br-f77fb5a75d.png", + "alt": "OpenCode link card: “Produto” and “Um agente, em todo lugar”." + }, + "tr": { + "image": "product-tr-1e9442de6c.png", + "alt": "OpenCode link card: “Ürün” and “Tek ajan, her yerde”." + }, + "th": { + "image": "product-th-cc450951de.png", + "alt": "OpenCode link card: “ผลิตภัณฑ์” and “เอเจนต์เดียว ทุกพื้นที่ทำงาน เริ่มเซสชันบนเดสก์ท็อป สั่งงานจากโทรศัพท์ ทำต่อในเทอร์มินัล หรือควบคุมจากโค้ดของคุณเอง”." + } + } + }, + "/sdk": { + "image": "sdk-d26c8f84d9.png", + "alt": "OpenCode link card: “SDK” and “Drive OpenCode from your own scripts, CI jobs and tools”.", + "video": "sdk-d329895728.mp4", + "locales": { + "zht": { + "image": "sdk-zht-07c6538f46.png", + "alt": "OpenCode link card: “SDK” and “從你自己的腳本、CI 工作和工具驅動 OpenCode”." + }, + "zh": { + "image": "sdk-zh-f935310ad9.png", + "alt": "OpenCode link card: “SDK” and “在您自己的脚本、CI 任务和工具中驱动 OpenCode”." + }, + "fr": { + "image": "sdk-fr-48c4aaf56f.png", + "alt": "OpenCode link card: “SDK” and “Pilotez OpenCode depuis vos scripts, jobs CI et outils”." + }, + "ko": { + "image": "sdk-ko-5fc0543a2c.png", + "alt": "OpenCode link card: “SDK” and “직접 만든 스크립트, CI 작업, 도구에서 OpenCode를 제어하세요”." + }, + "de": { + "image": "sdk-de-745692762f.png", + "alt": "OpenCode link card: “SDK” and “Steuere OpenCode aus deinen eigenen Skripten, CI-Jobs und Tools”." + }, + "da": { + "image": "sdk-da-67d88441cf.png", + "alt": "OpenCode link card: “SDK” and “Styr OpenCode fra dine egne scripts, CI-jobs og værktøjer”." + }, + "es": { + "image": "sdk-es-aa394787f8.png", + "alt": "OpenCode link card: “SDK” and “Controla OpenCode desde tus scripts, jobs de CI y herramientas”." + }, + "it": { + "image": "sdk-it-ac41238478.png", + "alt": "OpenCode link card: “SDK” and “Controlla OpenCode dai tuoi script, job di CI e strumenti”." + }, + "ja": { + "image": "sdk-ja-4edf56821b.png", + "alt": "OpenCode link card: “SDK” and “自分のスクリプト、CIジョブ、ツールからOpenCodeを操作できます”." + }, + "ru": { + "image": "sdk-ru-0a0de7fe5a.png", + "alt": "OpenCode link card: “SDK” and “Управляйте OpenCode из своих скриптов, CI-задач и инструментов”." + }, + "uk": { + "image": "sdk-uk-872475bacf.png", + "alt": "OpenCode link card: “SDK” and “Керуйте OpenCode зі своїх скриптів, CI-завдань та інструментів”." + }, + "pl": { + "image": "sdk-pl-9b00e23de8.png", + "alt": "OpenCode link card: “SDK” and “Steruj OpenCode z własnych skryptów, zadań CI i narzędzi”." + }, + "ar": { + "image": "sdk-ar-9ce21753f1.png", + "alt": "OpenCode link card: “SDK” and “تحكّم في OpenCode من سكربتاتك ومهام CI وأدواتك”." + }, + "br": { + "image": "sdk-br-3015a30545.png", + "alt": "OpenCode link card: “SDK” and “Controle o OpenCode pelos seus scripts, jobs de CI e ferramentas”." + }, + "th": { + "image": "sdk-th-782715452d.png", + "alt": "OpenCode link card: “SDK” and “ควบคุม OpenCode จากสคริปต์ งาน CI และเครื่องมือของคุณเอง ไคลเอนต์ TypeScript แบบมีชนิดข้อมูลสร้างเซสชัน ส่งพรอมต์ และสตรีมทุกอีเวนต์ทันทีที่เกิดขึ้น”." + }, + "no": { + "image": "sdk-no-58988ed6f2.png", + "alt": "OpenCode link card: “SDK” and “Styr OpenCode fra dine egne skript, CI-jobber og verktøy”." + }, + "tr": { + "image": "sdk-tr-a39e14c52c.png", + "alt": "OpenCode link card: “SDK” and “OpenCode'u kendi betiklerinizden, CI işlerinizden ve araçlarınızdan yönetin”." + } + } + }, + "/terminal": { + "image": "terminal-d2dc426c65.png", + "alt": "OpenCode link card: “Terminal” and “A fast terminal UI that works in any shell, editor or remote server”.", + "video": "terminal-b25f4ce5fe.mp4", + "locales": { + "zh": { + "image": "terminal-zh-d87bec3290.png", + "alt": "OpenCode link card: “Terminal” and “快速的终端界面,可在任意 shell、编辑器或远程服务器中使用”." + }, + "zht": { + "image": "terminal-zht-2c14139b59.png", + "alt": "OpenCode link card: “Terminal” and “快速的終端機介面,可在任何 shell、編輯器或遠端伺服器中使用”." + }, + "ko": { + "image": "terminal-ko-6b4b1c271a.png", + "alt": "OpenCode link card: “Terminal” and “어떤 셸, 에디터, 원격 서버에서도 동작하는 빠른 터미널 UI입니다”." + }, + "de": { + "image": "terminal-de-d2b06871e4.png", + "alt": "OpenCode link card: “Terminal” and “Ein schnelles Terminal-UI für jede Shell, jeden Editor und jeden Remote-Server”." + }, + "es": { + "image": "terminal-es-b616a76d0a.png", + "alt": "OpenCode link card: “Terminal” and “Una interfaz de terminal rápida que funciona en cualquier shell, editor o servidor remoto”." + }, + "it": { + "image": "terminal-it-c824bb8ef6.png", + "alt": "OpenCode link card: “Terminal” and “Un'interfaccia da terminale veloce che funziona in qualsiasi shell, editor o server remoto”." + }, + "fr": { + "image": "terminal-fr-6d7406601e.png", + "alt": "OpenCode link card: “Terminal” and “Une interface terminal rapide qui fonctionne dans tout shell, éditeur ou serveur distant”." + }, + "da": { + "image": "terminal-da-c497b08041.png", + "alt": "OpenCode link card: “Terminal” and “En hurtig terminalbrugerflade, der virker i enhver shell, editor eller fjernserver”." + }, + "pl": { + "image": "terminal-pl-d09d1d4401.png", + "alt": "OpenCode link card: “Terminal” and “Szybki interfejs terminalowy, który działa w każdej powłoce, edytorze i na zdalnym serwerze”." + }, + "ja": { + "image": "terminal-ja-583888e16d.png", + "alt": "OpenCode link card: “Terminal” and “どのシェル、エディタ、リモートサーバーでも動く高速なターミナルUI”." + }, + "ru": { + "image": "terminal-ru-d7933e2f12.png", + "alt": "OpenCode link card: “Terminal” and “Быстрый терминальный интерфейс для любой оболочки, редактора или удалённого сервера”." + }, + "uk": { + "image": "terminal-uk-179b0bf424.png", + "alt": "OpenCode link card: “Terminal” and “Швидкий термінальний інтерфейс для будь-якої оболонки, редактора чи віддаленого сервера”." + }, + "ar": { + "image": "terminal-ar-9f1b9a236a.png", + "alt": "OpenCode link card: “Terminal” and “واجهة طرفية سريعة تعمل في أي صدفة أو محرر أو خادم بعيد”." + }, + "no": { + "image": "terminal-no-6c9eef767f.png", + "alt": "OpenCode link card: “Terminal” and “Et raskt terminalgrensesnitt som fungerer i alle skall, editorer og eksterne servere”." + }, + "br": { + "image": "terminal-br-51344a44be.png", + "alt": "OpenCode link card: “Terminal” and “Uma interface de terminal rápida que funciona em qualquer shell, editor ou servidor remoto”." + }, + "th": { + "image": "terminal-th-3e10fd190f.png", + "alt": "OpenCode link card: “Terminal” and “UI เทอร์มินัลที่รวดเร็วของ OpenCode ใช้ได้ในทุกเชลล์ อีดิเตอร์ หรือเซิร์ฟเวอร์ระยะไกล บอกสิ่งที่ต้องการ ดูการแก้ไขแต่ละครั้งเป็น diff และอนุมัติคำสั่ง”." + }, + "tr": { + "image": "terminal-tr-f04135ed01.png", + "alt": "OpenCode link card: “Terminal” and “Her kabukta, editörde ya da uzak sunucuda çalışan hızlı bir terminal arayüzü”." + } + } + } + } +} diff --git a/services/site/src/asset/og-studio/mini-40b065f853.mp4 b/services/site/src/asset/og-studio/mini-40b065f853.mp4 new file mode 100644 index 000000000000..2b551926c540 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-40b065f853.mp4 differ diff --git a/services/site/src/asset/og-studio/mini-8925d0cfb2.png b/services/site/src/asset/og-studio/mini-8925d0cfb2.png new file mode 100644 index 000000000000..9494d45362ca Binary files /dev/null and b/services/site/src/asset/og-studio/mini-8925d0cfb2.png differ diff --git a/services/site/src/asset/og-studio/mini-ar-d7e44843fb.png b/services/site/src/asset/og-studio/mini-ar-d7e44843fb.png new file mode 100644 index 000000000000..0fb2f67454e4 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-ar-d7e44843fb.png differ diff --git a/services/site/src/asset/og-studio/mini-br-e02808797d.png b/services/site/src/asset/og-studio/mini-br-e02808797d.png new file mode 100644 index 000000000000..2b53d4ab0d9e Binary files /dev/null and b/services/site/src/asset/og-studio/mini-br-e02808797d.png differ diff --git a/services/site/src/asset/og-studio/mini-da-4276a15528.png b/services/site/src/asset/og-studio/mini-da-4276a15528.png new file mode 100644 index 000000000000..f0da9c31c8aa Binary files /dev/null and b/services/site/src/asset/og-studio/mini-da-4276a15528.png differ diff --git a/services/site/src/asset/og-studio/mini-de-7bb140b7ce.png b/services/site/src/asset/og-studio/mini-de-7bb140b7ce.png new file mode 100644 index 000000000000..e9a06dfa55d7 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-de-7bb140b7ce.png differ diff --git a/services/site/src/asset/og-studio/mini-es-7fe7879e9f.png b/services/site/src/asset/og-studio/mini-es-7fe7879e9f.png new file mode 100644 index 000000000000..62562ef55775 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-es-7fe7879e9f.png differ diff --git a/services/site/src/asset/og-studio/mini-fr-28ba3b5c4b.png b/services/site/src/asset/og-studio/mini-fr-28ba3b5c4b.png new file mode 100644 index 000000000000..3ca80907b71f Binary files /dev/null and b/services/site/src/asset/og-studio/mini-fr-28ba3b5c4b.png differ diff --git a/services/site/src/asset/og-studio/mini-it-9337e405db.png b/services/site/src/asset/og-studio/mini-it-9337e405db.png new file mode 100644 index 000000000000..91b2428cb598 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-it-9337e405db.png differ diff --git a/services/site/src/asset/og-studio/mini-ja-4b20294714.png b/services/site/src/asset/og-studio/mini-ja-4b20294714.png new file mode 100644 index 000000000000..18632062121d Binary files /dev/null and b/services/site/src/asset/og-studio/mini-ja-4b20294714.png differ diff --git a/services/site/src/asset/og-studio/mini-ko-bcfac56878.png b/services/site/src/asset/og-studio/mini-ko-bcfac56878.png new file mode 100644 index 000000000000..ff04afa2a421 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-ko-bcfac56878.png differ diff --git a/services/site/src/asset/og-studio/mini-no-77c2f54b76.png b/services/site/src/asset/og-studio/mini-no-77c2f54b76.png new file mode 100644 index 000000000000..fae4ec51170f Binary files /dev/null and b/services/site/src/asset/og-studio/mini-no-77c2f54b76.png differ diff --git a/services/site/src/asset/og-studio/mini-pl-9c504fe22b.png b/services/site/src/asset/og-studio/mini-pl-9c504fe22b.png new file mode 100644 index 000000000000..c0c543ac56b9 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-pl-9c504fe22b.png differ diff --git a/services/site/src/asset/og-studio/mini-ru-cf5249f206.png b/services/site/src/asset/og-studio/mini-ru-cf5249f206.png new file mode 100644 index 000000000000..8aa4744f6421 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-ru-cf5249f206.png differ diff --git a/services/site/src/asset/og-studio/mini-th-44230e6a55.png b/services/site/src/asset/og-studio/mini-th-44230e6a55.png new file mode 100644 index 000000000000..ed3ae9ab580c Binary files /dev/null and b/services/site/src/asset/og-studio/mini-th-44230e6a55.png differ diff --git a/services/site/src/asset/og-studio/mini-tr-902044f5b1.png b/services/site/src/asset/og-studio/mini-tr-902044f5b1.png new file mode 100644 index 000000000000..ce9d3ecfd384 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-tr-902044f5b1.png differ diff --git a/services/site/src/asset/og-studio/mini-uk-b1a0ce7ada.png b/services/site/src/asset/og-studio/mini-uk-b1a0ce7ada.png new file mode 100644 index 000000000000..b490966c62d0 Binary files /dev/null and b/services/site/src/asset/og-studio/mini-uk-b1a0ce7ada.png differ diff --git a/services/site/src/asset/og-studio/mini-zh-d93b26b0f0.png b/services/site/src/asset/og-studio/mini-zh-d93b26b0f0.png new file mode 100644 index 000000000000..da41bd08a64b Binary files /dev/null and b/services/site/src/asset/og-studio/mini-zh-d93b26b0f0.png differ diff --git a/services/site/src/asset/og-studio/mini-zht-92ff4b74c6.png b/services/site/src/asset/og-studio/mini-zht-92ff4b74c6.png new file mode 100644 index 000000000000..00495f69d79c Binary files /dev/null and b/services/site/src/asset/og-studio/mini-zht-92ff4b74c6.png differ diff --git a/services/site/src/asset/og-studio/mobile-3078f52f0b.mp4 b/services/site/src/asset/og-studio/mobile-3078f52f0b.mp4 new file mode 100644 index 000000000000..3688af75bf25 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-3078f52f0b.mp4 differ diff --git a/services/site/src/asset/og-studio/mobile-5d6ef9e218.png b/services/site/src/asset/og-studio/mobile-5d6ef9e218.png new file mode 100644 index 000000000000..66447b16d59c Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-5d6ef9e218.png differ diff --git a/services/site/src/asset/og-studio/mobile-ar-375257861f.png b/services/site/src/asset/og-studio/mobile-ar-375257861f.png new file mode 100644 index 000000000000..470c2738cbe4 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-ar-375257861f.png differ diff --git a/services/site/src/asset/og-studio/mobile-br-d4805263f3.png b/services/site/src/asset/og-studio/mobile-br-d4805263f3.png new file mode 100644 index 000000000000..726d815fe360 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-br-d4805263f3.png differ diff --git a/services/site/src/asset/og-studio/mobile-da-95ed46fc52.png b/services/site/src/asset/og-studio/mobile-da-95ed46fc52.png new file mode 100644 index 000000000000..1bc61fdd4961 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-da-95ed46fc52.png differ diff --git a/services/site/src/asset/og-studio/mobile-de-4333c9568f.png b/services/site/src/asset/og-studio/mobile-de-4333c9568f.png new file mode 100644 index 000000000000..934e91118aa8 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-de-4333c9568f.png differ diff --git a/services/site/src/asset/og-studio/mobile-es-150c9bc64d.png b/services/site/src/asset/og-studio/mobile-es-150c9bc64d.png new file mode 100644 index 000000000000..d43e05f3f6c7 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-es-150c9bc64d.png differ diff --git a/services/site/src/asset/og-studio/mobile-fr-426ec197eb.png b/services/site/src/asset/og-studio/mobile-fr-426ec197eb.png new file mode 100644 index 000000000000..bbd028263757 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-fr-426ec197eb.png differ diff --git a/services/site/src/asset/og-studio/mobile-it-9b75162215.png b/services/site/src/asset/og-studio/mobile-it-9b75162215.png new file mode 100644 index 000000000000..85b0d4b8d3ce Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-it-9b75162215.png differ diff --git a/services/site/src/asset/og-studio/mobile-ja-3b2f77645f.png b/services/site/src/asset/og-studio/mobile-ja-3b2f77645f.png new file mode 100644 index 000000000000..480553f3518b Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-ja-3b2f77645f.png differ diff --git a/services/site/src/asset/og-studio/mobile-ko-8006f2c551.png b/services/site/src/asset/og-studio/mobile-ko-8006f2c551.png new file mode 100644 index 000000000000..61f3f18cf558 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-ko-8006f2c551.png differ diff --git a/services/site/src/asset/og-studio/mobile-no-ee27348e57.png b/services/site/src/asset/og-studio/mobile-no-ee27348e57.png new file mode 100644 index 000000000000..22484fc9fc76 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-no-ee27348e57.png differ diff --git a/services/site/src/asset/og-studio/mobile-pl-fb5b61ee83.png b/services/site/src/asset/og-studio/mobile-pl-fb5b61ee83.png new file mode 100644 index 000000000000..57d2de06a97f Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-pl-fb5b61ee83.png differ diff --git a/services/site/src/asset/og-studio/mobile-ru-a427270345.png b/services/site/src/asset/og-studio/mobile-ru-a427270345.png new file mode 100644 index 000000000000..aa4222111533 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-ru-a427270345.png differ diff --git a/services/site/src/asset/og-studio/mobile-th-a689afa7d7.png b/services/site/src/asset/og-studio/mobile-th-a689afa7d7.png new file mode 100644 index 000000000000..0dedc36decf4 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-th-a689afa7d7.png differ diff --git a/services/site/src/asset/og-studio/mobile-tr-502c613f4d.png b/services/site/src/asset/og-studio/mobile-tr-502c613f4d.png new file mode 100644 index 000000000000..e790ae7fa1aa Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-tr-502c613f4d.png differ diff --git a/services/site/src/asset/og-studio/mobile-uk-d51e745314.png b/services/site/src/asset/og-studio/mobile-uk-d51e745314.png new file mode 100644 index 000000000000..0461e8dbbaaf Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-uk-d51e745314.png differ diff --git a/services/site/src/asset/og-studio/mobile-zh-efbc913b2d.png b/services/site/src/asset/og-studio/mobile-zh-efbc913b2d.png new file mode 100644 index 000000000000..1e1054f58ea3 Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-zh-efbc913b2d.png differ diff --git a/services/site/src/asset/og-studio/mobile-zht-40ad44a7bc.png b/services/site/src/asset/og-studio/mobile-zht-40ad44a7bc.png new file mode 100644 index 000000000000..2338890f72aa Binary files /dev/null and b/services/site/src/asset/og-studio/mobile-zht-40ad44a7bc.png differ diff --git a/services/site/src/asset/og-studio/press-7302275958.png b/services/site/src/asset/og-studio/press-7302275958.png new file mode 100644 index 000000000000..21fc96ff0fc2 Binary files /dev/null and b/services/site/src/asset/og-studio/press-7302275958.png differ diff --git a/services/site/src/asset/og-studio/press-ar-c93124613c.png b/services/site/src/asset/og-studio/press-ar-c93124613c.png new file mode 100644 index 000000000000..17f62fe0e4ec Binary files /dev/null and b/services/site/src/asset/og-studio/press-ar-c93124613c.png differ diff --git a/services/site/src/asset/og-studio/press-br-3a70f6deeb.png b/services/site/src/asset/og-studio/press-br-3a70f6deeb.png new file mode 100644 index 000000000000..f8abfe4cc177 Binary files /dev/null and b/services/site/src/asset/og-studio/press-br-3a70f6deeb.png differ diff --git a/services/site/src/asset/og-studio/press-da-f8576fc87c.png b/services/site/src/asset/og-studio/press-da-f8576fc87c.png new file mode 100644 index 000000000000..d16f630efa53 Binary files /dev/null and b/services/site/src/asset/og-studio/press-da-f8576fc87c.png differ diff --git a/services/site/src/asset/og-studio/press-de-6ea8ec3da2.png b/services/site/src/asset/og-studio/press-de-6ea8ec3da2.png new file mode 100644 index 000000000000..b48e79687729 Binary files /dev/null and b/services/site/src/asset/og-studio/press-de-6ea8ec3da2.png differ diff --git a/services/site/src/asset/og-studio/press-e1999bf877.mp4 b/services/site/src/asset/og-studio/press-e1999bf877.mp4 new file mode 100644 index 000000000000..511064a0abb1 Binary files /dev/null and b/services/site/src/asset/og-studio/press-e1999bf877.mp4 differ diff --git a/services/site/src/asset/og-studio/press-es-6c94963b28.png b/services/site/src/asset/og-studio/press-es-6c94963b28.png new file mode 100644 index 000000000000..4d84f85541e7 Binary files /dev/null and b/services/site/src/asset/og-studio/press-es-6c94963b28.png differ diff --git a/services/site/src/asset/og-studio/press-fr-335aaac834.png b/services/site/src/asset/og-studio/press-fr-335aaac834.png new file mode 100644 index 000000000000..d7018eee7864 Binary files /dev/null and b/services/site/src/asset/og-studio/press-fr-335aaac834.png differ diff --git a/services/site/src/asset/og-studio/press-it-36a3ec1056.png b/services/site/src/asset/og-studio/press-it-36a3ec1056.png new file mode 100644 index 000000000000..9636165abcee Binary files /dev/null and b/services/site/src/asset/og-studio/press-it-36a3ec1056.png differ diff --git a/services/site/src/asset/og-studio/press-ja-1da88d40a5.png b/services/site/src/asset/og-studio/press-ja-1da88d40a5.png new file mode 100644 index 000000000000..00c280dd5c66 Binary files /dev/null and b/services/site/src/asset/og-studio/press-ja-1da88d40a5.png differ diff --git a/services/site/src/asset/og-studio/press-ko-14af5ff28a.png b/services/site/src/asset/og-studio/press-ko-14af5ff28a.png new file mode 100644 index 000000000000..9cd042f7c561 Binary files /dev/null and b/services/site/src/asset/og-studio/press-ko-14af5ff28a.png differ diff --git a/services/site/src/asset/og-studio/press-no-dd4dd40f57.png b/services/site/src/asset/og-studio/press-no-dd4dd40f57.png new file mode 100644 index 000000000000..6e83e24e0648 Binary files /dev/null and b/services/site/src/asset/og-studio/press-no-dd4dd40f57.png differ diff --git a/services/site/src/asset/og-studio/press-pl-ecd83e566f.png b/services/site/src/asset/og-studio/press-pl-ecd83e566f.png new file mode 100644 index 000000000000..c4ad2064adf3 Binary files /dev/null and b/services/site/src/asset/og-studio/press-pl-ecd83e566f.png differ diff --git a/services/site/src/asset/og-studio/press-ru-21f9d654c1.png b/services/site/src/asset/og-studio/press-ru-21f9d654c1.png new file mode 100644 index 000000000000..b02eb79c9510 Binary files /dev/null and b/services/site/src/asset/og-studio/press-ru-21f9d654c1.png differ diff --git a/services/site/src/asset/og-studio/press-th-d380e8e759.png b/services/site/src/asset/og-studio/press-th-d380e8e759.png new file mode 100644 index 000000000000..7568b85d9115 Binary files /dev/null and b/services/site/src/asset/og-studio/press-th-d380e8e759.png differ diff --git a/services/site/src/asset/og-studio/press-tr-f35943d004.png b/services/site/src/asset/og-studio/press-tr-f35943d004.png new file mode 100644 index 000000000000..f107253970be Binary files /dev/null and b/services/site/src/asset/og-studio/press-tr-f35943d004.png differ diff --git a/services/site/src/asset/og-studio/press-uk-c641acaaa2.png b/services/site/src/asset/og-studio/press-uk-c641acaaa2.png new file mode 100644 index 000000000000..b187e6f3a2e1 Binary files /dev/null and b/services/site/src/asset/og-studio/press-uk-c641acaaa2.png differ diff --git a/services/site/src/asset/og-studio/press-zh-64d48f25c7.png b/services/site/src/asset/og-studio/press-zh-64d48f25c7.png new file mode 100644 index 000000000000..3ecc46630fca Binary files /dev/null and b/services/site/src/asset/og-studio/press-zh-64d48f25c7.png differ diff --git a/services/site/src/asset/og-studio/press-zht-9fd76be7af.png b/services/site/src/asset/og-studio/press-zht-9fd76be7af.png new file mode 100644 index 000000000000..32c8a27214e7 Binary files /dev/null and b/services/site/src/asset/og-studio/press-zht-9fd76be7af.png differ diff --git a/services/site/src/asset/og-studio/product-7c9ecd8a39.png b/services/site/src/asset/og-studio/product-7c9ecd8a39.png new file mode 100644 index 000000000000..7ee04d417340 Binary files /dev/null and b/services/site/src/asset/og-studio/product-7c9ecd8a39.png differ diff --git a/services/site/src/asset/og-studio/product-ar-4e66be4d55.png b/services/site/src/asset/og-studio/product-ar-4e66be4d55.png new file mode 100644 index 000000000000..a77f7bac46b7 Binary files /dev/null and b/services/site/src/asset/og-studio/product-ar-4e66be4d55.png differ diff --git a/services/site/src/asset/og-studio/product-br-f77fb5a75d.png b/services/site/src/asset/og-studio/product-br-f77fb5a75d.png new file mode 100644 index 000000000000..2918b62675c3 Binary files /dev/null and b/services/site/src/asset/og-studio/product-br-f77fb5a75d.png differ diff --git a/services/site/src/asset/og-studio/product-c179b05171.mp4 b/services/site/src/asset/og-studio/product-c179b05171.mp4 new file mode 100644 index 000000000000..a38751a8f837 Binary files /dev/null and b/services/site/src/asset/og-studio/product-c179b05171.mp4 differ diff --git a/services/site/src/asset/og-studio/product-da-f4f586f9dc.png b/services/site/src/asset/og-studio/product-da-f4f586f9dc.png new file mode 100644 index 000000000000..414e824801b3 Binary files /dev/null and b/services/site/src/asset/og-studio/product-da-f4f586f9dc.png differ diff --git a/services/site/src/asset/og-studio/product-de-827b14e025.png b/services/site/src/asset/og-studio/product-de-827b14e025.png new file mode 100644 index 000000000000..9223aac95581 Binary files /dev/null and b/services/site/src/asset/og-studio/product-de-827b14e025.png differ diff --git a/services/site/src/asset/og-studio/product-es-340a74e4fc.png b/services/site/src/asset/og-studio/product-es-340a74e4fc.png new file mode 100644 index 000000000000..bd25d7c627dd Binary files /dev/null and b/services/site/src/asset/og-studio/product-es-340a74e4fc.png differ diff --git a/services/site/src/asset/og-studio/product-fr-0bebf29659.png b/services/site/src/asset/og-studio/product-fr-0bebf29659.png new file mode 100644 index 000000000000..1ce8cce9e415 Binary files /dev/null and b/services/site/src/asset/og-studio/product-fr-0bebf29659.png differ diff --git a/services/site/src/asset/og-studio/product-it-8ae226ef99.png b/services/site/src/asset/og-studio/product-it-8ae226ef99.png new file mode 100644 index 000000000000..10e4988e6ec7 Binary files /dev/null and b/services/site/src/asset/og-studio/product-it-8ae226ef99.png differ diff --git a/services/site/src/asset/og-studio/product-ja-2d38926c36.png b/services/site/src/asset/og-studio/product-ja-2d38926c36.png new file mode 100644 index 000000000000..981d8a849fa5 Binary files /dev/null and b/services/site/src/asset/og-studio/product-ja-2d38926c36.png differ diff --git a/services/site/src/asset/og-studio/product-ko-4fc8d9b1d6.png b/services/site/src/asset/og-studio/product-ko-4fc8d9b1d6.png new file mode 100644 index 000000000000..0a72570062e0 Binary files /dev/null and b/services/site/src/asset/og-studio/product-ko-4fc8d9b1d6.png differ diff --git a/services/site/src/asset/og-studio/product-no-4a2be52aea.png b/services/site/src/asset/og-studio/product-no-4a2be52aea.png new file mode 100644 index 000000000000..45db6d7a1ef0 Binary files /dev/null and b/services/site/src/asset/og-studio/product-no-4a2be52aea.png differ diff --git a/services/site/src/asset/og-studio/product-pl-4e06d0a0b6.png b/services/site/src/asset/og-studio/product-pl-4e06d0a0b6.png new file mode 100644 index 000000000000..b19418de1c7b Binary files /dev/null and b/services/site/src/asset/og-studio/product-pl-4e06d0a0b6.png differ diff --git a/services/site/src/asset/og-studio/product-ru-411e66278c.png b/services/site/src/asset/og-studio/product-ru-411e66278c.png new file mode 100644 index 000000000000..6aeef23a657d Binary files /dev/null and b/services/site/src/asset/og-studio/product-ru-411e66278c.png differ diff --git a/services/site/src/asset/og-studio/product-th-cc450951de.png b/services/site/src/asset/og-studio/product-th-cc450951de.png new file mode 100644 index 000000000000..22d923ca8870 Binary files /dev/null and b/services/site/src/asset/og-studio/product-th-cc450951de.png differ diff --git a/services/site/src/asset/og-studio/product-tr-1e9442de6c.png b/services/site/src/asset/og-studio/product-tr-1e9442de6c.png new file mode 100644 index 000000000000..03bbfe50fd23 Binary files /dev/null and b/services/site/src/asset/og-studio/product-tr-1e9442de6c.png differ diff --git a/services/site/src/asset/og-studio/product-uk-7878aeafca.png b/services/site/src/asset/og-studio/product-uk-7878aeafca.png new file mode 100644 index 000000000000..801646d767c4 Binary files /dev/null and b/services/site/src/asset/og-studio/product-uk-7878aeafca.png differ diff --git a/services/site/src/asset/og-studio/product-zh-8d8bc557f4.png b/services/site/src/asset/og-studio/product-zh-8d8bc557f4.png new file mode 100644 index 000000000000..77df6e37364b Binary files /dev/null and b/services/site/src/asset/og-studio/product-zh-8d8bc557f4.png differ diff --git a/services/site/src/asset/og-studio/product-zht-06d0c500b3.png b/services/site/src/asset/og-studio/product-zht-06d0c500b3.png new file mode 100644 index 000000000000..40e25b646bfd Binary files /dev/null and b/services/site/src/asset/og-studio/product-zht-06d0c500b3.png differ diff --git a/services/site/src/asset/og-studio/sdk-ar-9ce21753f1.png b/services/site/src/asset/og-studio/sdk-ar-9ce21753f1.png new file mode 100644 index 000000000000..986159f2f1f4 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-ar-9ce21753f1.png differ diff --git a/services/site/src/asset/og-studio/sdk-br-3015a30545.png b/services/site/src/asset/og-studio/sdk-br-3015a30545.png new file mode 100644 index 000000000000..f3fc86befaf6 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-br-3015a30545.png differ diff --git a/services/site/src/asset/og-studio/sdk-d26c8f84d9.png b/services/site/src/asset/og-studio/sdk-d26c8f84d9.png new file mode 100644 index 000000000000..bd7a26f25a35 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-d26c8f84d9.png differ diff --git a/services/site/src/asset/og-studio/sdk-d329895728.mp4 b/services/site/src/asset/og-studio/sdk-d329895728.mp4 new file mode 100644 index 000000000000..40484ae6e5ac Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-d329895728.mp4 differ diff --git a/services/site/src/asset/og-studio/sdk-da-67d88441cf.png b/services/site/src/asset/og-studio/sdk-da-67d88441cf.png new file mode 100644 index 000000000000..de5e8d3c7d5a Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-da-67d88441cf.png differ diff --git a/services/site/src/asset/og-studio/sdk-de-745692762f.png b/services/site/src/asset/og-studio/sdk-de-745692762f.png new file mode 100644 index 000000000000..c01d3ae19065 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-de-745692762f.png differ diff --git a/services/site/src/asset/og-studio/sdk-es-aa394787f8.png b/services/site/src/asset/og-studio/sdk-es-aa394787f8.png new file mode 100644 index 000000000000..df97948d3880 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-es-aa394787f8.png differ diff --git a/services/site/src/asset/og-studio/sdk-fr-48c4aaf56f.png b/services/site/src/asset/og-studio/sdk-fr-48c4aaf56f.png new file mode 100644 index 000000000000..9b17f2a8d6f7 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-fr-48c4aaf56f.png differ diff --git a/services/site/src/asset/og-studio/sdk-it-ac41238478.png b/services/site/src/asset/og-studio/sdk-it-ac41238478.png new file mode 100644 index 000000000000..8e5d530f63c1 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-it-ac41238478.png differ diff --git a/services/site/src/asset/og-studio/sdk-ja-4edf56821b.png b/services/site/src/asset/og-studio/sdk-ja-4edf56821b.png new file mode 100644 index 000000000000..f47611d96342 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-ja-4edf56821b.png differ diff --git a/services/site/src/asset/og-studio/sdk-ko-5fc0543a2c.png b/services/site/src/asset/og-studio/sdk-ko-5fc0543a2c.png new file mode 100644 index 000000000000..ee087589b70c Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-ko-5fc0543a2c.png differ diff --git a/services/site/src/asset/og-studio/sdk-no-58988ed6f2.png b/services/site/src/asset/og-studio/sdk-no-58988ed6f2.png new file mode 100644 index 000000000000..08d78c418fc1 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-no-58988ed6f2.png differ diff --git a/services/site/src/asset/og-studio/sdk-pl-9b00e23de8.png b/services/site/src/asset/og-studio/sdk-pl-9b00e23de8.png new file mode 100644 index 000000000000..596626e9c8c8 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-pl-9b00e23de8.png differ diff --git a/services/site/src/asset/og-studio/sdk-ru-0a0de7fe5a.png b/services/site/src/asset/og-studio/sdk-ru-0a0de7fe5a.png new file mode 100644 index 000000000000..9f6012450735 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-ru-0a0de7fe5a.png differ diff --git a/services/site/src/asset/og-studio/sdk-th-782715452d.png b/services/site/src/asset/og-studio/sdk-th-782715452d.png new file mode 100644 index 000000000000..7e7b9f3546f9 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-th-782715452d.png differ diff --git a/services/site/src/asset/og-studio/sdk-tr-a39e14c52c.png b/services/site/src/asset/og-studio/sdk-tr-a39e14c52c.png new file mode 100644 index 000000000000..0c1fbd8bc797 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-tr-a39e14c52c.png differ diff --git a/services/site/src/asset/og-studio/sdk-uk-872475bacf.png b/services/site/src/asset/og-studio/sdk-uk-872475bacf.png new file mode 100644 index 000000000000..a390b5194989 Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-uk-872475bacf.png differ diff --git a/services/site/src/asset/og-studio/sdk-zh-f935310ad9.png b/services/site/src/asset/og-studio/sdk-zh-f935310ad9.png new file mode 100644 index 000000000000..99fe11b02b4a Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-zh-f935310ad9.png differ diff --git a/services/site/src/asset/og-studio/sdk-zht-07c6538f46.png b/services/site/src/asset/og-studio/sdk-zht-07c6538f46.png new file mode 100644 index 000000000000..40a47262318f Binary files /dev/null and b/services/site/src/asset/og-studio/sdk-zht-07c6538f46.png differ diff --git a/services/site/src/asset/og-studio/terminal-ar-9f1b9a236a.png b/services/site/src/asset/og-studio/terminal-ar-9f1b9a236a.png new file mode 100644 index 000000000000..a27c64c23641 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-ar-9f1b9a236a.png differ diff --git a/services/site/src/asset/og-studio/terminal-b25f4ce5fe.mp4 b/services/site/src/asset/og-studio/terminal-b25f4ce5fe.mp4 new file mode 100644 index 000000000000..322a855e956b Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-b25f4ce5fe.mp4 differ diff --git a/services/site/src/asset/og-studio/terminal-br-51344a44be.png b/services/site/src/asset/og-studio/terminal-br-51344a44be.png new file mode 100644 index 000000000000..71d614919b51 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-br-51344a44be.png differ diff --git a/services/site/src/asset/og-studio/terminal-d2dc426c65.png b/services/site/src/asset/og-studio/terminal-d2dc426c65.png new file mode 100644 index 000000000000..f538179ab2e2 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-d2dc426c65.png differ diff --git a/services/site/src/asset/og-studio/terminal-da-c497b08041.png b/services/site/src/asset/og-studio/terminal-da-c497b08041.png new file mode 100644 index 000000000000..3555bd7dc33a Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-da-c497b08041.png differ diff --git a/services/site/src/asset/og-studio/terminal-de-d2b06871e4.png b/services/site/src/asset/og-studio/terminal-de-d2b06871e4.png new file mode 100644 index 000000000000..11be1f1c1695 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-de-d2b06871e4.png differ diff --git a/services/site/src/asset/og-studio/terminal-es-b616a76d0a.png b/services/site/src/asset/og-studio/terminal-es-b616a76d0a.png new file mode 100644 index 000000000000..cbb29bf3438a Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-es-b616a76d0a.png differ diff --git a/services/site/src/asset/og-studio/terminal-fr-6d7406601e.png b/services/site/src/asset/og-studio/terminal-fr-6d7406601e.png new file mode 100644 index 000000000000..2b5c6a94e06a Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-fr-6d7406601e.png differ diff --git a/services/site/src/asset/og-studio/terminal-it-c824bb8ef6.png b/services/site/src/asset/og-studio/terminal-it-c824bb8ef6.png new file mode 100644 index 000000000000..9582631ae9e6 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-it-c824bb8ef6.png differ diff --git a/services/site/src/asset/og-studio/terminal-ja-583888e16d.png b/services/site/src/asset/og-studio/terminal-ja-583888e16d.png new file mode 100644 index 000000000000..fa63988a1a05 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-ja-583888e16d.png differ diff --git a/services/site/src/asset/og-studio/terminal-ko-6b4b1c271a.png b/services/site/src/asset/og-studio/terminal-ko-6b4b1c271a.png new file mode 100644 index 000000000000..0492ac983256 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-ko-6b4b1c271a.png differ diff --git a/services/site/src/asset/og-studio/terminal-no-6c9eef767f.png b/services/site/src/asset/og-studio/terminal-no-6c9eef767f.png new file mode 100644 index 000000000000..bc7b06423bd5 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-no-6c9eef767f.png differ diff --git a/services/site/src/asset/og-studio/terminal-pl-d09d1d4401.png b/services/site/src/asset/og-studio/terminal-pl-d09d1d4401.png new file mode 100644 index 000000000000..8de755062183 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-pl-d09d1d4401.png differ diff --git a/services/site/src/asset/og-studio/terminal-ru-d7933e2f12.png b/services/site/src/asset/og-studio/terminal-ru-d7933e2f12.png new file mode 100644 index 000000000000..70332191a400 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-ru-d7933e2f12.png differ diff --git a/services/site/src/asset/og-studio/terminal-th-3e10fd190f.png b/services/site/src/asset/og-studio/terminal-th-3e10fd190f.png new file mode 100644 index 000000000000..74b98607c692 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-th-3e10fd190f.png differ diff --git a/services/site/src/asset/og-studio/terminal-tr-f04135ed01.png b/services/site/src/asset/og-studio/terminal-tr-f04135ed01.png new file mode 100644 index 000000000000..66114c4c85fe Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-tr-f04135ed01.png differ diff --git a/services/site/src/asset/og-studio/terminal-uk-179b0bf424.png b/services/site/src/asset/og-studio/terminal-uk-179b0bf424.png new file mode 100644 index 000000000000..3d84e4e8aebb Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-uk-179b0bf424.png differ diff --git a/services/site/src/asset/og-studio/terminal-zh-d87bec3290.png b/services/site/src/asset/og-studio/terminal-zh-d87bec3290.png new file mode 100644 index 000000000000..ce295b1c9590 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-zh-d87bec3290.png differ diff --git a/services/site/src/asset/og-studio/terminal-zht-2c14139b59.png b/services/site/src/asset/og-studio/terminal-zht-2c14139b59.png new file mode 100644 index 000000000000..d2df26fe3e69 Binary files /dev/null and b/services/site/src/asset/og-studio/terminal-zht-2c14139b59.png differ diff --git a/services/site/src/client/overlays/markdown.tsx b/services/site/src/client/overlays/markdown.tsx index 79e843a81df1..41426fe0859f 100644 --- a/services/site/src/client/overlays/markdown.tsx +++ b/services/site/src/client/overlays/markdown.tsx @@ -36,10 +36,18 @@ export async function toggle(on = !dispose, fromFooter = false) { if (text === undefined || dispose) return const file = href()!.split("/").pop()! const home = $('[data-slot="logo"]')?.getAttribute("href") ?? "/" - dispose = await mount( + // Its own host after the page: disposing a render empties its host, which must not take the page. + const host = document.createElement("div") + host.style.display = "contents" + $('[data-component="content"]')!.append(host) + const unmount = await mount( () => void toggle(false)} />, - $('[data-component="content"]')!, + host, ) + dispose = () => { + unmount() + host.remove() + } sessionStorage.setItem(markdownKey, "1") show(true, fromFooter) } diff --git a/services/site/src/component/share-meta.tsx b/services/site/src/component/share-meta.tsx index a5a75f81d7db..9942acce5e7a 100644 --- a/services/site/src/component/share-meta.tsx +++ b/services/site/src/component/share-meta.tsx @@ -1,4 +1,5 @@ import { Meta } from "@solidjs/meta" +import { Show } from "solid-js" import { config } from "~/config" import { useLanguage } from "~/context/language" import type { Locale } from "~/lib/language" @@ -11,6 +12,7 @@ import type { OgImage } from "~/lib/og" */ export function ShareMeta(props: { title: string; description: string; image: OgImage; englishOnly?: boolean }) { const language = useLanguage() + const image = () => (props.englishOnly ? undefined : props.image.locales?.[language.locale()]) ?? props.image return ( <> @@ -18,17 +20,29 @@ export function ShareMeta(props: { title: string; description: string; image: Og - + - + + {/* Only iMessage and Discord play og:video. Everyone else shows og:image. */} + + {(video) => ( + <> + + + + + + + )} + - - + + ) } diff --git a/services/site/src/component/site/css-variants.json b/services/site/src/component/site/css-variants.json index 337c5ebb19d5..b13fc092f1c1 100644 --- a/services/site/src/component/site/css-variants.json +++ b/services/site/src/component/site/css-variants.json @@ -16,7 +16,7 @@ "data-menu-align": "edge", "data-wide-align": null, "data-nav-numbers": "1", - "data-docs-nav": "split", + "data-docs-nav": "combined", "data-section-menu": "list", "data-docs-variants": "typography-4 lists-3 blockquote-2 callout-3 tabs-6 code-6 codeTitle-6 codeLines-6 codeDiff-6 terminal-6 fileTree-6 steps-2 cards-3 tables-5 badges-4 details-2 media-2 api-7 config-6 cli-6 pagination-4 breadcrumbs-3 search-4 switchers-2 editLink-4 feedback-5 inlineCode-6", "data-status-bars": "4", @@ -41,7 +41,7 @@ ["[data-component=\"hero-install\"][data-mode=\"row\"]", "data-style", "inline"], ["[data-component=\"hero\"][data-design~=\"hero\"]", "data-title-size", "fitted"], ["[data-component=\"page-title\"]", "data-sticky", null], - ["[data-component=\"docs-version-notice\"]", "data-variant", "frosted top"], + ["[data-component=\"docs-version-notice\"]", "data-variant", "inverted"], ["[data-component=\"products\"]", "data-tone", "color"], ["[data-component=\"badges\"]", "data-style", "sans"], ["[data-component=\"badges\"]", "data-layout", "tabs"], diff --git a/services/site/src/component/site/design-mode.tsx b/services/site/src/component/site/design-mode.tsx index 569c72918c9d..2dfc6af3752b 100644 --- a/services/site/src/component/site/design-mode.tsx +++ b/services/site/src/component/site/design-mode.tsx @@ -332,14 +332,6 @@ export const copyVariants = { ], }, // The products after the carousel's four, on /product and their own pages. - "card.ide.body": { - label: "IDE extensions card", - lines: 1, - options: [ - "OpenCode in VS Code and its forks, and in any ACP editor.", - "Run opencode in your editor's terminal and the extension installs itself.", - ], - }, "card.mini.body": { label: "Mini card", lines: 1, @@ -348,13 +340,6 @@ export const copyVariants = { "The agent in your terminal, with only a prompt and a status line.", ], }, - "product.ide.intro": { - label: "IDE extensions intro", - lines: 1, - options: [ - "OpenCode beside your code. Open it in a split terminal with Cmd+Esc, share your selection, and insert file references, in VS Code and its forks or any editor that speaks ACP.", - ], - }, "product.mini.intro": { label: "Mini intro", lines: 1, diff --git a/services/site/src/component/site/docs-lockup.css b/services/site/src/component/site/docs-lockup.css index be17a871631e..5e3d7d80720e 100644 --- a/services/site/src/component/site/docs-lockup.css +++ b/services/site/src/component/site/docs-lockup.css @@ -56,7 +56,8 @@ position: relative; display: inline-flex; align-items: center; - gap: 6px; + /* Label and chevron are one button, so the chevron sits close, as in the product navs. */ + gap: 4px; /* OpenTUI Mono's caps sit 0.325px below its line box's centre; this puts them on the logo's centre. */ padding: 0 6px 0.65px; @@ -439,22 +440,6 @@ } } -/* The section word also opens the OpenCode product menu on hover (packages/nav-menus), so hovered, open and pressed it - takes the one name fill every OpenCode nav shares (--nav-name-hover), never a darker one; the chevron keeps its own - states for the sections menu. */ -[data-site] [data-component="docs-lockup"] [data-slot="word"][data-nav-product] { - @media (hover: hover) and (pointer: fine) { - &:hover { - background: var(--nav-name-hover); - } - } - - &:active, - &[aria-expanded="true"] { - background: var(--nav-name-hover); - } -} - /* The logo before the lockup stays a plain link (no fill); its keyboard ring, drawn around the mark (site.css), is 2px like the segments'. */ [data-site] diff --git a/services/site/src/component/site/docs-lockup.tsx b/services/site/src/component/site/docs-lockup.tsx index 2b94a6c18afe..95768238f45b 100644 --- a/services/site/src/component/site/docs-lockup.tsx +++ b/services/site/src/component/site/docs-lockup.tsx @@ -40,8 +40,8 @@ type Item = { /** * Settings › Docs switcher › lockup: the docs section word after the site's logo, like the Data and * Console headers (public/nav-demo/switcher.js). One button opens a menu of the docs sections, where - * "Docs" has a submenu of versions. On an older version, "/ V1" after the word shows it and switches - * back. The menus are always in the page, hidden while closed, so pages that never hydrate (the docs) + * "Docs" has a submenu of versions. On the V1 docs the word reads "V1 docs" and the same menu marks V1 + * under "Docs". The menus are always in the page, hidden while closed, so pages that never hydrate (the docs) * can open them from a delegated listener (src/docs/client.ts). */ export function DocsLockup(props: { @@ -63,10 +63,18 @@ export function DocsLockup(props: { } }) { const i18n = useI18n() + // On the V1 docs the product name says so: "V1 docs", with the same chevron and menu as the latest docs. + const v1 = () => props.version?.current === "v1" const name = (label: string) => - label === "Docs" - ? docsSectionName(i18n, label) - : i18n.t("docs.lockup.sectionDocs", { section: docsSectionName(i18n, label) }) + v1() + ? i18n.t("docs.lockup.sectionDocs", { section: "V1" }) + : label === "Docs" + ? docsSectionName(i18n, label) + : i18n.t("docs.lockup.sectionDocs", { section: docsSectionName(i18n, label) }) + // The sections menu names each section's docs: "CLI docs", "API docs". The main docs are about OpenCode + // itself, so they're "OpenCode docs" rather than "Docs docs". + const menuName = (label: string) => + i18n.t("docs.lockup.sectionDocs", { section: label === "Docs" ? "OpenCode" : docsSectionName(i18n, label) }) // V1 is a version, not a section: "Docs" has a submenu of versions, V2 (these docs) and V1 (the old // docs site). The /docs demo can pass its own (?version= switches in place). const sections = () => docsProducts.filter((product) => product.label !== "V1") @@ -115,8 +123,8 @@ export function DocsLockup(props: { triggerLabel={(label) => i18n.t("docs.lockup.switchLabel", { name: name(label) })} items={sections().map((product) => ({ id: product.label, - label: docsSectionName(i18n, product.label), - ariaLabel: name(product.label), + label: menuName(product.label), + ariaLabel: menuName(product.label), href: props.href?.(product.label) ?? product.href, sub: product.label !== "Docs" @@ -132,30 +140,8 @@ export function DocsLockup(props: { }))} current={props.current} onSelect={props.onSelect} - split={{ label: i18n.t("docs.lockup.switch"), onSelect: props.onSelect }} + split={{ label: i18n.t("docs.lockup.switch"), onSelect: props.onSelect, href: v1() ? v1DocsUrl() : undefined }} /> - {/* Only the main docs have versions, and only an older one shows here. */} - - {(version) => ( - <> - - docsVersions.find((item) => item.id === id)!.label} - triggerLabel={(id) => - i18n.t("docs.version.switch", { version: docsVersions.find((item) => item.id === id)!.label }) - } - items={versionItems(version())} - current={version().current} - onSelect={(id) => version().onSelect(id as DocsVersion)} - /> - - )} - ) if (props.inline) return lockup() @@ -186,8 +172,11 @@ function Dropdown(props: { items: Item[] current: string onSelect?: (id: string) => void - /** Settings › Docs nav › split: the word links to the section's home; `label` names the chevron. */ - split?: { label: string; onSelect?: (id: string) => void } + /** + * Settings › Docs nav › split: the word links to the section's home (or `href`, the V1 docs' home); + * `label` names the chevron. + */ + split?: { label: string; onSelect?: (id: string) => void; href?: string } }) { const i18n = useI18n() const [open, setOpen] = createSignal(false) @@ -323,11 +312,7 @@ function Dropdown(props: { ) } + +/** The 16px chevron after the logo row's links, toward the reading direction (mirrored in RTL by CSS). */ +export function LinkChevron() { + return ( + + ) +} diff --git a/services/site/src/component/site/download-sections.tsx b/services/site/src/component/site/download-sections.tsx index 9e4b5035f61e..bffbafce0c8e 100644 --- a/services/site/src/component/site/download-sections.tsx +++ b/services/site/src/component/site/download-sections.tsx @@ -346,9 +346,6 @@ export function ProductDownload(props: { slug: PageSlug }) { - - - {(lead) =>

{lead()}

}
0}> diff --git a/services/site/src/component/site/product-data.ts b/services/site/src/component/site/product-data.ts index 629611fbf698..af5eafe353a4 100644 --- a/services/site/src/component/site/product-data.ts +++ b/services/site/src/component/site/product-data.ts @@ -28,7 +28,7 @@ export const sdkSnippet = [ export type ProductSlug = "desktop" | "terminal" | "mobile" | "sdk" /** The products after the carousel's four, with pages of their own and cards on /product. */ -export type MoreSlug = "ide" | "mini" +export type MoreSlug = "mini" /** Every product with a page. */ export type PageSlug = ProductSlug | MoreSlug @@ -72,17 +72,9 @@ export const products = [ /** * The products /product lists after the carousel's four, in this order. Copy follows each one's - * README and docs: IDE extensions is the VS Code extension (sdks/vscode, publisher sst-dev; docs - * /docs/ide) plus `opencode acp` for ACP editors (docs /cli/acp), and Mini is `opencode mini` - * (packages/tui/src/mini). + * README and docs: Mini is `opencode mini` (packages/tui/src/mini). */ export const moreProducts = [ - { - slug: "ide", - name: "IDE extensions", - body: "Open OpenCode in VS Code, Cursor and Windsurf, or in Zed and JetBrains IDEs through ACP.", - action: "Install", - }, { slug: "mini", name: "Mini", @@ -97,18 +89,15 @@ export const moreProducts = [ isNew?: boolean }[] -/** Every product with a page, including IDE extensions and Mini, which have pages (/ide, /mini) but aren't listed. */ +/** Every product with a page, including Mini, which has a page (/mini) but is not listed. */ export const allProductPages = [...products, ...moreProducts] /** * The products listed on /product, in the site's product order: its grid (the home carousel's four), - * the arrow keys on product pages, the footer, search and llms.txt. IDE extensions and Mini stay - * reachable by URL only. + * the arrow keys on product pages, the footer, search and llms.txt. Mini stays reachable by URL + * only. */ -export const productPages = allProductPages.filter((product) => product.slug !== "ide" && product.slug !== "mini") - -/** The ACP docs: Zed, JetBrains IDEs and other ACP editors run `opencode acp`. */ -export const acpDocs = docsUrl("/cli/acp/") +export const productPages = allProductPages.filter((product) => product.slug !== "mini") /** * Settings › Extensions card: OpenCode inside editors. The VS Code extension is sdks/vscode @@ -161,8 +150,8 @@ export const mobileStores = [ * The changelog areas (keys in `/changelog?area=`) for each product: its product page lists the * newest entries with notes there and links to the changelog with the same filter. Core notes (the * shared server and agent) are on the changelog for everyone and would fill every product's list. - * Mobile has no area in the release notes yet, so its page says it is new. IDE extensions and Mini - * have no areas, so their pages leave the changelog out. + * Mobile has no area in the release notes yet, so its page says it is new. Mini has no + * area, so its page leaves the changelog out. */ export const productAreas: Partial> = { desktop: ["desktop"], diff --git a/services/site/src/component/site/product-details.ts b/services/site/src/component/site/product-details.ts index 0ebd6f266579..a258b367b7c1 100644 --- a/services/site/src/component/site/product-details.ts +++ b/services/site/src/component/site/product-details.ts @@ -182,25 +182,6 @@ export const productDetails: Record< }, ], }, - ide: { - title: "OpenCode | Editor integrations for VS Code, Cursor and Zed", - description: - "Use OpenCode inside your editor, with the extension for VS Code, Cursor, Windsurf and VSCodium, and opencode acp for Zed, JetBrains IDEs and other ACP editors.", - operatingSystem: "macOS, Windows, Linux", - intro: - "Use OpenCode inside your editor. In VS Code, Cursor, Windsurf and VSCodium, run opencode in the integrated terminal and the extension installs itself. Zed, JetBrains IDEs and other editors that support the Agent Client Protocol run OpenCode with opencode acp.", - features: [ - { title: "Quick launch", body: "Cmd+Esc or Ctrl+Esc opens OpenCode in a split terminal." }, - { title: "New session", body: "Cmd+Shift+Esc or Ctrl+Shift+Esc starts another session." }, - { title: "Context", body: "Shares your current selection or tab with OpenCode." }, - { title: "File references", body: "Cmd+Option+K or Alt+Ctrl+K inserts @File#L37-42." }, - { title: "Installs itself", body: "Run opencode in the integrated terminal to add it." }, - { title: "ACP editors", body: "Zed, JetBrains IDEs, Avante.nvim and CodeCompanion.nvim." }, - { title: "Open VSX", body: "Also on Open VSX for Cursor, Windsurf and VSCodium." }, - { title: "Same agent", body: "The OpenCode you run in the terminal, beside your code." }, - ], - showcase: [], - }, mini: { title: "OpenCode | Mini, a minimal terminal interface for the agent", description: diff --git a/services/site/src/component/site/products.tsx b/services/site/src/component/site/products.tsx index 359c8d41b9f2..2972f8536d7e 100644 --- a/services/site/src/component/site/products.tsx +++ b/services/site/src/component/site/products.tsx @@ -1098,13 +1098,6 @@ export function ProductAction(props: { slug: PageSlug; split?: boolean; both?: b {productCopy().sdk.action} - {/* The VS Code extension; ACP editors are on its page. */} - - - {extensionCardCopy().action} - - -
+ {/* V1: the notice sits in the logo row, after the sidebar's label so it can start past a long one + (docs.css); phones show it as a bar on the screen's bottom edge. */} + + {(versions) => } + {/* Mobile layout: the Contents rail folded into a bar stuck under the section row from load. It names the section being read (client.ts swaps the label as you scroll) and keeps "Contents" in its accessible name. Hidden beside the rail on wide screens. */} @@ -213,9 +218,6 @@ export function DocsLayout(props: {
- - {(versions) => } -
& { + translate: 2px 0; + } + + [dir="rtl"] & { + scale: -1 1; + } + + [dir="rtl"] :is(a:hover, a:focus-visible) > & { + translate: -2px 0; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + } +} + +@media (min-width: 60.0625rem) { + /* A heading reached from Contents or a link lands below the logo row's band. */ + [data-site] [data-slot="frame"]:has(> [data-placement="header"]) [data-component="docs-article"] [id] { + scroll-margin-top: calc(var(--v1-notice-bottom) + 1.5rem); + } + + [data-site] [data-slot="frame"]:has(> [data-placement="header"]) > [data-component="content"]::before { + content: ""; + position: fixed; + /* Under the sidebar (2), whose logo strip covers its own nav, and over the article. */ + z-index: 1; + top: 0; + inset-inline: 0; + height: var(--v1-notice-bottom); + background: var(--bg); + pointer-events: none; + } +} + +[data-site] [data-component="sidebar"] [data-component="docs-lockup"] :is([data-slot="toggle"], [data-slot="trigger"]) { + anchor-name: --docs-lockup-toggle; +} + +[data-site] [data-slot="frame"] { + --v1-notice-height: 2rem; + /* The bar's bottom edge, where the logo row's band ends. */ + --v1-notice-bottom: calc( + var(--banner-offset, 0px) + var(--top) + var(--logo-height) / 2 + var(--v1-notice-height) / 2 + ); + + &:has(> [data-placement="header"]) [data-component="docs-article"] { + anchor-name: --docs-article; + } +} + +/* Phones: one line on the screen's bottom edge, "V1 docs" and the link, in the same dark, running + under the home indicator to the very edge. iOS Safari tints its bottom toolbar from what touches the + bottom edge, and the page behind the site (html) takes the dark too, so the bottom of the screen is + one dark area; the top still takes the top bar's page colour. The page ends above the bar, so the + footer stays reachable. Open menus and sheets sit over it. */ +@media (max-width: 60rem) { + html:has([data-component="docs-version-notice"][data-placement="header"]) { + background: light-dark(hsl(0, 0%, 8%), hsl(0, 0%, 13%)); + } + + [data-site]:has([data-component="docs-version-notice"][data-placement="header"]) { + padding-bottom: calc(3rem + env(safe-area-inset-bottom, 0px)); + } + + [data-site][data-page="docs"] [data-component="docs-version-notice"][data-placement="header"] { + position: fixed; + inset: auto 0 0; + margin: 0; + z-index: 5; + height: auto; + translate: none; + align-items: center; + padding: 0 calc(var(--edge) + env(safe-area-inset-right, 0px)) env(safe-area-inset-bottom, 0px) + calc(var(--edge) + env(safe-area-inset-left, 0px)); + box-shadow: inset 0 1px 0 light-dark(transparent, var(--border-strong)); + font-size: 14px; + + [data-slot="badge"], + [data-slot="sentence"] { + display: none; + } + + [data-slot="short"] { + display: block; + flex: none; + text-transform: uppercase; + } + + p { + justify-content: flex-end; + padding: 0; + } + + a { + height: 3rem; + text-decoration: none; + } + + a::after { + content: none; + } + } + + /* While a phone menu or sheet is open, the bar goes, so nothing sits half under it. */ + [data-site]:has( + [data-component="topbar"] [data-slot="menu"]:not([hidden]), + [data-component="section-nav"][data-open], + [data-component="contents-menu"][open], + [data-search-dialog]:not([hidden]) + ) + [data-component="docs-version-notice"][data-placement="header"] { + visibility: hidden; + } +} diff --git a/services/site/src/i18n/content/ar.ts b/services/site/src/i18n/content/ar.ts index 19fd03db21c4..babc385b48e9 100644 --- a/services/site/src/i18n/content/ar.ts +++ b/services/site/src/i18n/content/ar.ts @@ -10,11 +10,6 @@ export const content = { mobile: { name: "Mobile", body: "ابدأ الجلسات ووجّهها ووافق عليها من هاتفك أينما كنت.", action: "تنزيل" }, terminal: { name: "Terminal", body: "واجهة طرفية سريعة تعمل في أي صدفة أو محرر أو خادم بعيد.", action: "تثبيت" }, sdk: { body: "تحكّم في OpenCode من سكربتاتك ومهام CI وأدواتك.", action: "الوثائق" }, - ide: { - name: "إضافات IDE", - body: "افتح OpenCode في VS Code وCursor وWindsurf، أو في Zed وبيئات JetBrains عبر ACP.", - action: "تثبيت", - }, mini: { body: "واجهة طرفية بسيطة. تُطبع الردود في سجل التمرير، ويبقى سطر إدخال واحد في الأسفل.", action: "تثبيت" }, }, productDetails: { @@ -130,23 +125,6 @@ export const content = { "in-your-process": { title: "داخل عمليتك", body: "يشغّل OpenCode داخل عمليتك، بإعداداتك ونماذجك." }, }, }, - ide: { - title: "OpenCode | تكاملات المحررات لـ VS Code وCursor وZed", - description: - "استخدم OpenCode داخل محررك، مع الإضافة لـ VS Code وCursor وWindsurf وVSCodium، وopencode acp لـ Zed وبيئات JetBrains ومحررات ACP الأخرى.", - intro: - "استخدم OpenCode داخل محررك. في VS Code وCursor وWindsurf وVSCodium، شغّل opencode في الطرفية المدمجة فتثبّت الإضافة نفسها. أما Zed وبيئات JetBrains والمحررات الأخرى التي تدعم Agent Client Protocol فتشغّل OpenCode عبر opencode acp.", - features: { - "quick-launch": { title: "تشغيل سريع", body: "يفتح Cmd+Esc أو Ctrl+Esc OpenCode في طرفية مقسّمة." }, - "new-session": { title: "جلسة جديدة", body: "يبدأ Cmd+Shift+Esc أو Ctrl+Shift+Esc جلسة أخرى." }, - context: { title: "السياق", body: "يشارك تحديدك الحالي أو علامة التبويب مع OpenCode." }, - "file-references": { title: "مراجع الملفات", body: "يُدرج Cmd+Option+K أو Alt+Ctrl+K المرجع @File#L37-42." }, - "installs-itself": { title: "تثبّت نفسها", body: "شغّل opencode في الطرفية المدمجة لإضافتها." }, - "acp-editors": { title: "محررات ACP", body: "Zed وبيئات JetBrains وAvante.nvim وCodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "متاحة أيضًا على Open VSX لـ Cursor وWindsurf وVSCodium." }, - "same-agent": { title: "نفس الوكيل", body: "OpenCode الذي تشغّله في الطرفية، بجانب كودك." }, - }, - }, mini: { title: "OpenCode | Mini، واجهة طرفية بسيطة للوكيل", description: @@ -614,14 +592,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "سكربت" } } }, sdk: { more: { label: "اقرأ وثائق SDK" } }, - ide: { - lead: "شغّل opencode في الطرفية المدمجة في محررك فتثبّت الإضافة نفسها، أو ثبّتها بنفسك.", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "إعداد Zed وبيئات JetBrains ومحررات ACP الأخرى" }, - }, mini: { lead: "يأتي Mini مع OpenCode CLI. ثبّته بأي من هذه الطرق، ثم شغّل opencode mini.", commands: { curl: { name: "سكربت" } }, diff --git a/services/site/src/i18n/content/br.ts b/services/site/src/i18n/content/br.ts index b91a761f3101..ad6ad67c9fb8 100644 --- a/services/site/src/i18n/content/br.ts +++ b/services/site/src/i18n/content/br.ts @@ -44,11 +44,6 @@ export const content = { body: "Controle o OpenCode pelos seus scripts, jobs de CI e ferramentas.", action: "Ver docs", }, - ide: { - name: "Extensões de IDE", - body: "Abra o OpenCode no VS Code, Cursor e Windsurf, ou no Zed e em IDEs JetBrains via ACP.", - action: "Instalar", - }, mini: { name: "Mini", body: "Uma interface de terminal mínima. As respostas vão para o seu histórico, com um prompt embaixo.", @@ -258,47 +253,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Integrações com editores como VS Code, Cursor e Zed", - description: - "Use o OpenCode no seu editor, com a extensão para VS Code, Cursor, Windsurf e VSCodium, e opencode acp para Zed, IDEs JetBrains e outros editores ACP.", - intro: - "Use o OpenCode no seu editor. No VS Code, Cursor, Windsurf e VSCodium, rode opencode no terminal integrado e a extensão se instala sozinha. Zed, IDEs JetBrains e outros editores compatíveis com o Agent Client Protocol rodam o OpenCode com opencode acp.", - features: { - "quick-launch": { - title: "Abertura rápida", - body: "Cmd+Esc ou Ctrl+Esc abre o OpenCode em um terminal dividido.", - }, - "new-session": { - title: "Nova sessão", - body: "Cmd+Shift+Esc ou Ctrl+Shift+Esc inicia outra sessão.", - }, - context: { - title: "Contexto", - body: "Compartilha sua seleção ou aba atual com o OpenCode.", - }, - "file-references": { - title: "Citar arquivos", - body: "Cmd+Option+K ou Alt+Ctrl+K insere @File#L37-42.", - }, - "installs-itself": { - title: "Instala sozinha", - body: "Rode opencode no terminal integrado para adicioná-la.", - }, - "acp-editors": { - title: "Editores ACP", - body: "Zed, IDEs JetBrains, Avante.nvim e CodeCompanion.nvim.", - }, - "open-vsx": { - title: "Open VSX", - body: "Também no Open VSX para Cursor, Windsurf e VSCodium.", - }, - "same-agent": { - title: "Mesmo agente", - body: "O OpenCode que você roda no terminal, ao lado do seu código.", - }, - }, - }, mini: { title: "OpenCode | Mini, uma interface de terminal mínima para o agente", description: @@ -1181,20 +1135,6 @@ export const content = { label: "Ler a documentação do SDK", }, }, - ide: { - links: { - "vs-code-marketplace": { - label: "VS Code Marketplace", - }, - "open-vsx-cursor-windsurf-vscodium": { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - }, - }, - lead: "Rode opencode no terminal integrado do seu editor e a extensão se instala sozinha, ou instale você mesmo.", - more: { - label: "Configure o Zed, IDEs JetBrains e outros editores ACP", - }, - }, mini: { lead: "O Mini vem com a CLI do OpenCode. Instale com qualquer uma destas opções e rode opencode mini.", commands: { diff --git a/services/site/src/i18n/content/da.ts b/services/site/src/i18n/content/da.ts index 1a28b9331d7e..7f8a8d001288 100644 --- a/services/site/src/i18n/content/da.ts +++ b/services/site/src/i18n/content/da.ts @@ -18,11 +18,6 @@ export const content = { action: "Installer", }, sdk: { body: "Styr OpenCode fra dine egne scripts, CI-jobs og værktøjer.", action: "Læs docs" }, - ide: { - name: "IDE-udvidelser", - body: "Åbn OpenCode i VS Code, Cursor og Windsurf, eller i Zed og JetBrains-IDE'er via ACP.", - action: "Installer", - }, mini: { body: "En minimal terminalbrugerflade. Svarene skrives ind i din scrollback med én prompt nedenunder.", action: "Installer", @@ -186,26 +181,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Editorintegrationer til VS Code, Cursor og Zed", - description: - "Brug OpenCode i din editor med udvidelsen til VS Code, Cursor, Windsurf og VSCodium, og med opencode acp til Zed, JetBrains-IDE'er og andre ACP-editorer.", - intro: - "Brug OpenCode i din editor. I VS Code, Cursor, Windsurf og VSCodium kører du opencode i den indbyggede terminal, og udvidelsen installerer sig selv. Zed, JetBrains-IDE'er og andre editorer, der understøtter Agent Client Protocol, kører OpenCode med opencode acp.", - features: { - "quick-launch": { title: "Hurtig start", body: "Cmd+Esc eller Ctrl+Esc åbner OpenCode i en delt terminal." }, - "new-session": { title: "Ny session", body: "Cmd+Shift+Esc eller Ctrl+Shift+Esc starter en ny session." }, - context: { title: "Kontekst", body: "Deler din aktuelle markering eller fane med OpenCode." }, - "file-references": { title: "Filreferencer", body: "Cmd+Option+K eller Alt+Ctrl+K indsætter @File#L37-42." }, - "installs-itself": { - title: "Installerer sig selv", - body: "Kør opencode i den indbyggede terminal for at tilføje den.", - }, - "acp-editors": { title: "ACP-editorer", body: "Zed, JetBrains-IDE'er, Avante.nvim og CodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "Også på Open VSX til Cursor, Windsurf og VSCodium." }, - "same-agent": { title: "Samme agent", body: "Det OpenCode, du kører i terminalen, ved siden af din kode." }, - }, - }, mini: { title: "OpenCode | Mini, en minimal terminalbrugerflade til agenten", description: @@ -690,14 +665,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "Script" } } }, sdk: { more: { label: "Læs SDK-dokumentationen" } }, - ide: { - lead: "Kør opencode i din editors indbyggede terminal, så installerer udvidelsen sig selv. Du kan også installere den selv.", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "Opsæt Zed, JetBrains-IDE'er og andre ACP-editorer" }, - }, mini: { commands: { curl: { name: "Script" } }, lead: "Mini følger med OpenCode CLI. Installer den på en af disse måder, og kør så opencode mini.", diff --git a/services/site/src/i18n/content/de.ts b/services/site/src/i18n/content/de.ts index fcdbb471fcd4..2e0c05f7fe8d 100644 --- a/services/site/src/i18n/content/de.ts +++ b/services/site/src/i18n/content/de.ts @@ -18,11 +18,6 @@ export const content = { action: "Installieren", }, sdk: { body: "Steuere OpenCode aus deinen eigenen Skripten, CI-Jobs und Tools.", action: "Doku lesen" }, - ide: { - name: "IDE-Extensions", - body: "Öffne OpenCode in VS Code, Cursor und Windsurf, oder über ACP in Zed und JetBrains-IDEs.", - action: "Installieren", - }, mini: { body: "Ein minimales Terminal-Interface. Antworten landen in deinem Scrollback, darunter steht ein Prompt.", action: "Installieren", @@ -207,32 +202,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Editor-Integrationen für VS Code, Cursor und Zed", - description: - "Nutze OpenCode in deinem Editor, mit der Extension für VS Code, Cursor, Windsurf und VSCodium und mit opencode acp für Zed, JetBrains-IDEs und andere ACP-Editoren.", - intro: - "Nutze OpenCode in deinem Editor. In VS Code, Cursor, Windsurf und VSCodium führst du opencode im integrierten Terminal aus, und die Extension installiert sich selbst. Zed, JetBrains-IDEs und andere Editoren mit Unterstützung für das Agent Client Protocol starten OpenCode mit opencode acp.", - features: { - "quick-launch": { - title: "Schnellstart", - body: "Cmd+Esc oder Ctrl+Esc öffnet OpenCode in einem geteilten Terminal.", - }, - "new-session": { - title: "Neue Session", - body: "Cmd+Shift+Esc oder Ctrl+Shift+Esc startet eine weitere Session.", - }, - context: { title: "Kontext", body: "Teilt deine aktuelle Auswahl oder deinen Tab mit OpenCode." }, - "file-references": { title: "Dateiverweise", body: "Cmd+Option+K oder Alt+Ctrl+K fügt @File#L37-42 ein." }, - "installs-itself": { - title: "Auto-Installation", - body: "Führe opencode im integrierten Terminal aus, um sie hinzuzufügen.", - }, - "acp-editors": { title: "ACP-Editoren", body: "Zed, JetBrains-IDEs, Avante.nvim und CodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "Auch auf Open VSX für Cursor, Windsurf und VSCodium." }, - "same-agent": { title: "Derselbe Agent", body: "Das OpenCode aus deinem Terminal, direkt neben deinem Code." }, - }, - }, mini: { title: "OpenCode | Mini, ein minimales Terminal-Interface für den Agent", description: @@ -738,14 +707,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "Skript" } } }, sdk: { more: { label: "SDK-Doku lesen" } }, - ide: { - lead: "Führe opencode im integrierten Terminal deines Editors aus, und die Extension installiert sich selbst. Oder installiere sie manuell.", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "Zed, JetBrains-IDEs und andere ACP-Editoren einrichten" }, - }, mini: { commands: { curl: { name: "Skript" } }, lead: "Mini ist Teil der OpenCode CLI. Installiere sie auf einem dieser Wege und führe dann opencode mini aus.", diff --git a/services/site/src/i18n/content/es.ts b/services/site/src/i18n/content/es.ts index b2c582f61be3..ace5fa1995fd 100644 --- a/services/site/src/i18n/content/es.ts +++ b/services/site/src/i18n/content/es.ts @@ -21,11 +21,6 @@ export const content = { body: "Controla OpenCode desde tus scripts, jobs de CI y herramientas.", action: "Ver docs", }, - ide: { - name: "Extensiones IDE", - body: "Abre OpenCode en VS Code, Cursor y Windsurf, o en Zed y los IDE de JetBrains mediante ACP.", - action: "Instalar", - }, mini: { body: "Una interfaz de terminal mínima. Las respuestas se imprimen en tu historial, con un solo prompt debajo.", action: "Instalar", @@ -234,47 +229,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Integraciones de editor para VS Code, Cursor y Zed", - description: - "Usa OpenCode dentro de tu editor, con la extensión para VS Code, Cursor, Windsurf y VSCodium, y opencode acp para Zed, los IDE de JetBrains y otros editores ACP.", - intro: - "Usa OpenCode dentro de tu editor. En VS Code, Cursor, Windsurf y VSCodium, ejecuta opencode en la terminal integrada y la extensión se instala sola. Zed, los IDE de JetBrains y otros editores compatibles con el Agent Client Protocol ejecutan OpenCode con opencode acp.", - features: { - "quick-launch": { - title: "Inicio rápido", - body: "Cmd+Esc o Ctrl+Esc abre OpenCode en una terminal dividida.", - }, - "new-session": { - title: "Nueva sesión", - body: "Cmd+Shift+Esc o Ctrl+Shift+Esc inicia otra sesión.", - }, - context: { - title: "Contexto", - body: "Comparte tu selección o pestaña actual con OpenCode.", - }, - "file-references": { - title: "Citar archivos", - body: "Cmd+Option+K o Alt+Ctrl+K inserta @File#L37-42.", - }, - "installs-itself": { - title: "Se instala sola", - body: "Ejecuta opencode en la terminal integrada para añadirla.", - }, - "acp-editors": { - title: "Editores ACP", - body: "Zed, IDE de JetBrains, Avante.nvim y CodeCompanion.nvim.", - }, - "open-vsx": { - title: "Open VSX", - body: "También en Open VSX para Cursor, Windsurf y VSCodium.", - }, - "same-agent": { - title: "Mismo agente", - body: "El OpenCode que usas en la terminal, junto a tu código.", - }, - }, - }, mini: { title: "OpenCode | Mini, una interfaz de terminal mínima para el agente", description: @@ -1120,20 +1074,6 @@ export const content = { label: "Lee la documentación del SDK", }, }, - ide: { - lead: "Ejecuta opencode en la terminal integrada de tu editor y la extensión se instala sola, o instálala tú.", - more: { - label: "Configura Zed, los IDE de JetBrains y otros editores ACP", - }, - links: { - "vs-code-marketplace": { - label: "VS Code Marketplace", - }, - "open-vsx-cursor-windsurf-vscodium": { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - }, - }, - }, mini: { lead: "Mini viene con la CLI de OpenCode. Instálala con cualquiera de estos comandos y luego ejecuta opencode mini.", commands: { diff --git a/services/site/src/i18n/content/fr.ts b/services/site/src/i18n/content/fr.ts index fdd5b0db409a..d3c49b4fe211 100644 --- a/services/site/src/i18n/content/fr.ts +++ b/services/site/src/i18n/content/fr.ts @@ -21,11 +21,6 @@ export const content = { body: "Pilotez OpenCode depuis vos scripts, jobs CI et outils.", action: "Lire la doc", }, - ide: { - name: "Extensions IDE", - body: "Ouvrez OpenCode dans VS Code, Cursor et Windsurf, ou dans Zed et les IDE JetBrains via ACP.", - action: "Installer", - }, mini: { body: "Une interface terminal minimale. Les réponses s'affichent dans votre historique, avec un seul prompt en dessous.", action: "Installer", @@ -234,47 +229,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Intégrations éditeur pour VS Code, Cursor et Zed", - description: - "Utilisez OpenCode dans votre éditeur, avec l'extension pour VS Code, Cursor, Windsurf et VSCodium, et opencode acp pour Zed, les IDE JetBrains et d'autres éditeurs ACP.", - intro: - "Utilisez OpenCode dans votre éditeur. Dans VS Code, Cursor, Windsurf et VSCodium, lancez opencode dans le terminal intégré et l'extension s'installe d'elle-même. Zed, les IDE JetBrains et les autres éditeurs compatibles avec l'Agent Client Protocol lancent OpenCode avec opencode acp.", - features: { - "quick-launch": { - title: "Lancement rapide", - body: "Cmd+Esc ou Ctrl+Esc ouvre OpenCode dans un terminal scindé.", - }, - "new-session": { - title: "Autre session", - body: "Cmd+Shift+Esc ou Ctrl+Shift+Esc lance une autre session.", - }, - context: { - title: "Contexte", - body: "Partage votre sélection ou votre onglet actuel avec OpenCode.", - }, - "file-references": { - title: "Citer un fichier", - body: "Cmd+Option+K ou Alt+Ctrl+K insère @File#L37-42.", - }, - "installs-itself": { - title: "Installation auto", - body: "Lancez opencode dans le terminal intégré pour l'ajouter.", - }, - "acp-editors": { - title: "Éditeurs ACP", - body: "Zed, IDE JetBrains, Avante.nvim et CodeCompanion.nvim.", - }, - "open-vsx": { - title: "Open VSX", - body: "Aussi sur Open VSX pour Cursor, Windsurf et VSCodium.", - }, - "same-agent": { - title: "Le même agent", - body: "L'OpenCode que vous lancez dans le terminal, à côté de votre code.", - }, - }, - }, mini: { title: "OpenCode | Mini, une interface terminal minimale pour l'agent", description: @@ -1120,20 +1074,6 @@ export const content = { label: "Lire la doc du SDK", }, }, - ide: { - lead: "Lancez opencode dans le terminal intégré de votre éditeur et l'extension s'installe d'elle-même, ou installez-la vous-même.", - more: { - label: "Configurer Zed, les IDE JetBrains et d'autres éditeurs ACP", - }, - links: { - "vs-code-marketplace": { - label: "VS Code Marketplace", - }, - "open-vsx-cursor-windsurf-vscodium": { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - }, - }, - }, mini: { lead: "Mini est inclus dans le CLI OpenCode. Installez-le avec l'une de ces commandes, puis lancez opencode mini.", commands: { diff --git a/services/site/src/i18n/content/it.ts b/services/site/src/i18n/content/it.ts index d6452c817dca..afebbf3883ab 100644 --- a/services/site/src/i18n/content/it.ts +++ b/services/site/src/i18n/content/it.ts @@ -21,11 +21,6 @@ export const content = { body: "Controlla OpenCode dai tuoi script, job di CI e strumenti.", action: "Leggi i docs", }, - ide: { - name: "Estensioni IDE", - body: "Apri OpenCode in VS Code, Cursor e Windsurf, oppure in Zed e negli IDE JetBrains tramite ACP.", - action: "Installa", - }, mini: { body: "Un'interfaccia da terminale minimale. Le risposte finiscono nello scrollback, con un solo prompt sotto.", action: "Installa", @@ -234,47 +229,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Integrazioni editor per VS Code, Cursor e Zed", - description: - "Usa OpenCode nel tuo editor, con l'estensione per VS Code, Cursor, Windsurf e VSCodium, e opencode acp per Zed, gli IDE JetBrains e altri editor ACP.", - intro: - "Usa OpenCode nel tuo editor. In VS Code, Cursor, Windsurf e VSCodium, esegui opencode nel terminale integrato e l'estensione si installa da sola. Zed, gli IDE JetBrains e gli altri editor che supportano l'Agent Client Protocol eseguono OpenCode con opencode acp.", - features: { - "quick-launch": { - title: "Avvio rapido", - body: "Cmd+Esc o Ctrl+Esc apre OpenCode in un terminale diviso.", - }, - "new-session": { - title: "Nuova sessione", - body: "Cmd+Shift+Esc o Ctrl+Shift+Esc avvia un'altra sessione.", - }, - context: { - title: "Contesto", - body: "Condivide con OpenCode la selezione o la scheda corrente.", - }, - "file-references": { - title: "Riferimenti ai file", - body: "Cmd+Option+K o Alt+Ctrl+K inserisce @File#L37-42.", - }, - "installs-itself": { - title: "Si installa da sé", - body: "Esegui opencode nel terminale integrato per aggiungerla.", - }, - "acp-editors": { - title: "Editor ACP", - body: "Zed, IDE JetBrains, Avante.nvim e CodeCompanion.nvim.", - }, - "open-vsx": { - title: "Open VSX", - body: "Anche su Open VSX per Cursor, Windsurf e VSCodium.", - }, - "same-agent": { - title: "Stesso agente", - body: "L'OpenCode che usi nel terminale, accanto al tuo codice.", - }, - }, - }, mini: { title: "OpenCode | Mini, un'interfaccia da terminale minimale", description: @@ -1119,20 +1073,6 @@ export const content = { label: "Leggi la documentazione dell'SDK", }, }, - ide: { - lead: "Esegui opencode nel terminale integrato del tuo editor e l'estensione si installa da sola, oppure installala tu.", - more: { - label: "Configura Zed, gli IDE JetBrains e altri editor ACP", - }, - links: { - "vs-code-marketplace": { - label: "VS Code Marketplace", - }, - "open-vsx-cursor-windsurf-vscodium": { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - }, - }, - }, mini: { lead: "Mini è incluso nella CLI di OpenCode. Installala con uno di questi comandi, poi esegui opencode mini.", commands: { diff --git a/services/site/src/i18n/content/ja.ts b/services/site/src/i18n/content/ja.ts index 8f9d68eb330e..a8891778494a 100644 --- a/services/site/src/i18n/content/ja.ts +++ b/services/site/src/i18n/content/ja.ts @@ -22,11 +22,6 @@ export const content = { body: "自分のスクリプト、CIジョブ、ツールからOpenCodeを操作できます。", action: "ドキュメント", }, - ide: { - name: "IDE拡張機能", - body: "VS Code、Cursor、WindsurfでOpenCodeを開けます。ZedやJetBrains IDEではACP経由で使えます。", - action: "インストール", - }, mini: { name: "Mini", body: "最小限のターミナルインターフェース。返答はスクロールバックに出力され、下にはプロンプトが1つだけ残ります。", @@ -188,32 +183,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | VS Code、Cursor、Zed向けのエディタ連携", - description: - "エディタの中でOpenCodeを使えます。VS Code、Cursor、Windsurf、VSCodiumには拡張機能があり、Zed、JetBrains IDE、その他のACP対応エディタでは opencode acp を使います。", - intro: - "エディタの中でOpenCodeを使えます。VS Code、Cursor、Windsurf、VSCodiumでは、統合ターミナルで opencode を実行すると拡張機能が自動でインストールされます。Zed、JetBrains IDE、その他のAgent Client Protocol対応エディタでは、opencode acp でOpenCodeを実行します。", - features: { - "quick-launch": { - title: "すばやく起動", - body: "Cmd+Esc または Ctrl+Esc で、分割したターミナルにOpenCodeを開きます。", - }, - "new-session": { - title: "新規セッション", - body: "Cmd+Shift+Esc または Ctrl+Shift+Esc で別のセッションを開始します。", - }, - context: { title: "コンテキスト", body: "現在の選択範囲やタブをOpenCodeと共有します。" }, - "file-references": { - title: "ファイル参照", - body: "Cmd+Option+K または Alt+Ctrl+K で @File#L37-42 を挿入します。", - }, - "installs-itself": { title: "自動インストール", body: "統合ターミナルで opencode を実行すると追加されます。" }, - "acp-editors": { title: "ACPエディタ", body: "Zed、JetBrains IDE、Avante.nvim、CodeCompanion.nvim。" }, - "open-vsx": { title: "Open VSX", body: "Cursor、Windsurf、VSCodium向けにOpen VSXでも公開しています。" }, - "same-agent": { title: "同じエージェント", body: "ターミナルで使うOpenCodeを、コードのすぐ横で。" }, - }, - }, mini: { title: "OpenCode | Mini、エージェントのための最小限のターミナルUI", description: @@ -719,14 +688,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "スクリプト" } } }, sdk: { more: { label: "SDKのドキュメントを読む" } }, - ide: { - lead: "エディタの統合ターミナルで opencode を実行すると拡張機能が自動でインストールされます。手動でインストールすることもできます。", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX(Cursor、Windsurf、VSCodium)" }, - }, - more: { label: "Zed、JetBrains IDE、その他のACPエディタを設定" }, - }, mini: { commands: { curl: { name: "スクリプト" } }, lead: "MiniはOpenCode CLIに含まれています。次のいずれかでインストールし、opencode mini を実行してください。", diff --git a/services/site/src/i18n/content/ko.ts b/services/site/src/i18n/content/ko.ts index 25e147bafc12..e060283994ef 100644 --- a/services/site/src/i18n/content/ko.ts +++ b/services/site/src/i18n/content/ko.ts @@ -18,11 +18,6 @@ export const content = { action: "설치", }, sdk: { name: "SDK", body: "직접 만든 스크립트, CI 작업, 도구에서 OpenCode를 제어하세요.", action: "문서 읽기" }, - ide: { - name: "IDE 확장 프로그램", - body: "VS Code, Cursor, Windsurf에서 OpenCode를 열거나, ACP로 Zed와 JetBrains IDE에서 사용하세요.", - action: "설치", - }, mini: { name: "Mini", body: "미니멀한 터미널 인터페이스입니다. 답변은 스크롤백에 출력되고, 아래에는 프롬프트 하나만 남습니다.", @@ -163,23 +158,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | VS Code, Cursor, Zed 등을 위한 IDE 확장 프로그램", - description: - "에디터 안에서 OpenCode를 사용하세요. VS Code, Cursor, Windsurf, VSCodium에는 확장 프로그램이, Zed, JetBrains IDE 등 ACP 에디터에는 opencode acp가 있습니다.", - intro: - "에디터 안에서 OpenCode를 사용하세요. VS Code, Cursor, Windsurf, VSCodium에서는 통합 터미널에서 opencode를 실행하면 확장 프로그램이 자동으로 설치됩니다. Zed, JetBrains IDE 등 Agent Client Protocol을 지원하는 에디터에서는 opencode acp로 OpenCode를 실행합니다.", - features: { - "quick-launch": { title: "빠른 실행", body: "Cmd+Esc 또는 Ctrl+Esc로 분할 터미널에서 OpenCode를 엽니다." }, - "new-session": { title: "새 세션", body: "Cmd+Shift+Esc 또는 Ctrl+Shift+Esc로 새 세션을 시작합니다." }, - context: { title: "컨텍스트", body: "현재 선택 영역이나 탭을 OpenCode와 공유합니다." }, - "file-references": { title: "파일 참조", body: "Cmd+Option+K 또는 Alt+Ctrl+K로 @File#L37-42를 삽입합니다." }, - "installs-itself": { title: "자동 설치", body: "통합 터미널에서 opencode를 실행하면 추가됩니다." }, - "acp-editors": { title: "ACP 에디터", body: "Zed, JetBrains IDE, Avante.nvim, CodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "Cursor, Windsurf, VSCodium용으로 Open VSX에도 있습니다." }, - "same-agent": { title: "같은 에이전트", body: "터미널에서 쓰던 그 OpenCode를 코드 바로 옆에서." }, - }, - }, mini: { title: "OpenCode | 에이전트를 위한 미니멀 터미널 인터페이스, Mini", description: @@ -653,14 +631,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "스크립트" } } }, sdk: { more: { label: "SDK 문서 읽기" } }, - ide: { - links: { - "vs-code-marketplace": { label: "VS Code 마켓플레이스" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - lead: "에디터의 통합 터미널에서 opencode를 실행하면 확장 프로그램이 자동으로 설치됩니다. 직접 설치할 수도 있습니다.", - more: { label: "Zed, JetBrains IDE 등 ACP 에디터 설정" }, - }, mini: { commands: { curl: { name: "스크립트" } }, lead: "Mini는 OpenCode CLI에 포함되어 있습니다. 아래 방법 중 하나로 설치한 뒤 opencode mini를 실행하세요.", diff --git a/services/site/src/i18n/content/no.ts b/services/site/src/i18n/content/no.ts index 5008dde0b454..54d84ac42469 100644 --- a/services/site/src/i18n/content/no.ts +++ b/services/site/src/i18n/content/no.ts @@ -18,11 +18,6 @@ export const content = { action: "Installer", }, sdk: { body: "Styr OpenCode fra dine egne skript, CI-jobber og verktøy.", action: "Les docs" }, - ide: { - name: "IDE-utvidelser", - body: "Åpne OpenCode i VS Code, Cursor og Windsurf, eller i Zed og JetBrains-IDE-er via ACP.", - action: "Installer", - }, mini: { body: "Et minimalt terminalgrensesnitt. Svarene skrives inn i scrollbacken din, med én prompt under.", action: "Installer", @@ -186,26 +181,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Editorintegrasjoner for VS Code, Cursor og Zed", - description: - "Bruk OpenCode i editoren din, med utvidelsen for VS Code, Cursor, Windsurf og VSCodium, og opencode acp for Zed, JetBrains-IDE-er og andre ACP-editorer.", - intro: - "Bruk OpenCode i editoren din. I VS Code, Cursor, Windsurf og VSCodium kjører du opencode i den integrerte terminalen, så installerer utvidelsen seg selv. Zed, JetBrains-IDE-er og andre editorer som støtter Agent Client Protocol, kjører OpenCode med opencode acp.", - features: { - "quick-launch": { title: "Hurtigstart", body: "Cmd+Esc eller Ctrl+Esc åpner OpenCode i en delt terminal." }, - "new-session": { title: "Ny sesjon", body: "Cmd+Shift+Esc eller Ctrl+Shift+Esc starter en ny sesjon." }, - context: { title: "Kontekst", body: "Deler gjeldende utvalg eller fane med OpenCode." }, - "file-references": { title: "Filreferanser", body: "Cmd+Option+K eller Alt+Ctrl+K setter inn @File#L37-42." }, - "installs-itself": { - title: "Installerer seg", - body: "Kjør opencode i den integrerte terminalen for å legge den til.", - }, - "acp-editors": { title: "ACP-editorer", body: "Zed, JetBrains-IDE-er, Avante.nvim og CodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "Også på Open VSX for Cursor, Windsurf og VSCodium." }, - "same-agent": { title: "Samme agent", body: "OpenCode du kjører i terminalen, ved siden av koden din." }, - }, - }, mini: { title: "OpenCode | Mini, et minimalt terminalgrensesnitt for agenten", description: @@ -696,14 +671,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "Skript" } } }, sdk: { more: { label: "Les SDK-dokumentasjonen" } }, - ide: { - lead: "Kjør opencode i den integrerte terminalen i editoren din, så installerer utvidelsen seg selv. Du kan også installere den selv.", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "Sett opp Zed, JetBrains-IDE-er og andre ACP-editorer" }, - }, mini: { commands: { curl: { name: "Skript" } }, lead: "Mini følger med OpenCode CLI. Installer den på en av disse måtene, og kjør så opencode mini.", diff --git a/services/site/src/i18n/content/pl.ts b/services/site/src/i18n/content/pl.ts index 54c3938b295d..f9c2b2bf5bce 100644 --- a/services/site/src/i18n/content/pl.ts +++ b/services/site/src/i18n/content/pl.ts @@ -44,11 +44,6 @@ export const content = { body: "Steruj OpenCode z własnych skryptów, zadań CI i narzędzi.", action: "Czytaj docs", }, - ide: { - name: "Rozszerzenia IDE", - body: "Otwórz OpenCode w VS Code, Cursorze i Windsurfie albo w Zedzie i IDE JetBrains przez ACP.", - action: "Instaluj", - }, mini: { name: "Mini", body: "Minimalny interfejs terminalowy. Odpowiedzi trafiają do historii terminala, a pod nimi jest jeden prompt.", @@ -258,47 +253,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Integracje z edytorami VS Code, Cursor i Zed", - description: - "Używaj OpenCode w edytorze, z rozszerzeniem dla VS Code, Cursora, Windsurfa i VSCodium oraz opencode acp dla Zeda, IDE JetBrains i innych edytorów ACP.", - intro: - "Używaj OpenCode w swoim edytorze. W VS Code, Cursorze, Windsurfie i VSCodium uruchom opencode we wbudowanym terminalu, a rozszerzenie zainstaluje się samo. Zed, IDE JetBrains i inne edytory obsługujące Agent Client Protocol uruchamiają OpenCode przez opencode acp.", - features: { - "quick-launch": { - title: "Szybki start", - body: "Cmd+Esc lub Ctrl+Esc otwiera OpenCode w podzielonym terminalu.", - }, - "new-session": { - title: "Nowa sesja", - body: "Cmd+Shift+Esc lub Ctrl+Shift+Esc zaczyna kolejną sesję.", - }, - context: { - title: "Kontekst", - body: "Udostępnia OpenCode bieżące zaznaczenie lub kartę.", - }, - "file-references": { - title: "Odwołania", - body: "Cmd+Option+K lub Alt+Ctrl+K wstawia @File#L37-42.", - }, - "installs-itself": { - title: "Instaluje się samo", - body: "Uruchom opencode we wbudowanym terminalu, aby je dodać.", - }, - "acp-editors": { - title: "Edytory ACP", - body: "Zed, IDE JetBrains, Avante.nvim i CodeCompanion.nvim.", - }, - "open-vsx": { - title: "Open VSX", - body: "Dostępne też w Open VSX dla Cursora, Windsurfa i VSCodium.", - }, - "same-agent": { - title: "Ten sam agent", - body: "OpenCode, którego używasz w terminalu, obok Twojego kodu.", - }, - }, - }, mini: { title: "OpenCode | Mini, minimalny interfejs terminalowy dla agenta", description: @@ -1181,20 +1135,6 @@ export const content = { label: "Czytaj dokumentację SDK", }, }, - ide: { - links: { - "vs-code-marketplace": { - label: "VS Code Marketplace", - }, - "open-vsx-cursor-windsurf-vscodium": { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - }, - }, - lead: "Uruchom opencode we wbudowanym terminalu edytora, a rozszerzenie zainstaluje się samo, albo zainstaluj je ręcznie.", - more: { - label: "Skonfiguruj Zeda, IDE JetBrains i inne edytory ACP", - }, - }, mini: { lead: "Mini jest częścią OpenCode CLI. Zainstaluj go dowolnym z tych sposobów, a potem uruchom opencode mini.", commands: { diff --git a/services/site/src/i18n/content/ru.ts b/services/site/src/i18n/content/ru.ts index 8d9a14263614..4ed88d9cd0a4 100644 --- a/services/site/src/i18n/content/ru.ts +++ b/services/site/src/i18n/content/ru.ts @@ -18,11 +18,6 @@ export const content = { action: "Установить", }, sdk: { body: "Управляйте OpenCode из своих скриптов, CI-задач и инструментов.", action: "Документация" }, - ide: { - name: "Расширения для IDE", - body: "Открывайте OpenCode в VS Code, Cursor и Windsurf или в Zed и JetBrains IDE через ACP.", - action: "Установить", - }, mini: { body: "Минимальный терминальный интерфейс. Ответы выводятся в историю прокрутки, а внизу одна строка ввода.", action: "Установить", @@ -183,29 +178,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Интеграции с редакторами VS Code, Cursor и Zed", - description: - "Используйте OpenCode в своём редакторе. Расширение для VS Code, Cursor, Windsurf и VSCodium, а opencode acp для Zed, JetBrains IDE и других ACP-редакторов.", - intro: - "Используйте OpenCode в своём редакторе. В VS Code, Cursor, Windsurf и VSCodium запустите opencode во встроенном терминале, и расширение установится само. Zed, JetBrains IDE и другие редакторы с поддержкой Agent Client Protocol запускают OpenCode через opencode acp.", - features: { - "quick-launch": { - title: "Быстрый запуск", - body: "Cmd+Esc или Ctrl+Esc открывает OpenCode в разделённом терминале.", - }, - "new-session": { title: "Новая сессия", body: "Cmd+Shift+Esc или Ctrl+Shift+Esc начинает ещё одну сессию." }, - context: { title: "Контекст", body: "Передаёт в OpenCode текущее выделение или вкладку." }, - "file-references": { title: "Ссылки на файлы", body: "Cmd+Option+K или Alt+Ctrl+K вставляет @File#L37-42." }, - "installs-itself": { - title: "Ставится само", - body: "Запустите opencode во встроенном терминале, чтобы добавить его.", - }, - "acp-editors": { title: "ACP-редакторы", body: "Zed, JetBrains IDE, Avante.nvim и CodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "Также в Open VSX для Cursor, Windsurf и VSCodium." }, - "same-agent": { title: "Тот же агент", body: "Тот же OpenCode, что и в терминале, рядом с вашим кодом." }, - }, - }, mini: { title: "OpenCode | Mini, минимальный терминальный интерфейс агента", description: @@ -689,14 +661,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "Скрипт" } } }, sdk: { more: { label: "Документация SDK" } }, - ide: { - lead: "Запустите opencode во встроенном терминале редактора, и расширение установится само, или установите его вручную.", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "Настройка Zed, JetBrains IDE и других ACP-редакторов" }, - }, mini: { lead: "Mini входит в OpenCode CLI. Установите его любым из этих способов, затем запустите opencode mini.", commands: { curl: { name: "Скрипт" } }, diff --git a/services/site/src/i18n/content/th.ts b/services/site/src/i18n/content/th.ts index b9b01c112331..c5a63140b912 100644 --- a/services/site/src/i18n/content/th.ts +++ b/services/site/src/i18n/content/th.ts @@ -18,11 +18,6 @@ export const content = { action: "ติดตั้ง", }, sdk: { name: "SDK", body: "ควบคุม OpenCode จากสคริปต์ งาน CI และเครื่องมือของคุณเอง", action: "อ่านเอกสาร" }, - ide: { - name: "ส่วนขยาย IDE", - body: "เปิด OpenCode ใน VS Code, Cursor และ Windsurf หรือใน Zed และ JetBrains IDE ผ่าน ACP", - action: "ติดตั้ง", - }, mini: { name: "Mini", body: "อินเทอร์เฟซเทอร์มินัลแบบมินิมอล คำตอบจะพิมพ์ลงใน scrollback ของคุณ โดยมีพรอมต์เดียวอยู่ด้านล่าง", @@ -157,26 +152,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | การเชื่อมต่ออีดิเตอร์สำหรับ VS Code, Cursor และ Zed", - description: - "ใช้ OpenCode ในอีดิเตอร์ของคุณ ด้วยส่วนขยายสำหรับ VS Code, Cursor, Windsurf และ VSCodium และ opencode acp สำหรับ Zed, JetBrains IDE และอีดิเตอร์ ACP อื่นๆ", - intro: - "ใช้ OpenCode ในอีดิเตอร์ของคุณ ใน VS Code, Cursor, Windsurf และ VSCodium ให้รัน opencode ในเทอร์มินัลในตัว แล้วส่วนขยายจะติดตั้งเอง Zed, JetBrains IDE และอีดิเตอร์อื่นที่รองรับ Agent Client Protocol จะรัน OpenCode ด้วย opencode acp", - features: { - "quick-launch": { title: "เปิดด่วน", body: "Cmd+Esc หรือ Ctrl+Esc เปิด OpenCode ในเทอร์มินัลแบบแยกหน้าจอ" }, - "new-session": { title: "เซสชันใหม่", body: "Cmd+Shift+Esc หรือ Ctrl+Shift+Esc เริ่มอีกเซสชัน" }, - context: { title: "บริบท", body: "แชร์ส่วนที่เลือกหรือแท็บปัจจุบันกับ OpenCode" }, - "file-references": { title: "อ้างอิงไฟล์", body: "Cmd+Option+K หรือ Alt+Ctrl+K แทรก @File#L37-42" }, - "installs-itself": { title: "ติดตั้งเอง", body: "รัน opencode ในเทอร์มินัลในตัวเพื่อเพิ่มส่วนขยาย" }, - "acp-editors": { title: "อีดิเตอร์ ACP", body: "Zed, JetBrains IDE, Avante.nvim และ CodeCompanion.nvim" }, - "open-vsx": { title: "Open VSX", body: "มีบน Open VSX สำหรับ Cursor, Windsurf และ VSCodium ด้วย" }, - "same-agent": { - title: "เอเจนต์เดียวกัน", - body: "OpenCode ตัวเดียวกับที่คุณใช้ในเทอร์มินัล อยู่ข้างโค้ดของคุณ", - }, - }, - }, mini: { title: "OpenCode | Mini อินเทอร์เฟซเทอร์มินัลแบบมินิมอลสำหรับเอเจนต์", description: @@ -670,14 +645,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "สคริปต์" } } }, sdk: { more: { label: "อ่านเอกสาร SDK" } }, - ide: { - lead: "รัน opencode ในเทอร์มินัลในตัวของอีดิเตอร์ แล้วส่วนขยายจะติดตั้งเอง หรือติดตั้งด้วยตัวเองก็ได้", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "ตั้งค่า Zed, JetBrains IDE และอีดิเตอร์ ACP อื่นๆ" }, - }, mini: { commands: { curl: { name: "สคริปต์" } }, lead: "Mini มาพร้อมกับ OpenCode CLI ติดตั้งด้วยวิธีใดก็ได้ด้านล่าง แล้วรัน opencode mini", diff --git a/services/site/src/i18n/content/tr.ts b/services/site/src/i18n/content/tr.ts index cb27b34a70db..1c57d78cf0d1 100644 --- a/services/site/src/i18n/content/tr.ts +++ b/services/site/src/i18n/content/tr.ts @@ -44,11 +44,6 @@ export const content = { body: "OpenCode'u kendi betiklerinizden, CI işlerinizden ve araçlarınızdan yönetin.", action: "Dokümanlar", }, - ide: { - name: "IDE eklentileri", - body: "OpenCode'u VS Code, Cursor ve Windsurf'te ya da ACP ile Zed ve JetBrains IDE'lerinde açın.", - action: "Kur", - }, mini: { name: "Mini", body: "Minimal bir terminal arayüzü. Yanıtlar kaydırma geçmişinize yazılır, altta tek bir prompt kalır.", @@ -258,47 +253,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | VS Code, Cursor ve Zed için editör entegrasyonları", - description: - "OpenCode'u editörünüzde kullanın. VS Code, Cursor, Windsurf ve VSCodium için eklenti, Zed, JetBrains IDE'leri ve diğer ACP editörleri için opencode acp.", - intro: - "OpenCode'u editörünüzün içinde kullanın. VS Code, Cursor, Windsurf ve VSCodium'da entegre terminalde opencode çalıştırın, eklenti kendini kursun. Zed, JetBrains IDE'leri ve Agent Client Protocol destekleyen diğer editörler OpenCode'u opencode acp ile çalıştırır.", - features: { - "quick-launch": { - title: "Hızlı açılış", - body: "Cmd+Esc ya da Ctrl+Esc, OpenCode'u bölünmüş bir terminalde açar.", - }, - "new-session": { - title: "Yeni oturum", - body: "Cmd+Shift+Esc ya da Ctrl+Shift+Esc yeni bir oturum başlatır.", - }, - context: { - title: "Bağlam", - body: "Geçerli seçiminizi ya da sekmenizi OpenCode ile paylaşır.", - }, - "file-references": { - title: "Dosya referansı", - body: "Cmd+Option+K ya da Alt+Ctrl+K, @File#L37-42 ekler.", - }, - "installs-itself": { - title: "Kendini kurar", - body: "Eklemek için entegre terminalde opencode çalıştırın.", - }, - "acp-editors": { - title: "ACP editörleri", - body: "Zed, JetBrains IDE'leri, Avante.nvim ve CodeCompanion.nvim.", - }, - "open-vsx": { - title: "Open VSX", - body: "Cursor, Windsurf ve VSCodium için Open VSX'te de var.", - }, - "same-agent": { - title: "Aynı ajan", - body: "Terminalde çalıştırdığınız OpenCode, kodunuzun yanında.", - }, - }, - }, mini: { title: "OpenCode | Mini, ajan için minimal bir terminal arayüzü", description: @@ -1181,20 +1135,6 @@ export const content = { label: "SDK dokümanlarını okuyun", }, }, - ide: { - links: { - "vs-code-marketplace": { - label: "VS Code Marketplace", - }, - "open-vsx-cursor-windsurf-vscodium": { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - }, - }, - lead: "Editörünüzün entegre terminalinde opencode çalıştırın, eklenti kendini kursun ya da kendiniz kurun.", - more: { - label: "Zed, JetBrains IDE'leri ve diğer ACP editörlerini kurun", - }, - }, mini: { lead: "Mini, OpenCode CLI ile gelir. Bunlardan biriyle kurun, sonra opencode mini çalıştırın.", commands: { diff --git a/services/site/src/i18n/content/uk.ts b/services/site/src/i18n/content/uk.ts index f0c1e3f8fd1b..b6e783d04260 100644 --- a/services/site/src/i18n/content/uk.ts +++ b/services/site/src/i18n/content/uk.ts @@ -18,11 +18,6 @@ export const content = { action: "Встановити", }, sdk: { body: "Керуйте OpenCode зі своїх скриптів, CI-завдань та інструментів.", action: "Документація" }, - ide: { - name: "Розширення для IDE", - body: "Відкривайте OpenCode у VS Code, Cursor і Windsurf або в Zed і JetBrains IDE через ACP.", - action: "Встановити", - }, mini: { body: "Мінімальний термінальний інтерфейс. Відповіді виводяться в історію прокрутки, а внизу один рядок введення.", action: "Встановити", @@ -189,29 +184,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | Інтеграції з редакторами VS Code, Cursor і Zed", - description: - "Використовуйте OpenCode у своєму редакторі. Розширення для VS Code, Cursor, Windsurf і VSCodium, а opencode acp для Zed, JetBrains IDE та інших ACP-редакторів.", - intro: - "Використовуйте OpenCode у своєму редакторі. У VS Code, Cursor, Windsurf і VSCodium запустіть opencode у вбудованому терміналі, і розширення встановиться саме. Zed, JetBrains IDE та інші редактори з підтримкою Agent Client Protocol запускають OpenCode через opencode acp.", - features: { - "quick-launch": { - title: "Швидкий запуск", - body: "Cmd+Esc або Ctrl+Esc відкриває OpenCode в розділеному терміналі.", - }, - "new-session": { title: "Нова сесія", body: "Cmd+Shift+Esc або Ctrl+Shift+Esc починає ще одну сесію." }, - context: { title: "Контекст", body: "Передає в OpenCode поточне виділення або вкладку." }, - "file-references": { title: "Посилання на файли", body: "Cmd+Option+K або Alt+Ctrl+K вставляє @File#L37-42." }, - "installs-itself": { - title: "Ставиться саме", - body: "Запустіть opencode у вбудованому терміналі, щоб додати його.", - }, - "acp-editors": { title: "ACP-редактори", body: "Zed, JetBrains IDE, Avante.nvim і CodeCompanion.nvim." }, - "open-vsx": { title: "Open VSX", body: "Також в Open VSX для Cursor, Windsurf і VSCodium." }, - "same-agent": { title: "Той самий агент", body: "Той самий OpenCode, що й у терміналі, поруч із вашим кодом." }, - }, - }, mini: { title: "OpenCode | Mini, мінімальний термінальний інтерфейс агента", description: @@ -699,14 +671,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "Скрипт" } } }, sdk: { more: { label: "Документація SDK" } }, - ide: { - lead: "Запустіть opencode у вбудованому терміналі редактора, і розширення встановиться саме, або встановіть його вручну.", - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - more: { label: "Налаштування Zed, JetBrains IDE та інших ACP-редакторів" }, - }, mini: { lead: "Mini входить до OpenCode CLI. Встановіть його будь-яким із цих способів, потім запустіть opencode mini.", commands: { curl: { name: "Скрипт" } }, diff --git a/services/site/src/i18n/content/zh.ts b/services/site/src/i18n/content/zh.ts index b4ef5d55b3cb..0480f549cace 100644 --- a/services/site/src/i18n/content/zh.ts +++ b/services/site/src/i18n/content/zh.ts @@ -10,11 +10,6 @@ export const content = { mobile: { name: "Mobile", body: "无论身在何处,都能在手机上启动、引导和批准会话。", action: "下载" }, terminal: { name: "Terminal", body: "快速的终端界面,可在任意 shell、编辑器或远程服务器中使用。", action: "安装" }, sdk: { name: "SDK", body: "在您自己的脚本、CI 任务和工具中驱动 OpenCode。", action: "阅读文档" }, - ide: { - name: "IDE 扩展", - body: "在 VS Code、Cursor 和 Windsurf 中打开 OpenCode,或通过 ACP 在 Zed 和 JetBrains IDE 中使用。", - action: "安装", - }, mini: { name: "Mini", body: "极简的终端界面,回复直接输出到滚动记录中,下方只有一个提示词输入框。", @@ -125,23 +120,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | 适用于 VS Code、Cursor、Zed 等的 IDE 扩展", - description: - "在编辑器中使用 OpenCode。VS Code、Cursor、Windsurf 和 VSCodium 有专用扩展,Zed、JetBrains IDE 和其他 ACP 编辑器可使用 opencode acp。", - intro: - "在编辑器中使用 OpenCode。在 VS Code、Cursor、Windsurf 和 VSCodium 中,在集成终端里运行 opencode,扩展就会自动安装。Zed、JetBrains IDE 以及其他支持 Agent Client Protocol 的编辑器可通过 opencode acp 运行 OpenCode。", - features: { - "quick-launch": { title: "快速启动", body: "Cmd+Esc 或 Ctrl+Esc 在分屏终端中打开 OpenCode。" }, - "new-session": { title: "新会话", body: "Cmd+Shift+Esc 或 Ctrl+Shift+Esc 开启另一个会话。" }, - context: { title: "上下文", body: "将当前选中内容或标签页分享给 OpenCode。" }, - "file-references": { title: "文件引用", body: "Cmd+Option+K 或 Alt+Ctrl+K 插入 @File#L37-42。" }, - "installs-itself": { title: "自动安装", body: "在集成终端中运行 opencode 即可添加。" }, - "acp-editors": { title: "ACP 编辑器", body: "Zed、JetBrains IDE、Avante.nvim 和 CodeCompanion.nvim。" }, - "open-vsx": { title: "Open VSX", body: "也在 Open VSX 上提供,适用于 Cursor、Windsurf 和 VSCodium。" }, - "same-agent": { title: "同一个代理", body: "就是您在终端中运行的 OpenCode,就在代码旁边。" }, - }, - }, mini: { title: "OpenCode | Mini,代理的极简终端界面", description: @@ -600,14 +578,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "脚本" } } }, sdk: { more: { label: "阅读 SDK 文档" } }, - ide: { - links: { - "vs-code-marketplace": { label: "VS Code 扩展市场" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - lead: "在编辑器的集成终端中运行 opencode,扩展就会自动安装,也可以手动安装。", - more: { label: "设置 Zed、JetBrains IDE 和其他 ACP 编辑器" }, - }, mini: { commands: { curl: { name: "脚本" } }, lead: "Mini 随 OpenCode CLI 一起提供。用以下任一方式安装,然后运行 opencode mini。", diff --git a/services/site/src/i18n/content/zht.ts b/services/site/src/i18n/content/zht.ts index 8923a920beef..1f374b7fb5fb 100644 --- a/services/site/src/i18n/content/zht.ts +++ b/services/site/src/i18n/content/zht.ts @@ -14,11 +14,6 @@ export const content = { action: "安裝", }, sdk: { name: "SDK", body: "從你自己的腳本、CI 工作和工具驅動 OpenCode。", action: "閱讀文件" }, - ide: { - name: "IDE 擴充功能", - body: "在 VS Code、Cursor 和 Windsurf 中開啟 OpenCode,或透過 ACP 在 Zed 和 JetBrains IDE 中使用。", - action: "安裝", - }, mini: { name: "Mini", body: "極簡的終端機介面,回覆直接輸出到捲動紀錄中,下方只有一個提示詞輸入框。", @@ -129,23 +124,6 @@ export const content = { }, }, }, - ide: { - title: "OpenCode | 適用於 VS Code、Cursor、Zed 等的 IDE 擴充功能", - description: - "在編輯器中使用 OpenCode。VS Code、Cursor、Windsurf 和 VSCodium 有專用擴充功能,Zed、JetBrains IDE 和其他 ACP 編輯器可使用 opencode acp。", - intro: - "在編輯器中使用 OpenCode。在 VS Code、Cursor、Windsurf 和 VSCodium 中,於整合式終端機執行 opencode,擴充功能就會自動安裝。Zed、JetBrains IDE 以及其他支援 Agent Client Protocol 的編輯器可透過 opencode acp 執行 OpenCode。", - features: { - "quick-launch": { title: "快速啟動", body: "Cmd+Esc 或 Ctrl+Esc 在分割終端機中開啟 OpenCode。" }, - "new-session": { title: "新工作階段", body: "Cmd+Shift+Esc 或 Ctrl+Shift+Esc 開啟另一個工作階段。" }, - context: { title: "上下文", body: "將目前選取的內容或分頁分享給 OpenCode。" }, - "file-references": { title: "檔案參照", body: "Cmd+Option+K 或 Alt+Ctrl+K 插入 @File#L37-42。" }, - "installs-itself": { title: "自動安裝", body: "在整合式終端機中執行 opencode 即可加入。" }, - "acp-editors": { title: "ACP 編輯器", body: "Zed、JetBrains IDE、Avante.nvim 和 CodeCompanion.nvim。" }, - "open-vsx": { title: "Open VSX", body: "也在 Open VSX 上提供,適用於 Cursor、Windsurf 和 VSCodium。" }, - "same-agent": { title: "同一個代理", body: "就是你在終端機中執行的 OpenCode,就在程式碼旁邊。" }, - }, - }, mini: { title: "OpenCode | Mini,代理的極簡終端機介面", description: @@ -604,14 +582,6 @@ export const content = { productDownloads: { terminal: { commands: { curl: { name: "指令碼" } } }, sdk: { more: { label: "閱讀 SDK 文件" } }, - ide: { - links: { - "vs-code-marketplace": { label: "VS Code Marketplace" }, - "open-vsx-cursor-windsurf-vscodium": { label: "Open VSX (Cursor, Windsurf, VSCodium)" }, - }, - lead: "在編輯器的整合式終端機中執行 opencode,擴充功能就會自動安裝,也可以手動安裝。", - more: { label: "設定 Zed、JetBrains IDE 和其他 ACP 編輯器" }, - }, mini: { commands: { curl: { name: "指令碼" } }, lead: "Mini 隨 OpenCode CLI 一起提供。用以下任一方式安裝,然後執行 opencode mini。", diff --git a/services/site/src/i18n/stamps/ar.json b/services/site/src/i18n/stamps/ar.json index 1dd8209cab2c..6df337e7cfb4 100644 --- a/services/site/src/i18n/stamps/ar.json +++ b/services/site/src/i18n/stamps/ar.json @@ -422,25 +422,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -523,10 +504,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -534,9 +511,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/br.json b/services/site/src/i18n/stamps/br.json index 478432f8342e..881cbe41856b 100644 --- a/services/site/src/i18n/stamps/br.json +++ b/services/site/src/i18n/stamps/br.json @@ -439,25 +439,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -540,10 +521,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -551,9 +528,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/da.json b/services/site/src/i18n/stamps/da.json index ec4f1056e518..5261a77d1fd6 100644 --- a/services/site/src/i18n/stamps/da.json +++ b/services/site/src/i18n/stamps/da.json @@ -416,25 +416,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -517,10 +498,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -528,9 +505,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/de.json b/services/site/src/i18n/stamps/de.json index 84bc62fa2baf..604eba472238 100644 --- a/services/site/src/i18n/stamps/de.json +++ b/services/site/src/i18n/stamps/de.json @@ -416,25 +416,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -517,10 +498,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -528,9 +505,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/es.json b/services/site/src/i18n/stamps/es.json index 87ca349355c3..cedbaa34ff3b 100644 --- a/services/site/src/i18n/stamps/es.json +++ b/services/site/src/i18n/stamps/es.json @@ -417,25 +417,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -518,10 +499,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -529,9 +506,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/fr.json b/services/site/src/i18n/stamps/fr.json index cb24cbf9ea13..1ec63754db92 100644 --- a/services/site/src/i18n/stamps/fr.json +++ b/services/site/src/i18n/stamps/fr.json @@ -417,25 +417,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -518,10 +499,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -529,9 +506,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/it.json b/services/site/src/i18n/stamps/it.json index a1ef87c73157..9b1ef2d893f0 100644 --- a/services/site/src/i18n/stamps/it.json +++ b/services/site/src/i18n/stamps/it.json @@ -417,25 +417,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -518,10 +499,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -529,9 +506,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/ja.json b/services/site/src/i18n/stamps/ja.json index 8399df47c386..c2e2dff4fcd9 100644 --- a/services/site/src/i18n/stamps/ja.json +++ b/services/site/src/i18n/stamps/ja.json @@ -431,25 +431,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -532,10 +513,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -543,9 +520,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/ko.json b/services/site/src/i18n/stamps/ko.json index c9137fdd8a3f..2ac6cf9e270a 100644 --- a/services/site/src/i18n/stamps/ko.json +++ b/services/site/src/i18n/stamps/ko.json @@ -430,25 +430,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -531,10 +512,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -542,9 +519,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/no.json b/services/site/src/i18n/stamps/no.json index 84bc62fa2baf..604eba472238 100644 --- a/services/site/src/i18n/stamps/no.json +++ b/services/site/src/i18n/stamps/no.json @@ -416,25 +416,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -517,10 +498,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -528,9 +505,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/pl.json b/services/site/src/i18n/stamps/pl.json index 478432f8342e..881cbe41856b 100644 --- a/services/site/src/i18n/stamps/pl.json +++ b/services/site/src/i18n/stamps/pl.json @@ -439,25 +439,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -540,10 +521,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -551,9 +528,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/ru.json b/services/site/src/i18n/stamps/ru.json index 95ba231b3a5c..15de8b283bd4 100644 --- a/services/site/src/i18n/stamps/ru.json +++ b/services/site/src/i18n/stamps/ru.json @@ -422,25 +422,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -523,10 +504,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -534,9 +511,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/th.json b/services/site/src/i18n/stamps/th.json index 8399df47c386..c2e2dff4fcd9 100644 --- a/services/site/src/i18n/stamps/th.json +++ b/services/site/src/i18n/stamps/th.json @@ -431,25 +431,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -532,10 +513,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -543,9 +520,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/tr.json b/services/site/src/i18n/stamps/tr.json index 478432f8342e..881cbe41856b 100644 --- a/services/site/src/i18n/stamps/tr.json +++ b/services/site/src/i18n/stamps/tr.json @@ -439,25 +439,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -540,10 +521,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -551,9 +528,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/uk.json b/services/site/src/i18n/stamps/uk.json index 95ba231b3a5c..15de8b283bd4 100644 --- a/services/site/src/i18n/stamps/uk.json +++ b/services/site/src/i18n/stamps/uk.json @@ -422,25 +422,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -523,10 +504,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -534,9 +511,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mobile.action": "82r1papihj9v", diff --git a/services/site/src/i18n/stamps/zh.json b/services/site/src/i18n/stamps/zh.json index c9137fdd8a3f..2ac6cf9e270a 100644 --- a/services/site/src/i18n/stamps/zh.json +++ b/services/site/src/i18n/stamps/zh.json @@ -430,25 +430,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -531,10 +512,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -542,9 +519,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/i18n/stamps/zht.json b/services/site/src/i18n/stamps/zht.json index c9137fdd8a3f..2ac6cf9e270a 100644 --- a/services/site/src/i18n/stamps/zht.json +++ b/services/site/src/i18n/stamps/zht.json @@ -430,25 +430,6 @@ "content:productDetails.desktop.showcase.see-it-in-the-browser.body": "2buln409xzbcf", "content:productDetails.desktop.showcase.see-it-in-the-browser.title": "2mmw93f6d0399", "content:productDetails.desktop.title": "3cxw25x92nts6", - "content:productDetails.ide.description": "2c5jpf6nkm2kp", - "content:productDetails.ide.features.acp-editors.body": "180qlaoxl5833", - "content:productDetails.ide.features.acp-editors.title": "31s8p8q6ymzgf", - "content:productDetails.ide.features.context.body": "2wbxwyw94bgl3", - "content:productDetails.ide.features.context.title": "1vwldfdujb0cq", - "content:productDetails.ide.features.file-references.body": "1jqscu5udgcqt", - "content:productDetails.ide.features.file-references.title": "251wfv5xeufp8", - "content:productDetails.ide.features.installs-itself.body": "1sk8abc9q7nxb", - "content:productDetails.ide.features.installs-itself.title": "e46vj7lvoepf", - "content:productDetails.ide.features.new-session.body": "1qvk8m1ntl2av", - "content:productDetails.ide.features.new-session.title": "2sl16xnz1uzic", - "content:productDetails.ide.features.open-vsx.body": "12j4c1jaop4az", - "content:productDetails.ide.features.open-vsx.title": "igqaytjkrpfu", - "content:productDetails.ide.features.quick-launch.body": "1uh60ssrn16b7", - "content:productDetails.ide.features.quick-launch.title": "204nz15su0e43", - "content:productDetails.ide.features.same-agent.body": "p7j08ji8sg9q", - "content:productDetails.ide.features.same-agent.title": "kmzn7qnd7yog", - "content:productDetails.ide.intro": "271qphg1qblei", - "content:productDetails.ide.title": "1zm1b7kb60js7", "content:productDetails.mini.description": "3714rtad3ba0r", "content:productDetails.mini.features.agents.body": "8qc0ozd0eyze", "content:productDetails.mini.features.agents.title": "pg3iqndrugmx", @@ -531,10 +512,6 @@ "content:productDetails.terminal.showcase.mini.body": "3anqhzmo9dk3j", "content:productDetails.terminal.showcase.mini.title": "3hj3jur2ydhxv", "content:productDetails.terminal.title": "2nlihvubh60te", - "content:productDownloads.ide.lead": "37n0hw1e225ll", - "content:productDownloads.ide.links.open-vsx-cursor-windsurf-vscodium.label": "838kc7xxz8u5", - "content:productDownloads.ide.links.vs-code-marketplace.label": "26c237pckjysl", - "content:productDownloads.ide.more.label": "xentqbajo6qy", "content:productDownloads.mini.commands.curl.name": "1hn3ysltrmq5c", "content:productDownloads.mini.lead": "1vcqe5ltl2m2n", "content:productDownloads.sdk.more.label": "1gdlqxizo5kgp", @@ -542,9 +519,6 @@ "content:products.desktop.action": "82r1papihj9v", "content:products.desktop.body": "32p31e5qyhrc5", "content:products.desktop.name": "1nw8tp0d0ud3j", - "content:products.ide.action": "1yio8y7pfgnft", - "content:products.ide.body": "8gsgdoefxjfc", - "content:products.ide.name": "1j778ibkptu5g", "content:products.mini.action": "1yio8y7pfgnft", "content:products.mini.body": "3wzueuq89u04", "content:products.mini.name": "3hj3jur2ydhxv", diff --git a/services/site/src/lib/download-content.ts b/services/site/src/lib/download-content.ts index dd088aa03983..48f73b424aa3 100644 --- a/services/site/src/lib/download-content.ts +++ b/services/site/src/lib/download-content.ts @@ -1,7 +1,5 @@ import { - acpDocs, androidSoon, - extensions, installs, mobileStores, sdkDocs, @@ -94,27 +92,13 @@ export function productDownloads(slug: PageSlug, route: (path: string) => string ? { ...none, commands: installs } : slug === "sdk" ? { ...none, commands: sdkInstalls, more: { label: "Read the SDK docs", href: route(sdkDocs) } } - : slug === "ide" + : slug === "mini" ? { ...none, - lead: "Run opencode in your editor's integrated terminal and the extension installs itself, or install it yourself.", - links: [ - { label: "VS Code Marketplace", href: extensions.href, external: true }, - { - label: "Open VSX (Cursor, Windsurf, VSCodium)", - href: "https://open-vsx.org/extension/sst-dev/opencode", - external: true, - }, - ], - more: { label: "Set up Zed, JetBrains IDEs and other ACP editors", href: route(acpDocs) }, + lead: "Mini comes with the OpenCode CLI. Install it with any of these, then run opencode mini.", + commands: [...installs, { id: "run", command: "opencode mini" }], } - : slug === "mini" - ? { - ...none, - lead: "Mini comes with the OpenCode CLI. Install it with any of these, then run opencode mini.", - commands: [...installs, { id: "run", command: "opencode mini" }], - } - : none + : none return result } diff --git a/services/site/src/lib/funnel-config.ts b/services/site/src/lib/funnel-config.ts index 0d36eaf1038a..2e128bb612b0 100644 --- a/services/site/src/lib/funnel-config.ts +++ b/services/site/src/lib/funnel-config.ts @@ -9,7 +9,6 @@ const pages = new Set([ "terminal", "mobile", "sdk", - "ide", "mini", "extensions", "changelog", diff --git a/services/site/src/lib/legacy.ts b/services/site/src/lib/legacy.ts index e418e31f35e8..401387f54e21 100644 --- a/services/site/src/lib/legacy.ts +++ b/services/site/src/lib/legacy.ts @@ -50,6 +50,10 @@ export function legacyRedirect(request: Legacy): Response | undefined { const share = request.path.match(/^\/s\/([^/]+)\/?$/) if (share) return redirect(301, `https://opncd.ai/share/${share[1]}`) + // The IDE extensions page, removed in Nov 2026: its V1 docs page covers the extensions. Old links and + // search results. + if (/^\/ide\/?$/.test(request.path) && read) return redirect(301, `/v1/docs/ide/${request.search}`) + // The V2 docs' first address, before they moved to /docs in Nov 2026. Apps up to v2.2.5 (Help menu, // settings links, the opencode skill), the READMEs and install script of those releases, search // engines and outside links. Pages, Markdown twins and the docs' files (llms.txt, the sitemap, diff --git a/services/site/src/lib/media.ts b/services/site/src/lib/media.ts index d59cbca0a108..f287bf0655b8 100644 --- a/services/site/src/lib/media.ts +++ b/services/site/src/lib/media.ts @@ -9,6 +9,13 @@ export const mediaBase = "/files/site/2026-11" /** File types that live in the files bucket rather than in the Worker's static assets. */ export const mediaFile = /\.(mp4|webm|mov|mp3|wav|ogg|m4a|zip|glb|gltf)$/i +/** + * Whether a file under public/ (its path from there) goes to the files bucket. The link-card videos + * script/og.ts writes to og/ (og:video, under 100 kB each) are the exception: they ship as static + * assets with the cards that name them. + */ +export const inBucket = (file: string) => mediaFile.test(file) && !/^og[\\/]/.test(file) + /** The files-bucket URL for a media site path, for example `mediaUrl("/arcade3d/cabinet.glb")`. Other paths pass through. */ export function mediaUrl(path: string) { if (!path.startsWith("/") || path.startsWith(mediaBase) || !mediaFile.test(path.split(/[?#]/)[0])) return path diff --git a/services/site/src/lib/og.ts b/services/site/src/lib/og.ts index 039cde2bccea..59494656efa8 100644 --- a/services/site/src/lib/og.ts +++ b/services/site/src/lib/og.ts @@ -1,5 +1,8 @@ -/** A page's link preview card: its file (a site path) and alt text, rendered by script/og.ts. */ -export type OgImage = { src: string; alt: string } +/** + * A page's link preview card: its file (a site path) and alt text, rendered by script/og.ts. + * Cards from OG Studio can also have a video (og:video) and a translated image for each locale. + */ +export type OgImage = { src: string; alt: string; video?: string; locales?: Record } // script/og.ts writes og-images.json before `vite dev` and `vite build`. A glob, not an import, so // typecheck and tests also pass in a fresh checkout where the file does not exist yet. @@ -9,7 +12,7 @@ const cards: Record = const fallback: OgImage = { src: "/social-share.png", alt: "OpenCode" } /** - * The card for a page, by its English path; every locale shares the English card. script/og.ts + * The card for a page, by its English path. ShareMeta picks the locale's image when there is one. script/og.ts * renders one for every page that has ShareMeta, and a page it doesn't know gets the home card. */ export function ogImage(path: string): OgImage { diff --git a/services/site/src/lib/product-markdown.ts b/services/site/src/lib/product-markdown.ts index b5deceab3e2c..fe19726a9c28 100644 --- a/services/site/src/lib/product-markdown.ts +++ b/services/site/src/lib/product-markdown.ts @@ -1,8 +1,6 @@ import { anomalyApps, anomalyProducts } from "~/component/site/links" import { extensionPages, type ExtensionSlug } from "~/component/site/extension-data" import { - acpDocs, - extensions, installs, mobileStores, productAreas, @@ -126,8 +124,6 @@ export function productActionMarkdown(slug: PageSlug, context: MarkdownContext) ).trimEnd() if (slug === "mobile") return `Download: ${mobileStores.map((store) => storeMarkdown({ ...store, href: store.href.startsWith("/") ? context.route(store.href) : store.href })).join(", ")}` - if (slug === "ide") - return `Install: ${link("VS Code Marketplace", extensions.href)}, or run \`opencode\` in your editor's integrated terminal. ACP editors: ${link("ACP docs", context.route(acpDocs))}` if (slug === "terminal" || slug === "mini") return blocks( "Install with any of these:", diff --git a/services/site/src/routes/ide.tsx b/services/site/src/routes/ide.tsx deleted file mode 100644 index c77466c4f6a1..000000000000 --- a/services/site/src/routes/ide.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { ProductPage } from "~/component/site/product-page" - -export default function Page() { - return -} diff --git a/services/site/src/static/routes.ts b/services/site/src/static/routes.ts index febd0f59d1b9..3e55189aeadb 100644 --- a/services/site/src/static/routes.ts +++ b/services/site/src/static/routes.ts @@ -13,7 +13,6 @@ export const staticPaths = [ "/terminal", "/mobile", "/sdk", - "/ide", "/mini", "/legal", "/legal/privacy-policy", diff --git a/services/site/test/funnel.test.ts b/services/site/test/funnel.test.ts index 4eb96460f636..a58e3db746ec 100644 --- a/services/site/test/funnel.test.ts +++ b/services/site/test/funnel.test.ts @@ -33,7 +33,6 @@ const surfaces: Record = { "/desktop": "www-desktop", "/devices": undefined, "/font": "www-font", - "/ide": "www-ide", "/legal": "www-legal", "/legal/privacy-policy": "www-legal", "/legal/terms-of-service": "www-legal", diff --git a/services/site/test/legacy.test.ts b/services/site/test/legacy.test.ts index ae1d524e14bc..78e6287872c0 100644 --- a/services/site/test/legacy.test.ts +++ b/services/site/test/legacy.test.ts @@ -46,7 +46,7 @@ describe("legacy redirects", () => { expect(get("/pricing", { locale: "de" })).toBeUndefined() }) - test("the old dashboard, Black, stats and share links", () => { + test("the old dashboard, Black, stats, share and IDE links", () => { const auth = get("/workspace/wrk_123/go", { method: "POST", locale: "de" }) expect(auth?.status).toBe(302) expect(auth?.headers.get("Location")).toBe("https://opencode.ai/console/login") @@ -63,6 +63,8 @@ describe("legacy redirects", () => { const share = get("/s/abc123") expect(share?.status).toBe(301) expect(share?.headers.get("Location")).toBe("https://opncd.ai/share/abc123") + expect(get("/ide/", { locale: "de" })?.headers.get("Location")).toBe("/v1/docs/ide/") + expect(get("/ideas")).toBeUndefined() }) test("the V2 docs' old /v2 URLs move to /docs permanently, keeping the path and query", () => {