Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): upgrade CPA to patched v7.3.16 (#2200)
Call Whited9d4c4df55a2
diff --git a/.github/workflows/model-hub-engine-release-guard.yml b/.github/workflows/model-hub-engine-release-guard.ymlindex a2183e9ae..eca79dfdc 100644--- a/.github/workflows/model-hub-engine-release-guard.yml+++ b/.github/workflows/model-hub-engine-release-guard.yml@@ -5,6 +5,8 @@ on:branches: [master]paths:- "vibe/model_hub_runtime/cliproxyapi_manifest.json"+ - "patches/model-hub-cpa-v7.3.16/**"+ - "scripts/build_model_hub_engine.py"- "scripts/model_hub_engine_release_guard.py"- ".github/workflows/model-hub-engine-release-guard.yml"schedule:@@ -21,8 +23,121 @@ concurrency:cancel-in-progress: falsejobs:+ build-patched-source:+ name: Build patched source assets+ if: github.event_name == 'workflow_dispatch'+ runs-on: ubuntu-latest+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5++ - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6+ with:+ go-version: "1.26.0"++ - name: Build and verify patched source assets+ run: |+ python3 scripts/model_hub_engine_release_guard.py fetch-source \+ --output-dir "$RUNNER_TEMP/model-hub-engine-patched"++ - name: Upload patched source assets+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: model-hub-engine-patched-source-${{ github.sha }}+ path: ${{ runner.temp }}/model-hub-engine-patched+ if-no-files-found: error+ retention-days: 90+ compression-level: 0++ publish-patched-source:+ name: Publish patched source assets+ if: github.event_name == 'workflow_dispatch'+ needs: build-patched-source+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5++ - name: Download verified patched source assets+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8+ with:+ name: model-hub-engine-patched-source-${{ github.sha }}+ path: ${{ runner.temp }}/model-hub-engine-patched++ - name: Verify patched source assets+ run: |+ python3 scripts/model_hub_engine_release_guard.py verify \+ --asset-dir "$RUNNER_TEMP/model-hub-engine-patched"++ - name: Publish or verify the pinned release+ env:+ GH_TOKEN: ${{ github.token }}+ shell: bash+ run: |+ set -euo pipefail+ manifest="vibe/model_hub_runtime/cliproxyapi_manifest.json"+ release_tag="$(jq -er '.asset_release_tag' "$manifest")"+ version="$(jq -er '.version' "$manifest")"+ asset_dir="$RUNNER_TEMP/model-hub-engine-patched"+ assets=("$asset_dir"/*)++ if gh release view "$release_tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then+ is_draft="$(+ gh release view "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ --json isDraft \+ --jq '.isDraft'+ )"+ declare -A existing_assets=()+ while IFS= read -r asset_name; do+ existing_assets["$asset_name"]=1+ done < <(+ gh release view "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ --json assets \+ --jq '.assets[].name'+ )++ missing_assets=()+ for asset in "${assets[@]}"; do+ asset_name="${asset##*/}"+ if [ -z "${existing_assets[$asset_name]:-}" ]; then+ missing_assets+=("$asset")+ fi+ done+ if [ "${#missing_assets[@]}" -gt 0 ]; then+ gh release upload "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ "${missing_assets[@]}"+ else+ echo "All expected release asset names already exist; preserving their bytes."+ fi+ if [ "$is_draft" = "true" ]; then+ python3 scripts/model_hub_engine_release_guard.py publish-draft \+ --repo "$GITHUB_REPOSITORY" \+ --asset-dir "$asset_dir"+ fi+ else+ gh release create "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ --target "$GITHUB_SHA" \+ --latest=false \+ --title "Avibe Model Hub engine $version" \+ --notes "Avibe-managed patched CPA assets." \+ "${assets[@]}"+ fi+ python3 scripts/model_hub_engine_release_guard.py fetch \+ --output-dir "$RUNNER_TEMP/model-hub-engine-published"+guard:name: Verify and recover pinned assets+ if: >-+ always() &&+ (github.event_name != 'workflow_dispatch' ||+ needs.publish-patched-source.result == 'success')+ needs: [publish-patched-source]runs-on: ubuntu-latesttimeout-minutes: 20steps:@@ -92,6 +207,12 @@ jobs:assets=("$RESTORE_DIR"/*)if gh release view "$release_tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then+ is_draft="$(+ gh release view "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ --json isDraft \+ --jq '.isDraft'+ )"declare -A existing_assets=()while IFS= read -r asset_name; doexisting_assets["$asset_name"]=1@@ -110,16 +231,25 @@ jobs:fidoneif [ "${#missing_assets[@]}" -eq 0 ]; then- echo "::error::Every expected asset name exists but verification failed; refusing to overwrite pinned bytes."- exit 1+ if [ "$is_draft" != "true" ]; then+ echo "::error::Every expected asset name exists but verification failed; refusing to overwrite pinned bytes."+ exit 1+ fi+ echo "All expected names exist on the draft; verifying its bytes before publication."+ else+ gh release upload "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ "${missing_assets[@]}"+ fi+ if [ "$is_draft" = "true" ]; then+ python3 scripts/model_hub_engine_release_guard.py publish-draft \+ --repo "$GITHUB_REPOSITORY" \+ --asset-dir "$RESTORE_DIR"fi- gh release upload "$release_tag" \- --repo "$GITHUB_REPOSITORY" \- "${missing_assets[@]}"elsegh release create "$release_tag" \--repo "$GITHUB_REPOSITORY" \- --verify-tag \+ --target "$GITHUB_SHA" \--latest=false \--title "Avibe Model Hub engine $version" \--notes "Avibe-managed CPA assets recovered from a manifest-verified backup." \diff --git a/docs/plans/model-hub-cpa-7.3.16.md b/docs/plans/model-hub-cpa-7.3.16.mdnew file mode 100644index 000000000..d1c3eebce--- /dev/null+++ b/docs/plans/model-hub-cpa-7.3.16.md@@ -0,0 +1,176 @@+# Model Hub CPA v7.3.16 Upgrade++Status: release assets published and verified; login-only compatibility in review,+2026-09-26. The packaged target is an Avibe-owned v7.3.16 build. The installed+runtime was not upgraded or restarted in this change.++## Change contract++Upgrade Model Hub from CLIProxyAPI v7.2.149 to v7.3.16 at source commit+`c404af96ebacedf8168b3c2bdbf4449a21cd1c1e`. Publish the four-platform+Avibe-owned assets as `model-hub-engine-v7.3.16-3` before adoption. Preserve+the existing platform matrix and the [dependency lifecycle](model-hub-cpa-dependency.md).++The upgrade must preserve:++- Exact Source, credential, and upstream model selection, including unlisted+ models. Avibe remains the owner of cross-Source fallback.+- Management API credential inventory and OAuth flow identities.+- Buffered and streaming Messages, Chat Completions, and Responses behavior,+ including tool calls, usage, cancellation, and active-stream reload.+- Verified atomic installation, previous-generation retention, and separation+ between installing the dependency and starting the engine.++## Compatibility ownership++### Claude credential filenames++CPA v7.3.16 changes a Claude filename only when saving a new OAuth login.+The email-only name `[email protected]` can become+`[email protected]`; an account-hashed name can likewise+precede an organization-hashed name. Existing files remain usable without+relogin. Startup, restart, token refresh, upload and watcher loading do not+generate a new Claude filename.++The pinned upstream call graph at `c404af96ebacedf8168b3c2bdbf4449a21cd1c1e`+is the evidence for this boundary:++- `internal/api/handlers/management/auth_files_provider_oauth.go:169-180`+ computes the canonical name after login and calls `saveTokenRecord`.+- `internal/api/handlers/management/auth_files_fields.go:945-980` finds the+ legacy credential, merges its metadata, saves the new file, then deletes the+ predecessor. `sdk/auth/manager.go:90-110` does the same for CLI login.+ These are the only callers of `FindMatchingLegacyCredential`.+- `sdk/cliproxy/auth/metadata_merge.go:24-53` preserves non-token metadata,+ including Avibe's prefix; `internal/auth/claude/token.go:73-100` writes it.+- `sdk/auth/filestore.go:417-446` resolves persistence to the existing path or+ filename. `internal/watcher/synthesizer/file.go:97,199` loads the existing+ basename; `internal/api/handlers/management/auth_files_crud.go:261-275`+ uploads under the supplied name. None invokes Claude filename generation.++Avibe therefore applies one rule, only in `_complete_oauth`, after identifying+the login's resulting auth file and before binding or cleanup:++- A file carrying an existing Claude credential's exact Avibe prefix belongs+ to that credential. Update only its `auth_name`; preserve ref, Source and+ prefix. Account email/organization/account UUID fields are not ownership keys.+- The normal same-Source reauthentication and foreign-Source rejection then+ apply. A migrated file owned by another Source is retained as+ `FOREIGN_SOURCE_REF`, never deleted merely because its filename is new.+- Multiple credential owners or a still-present predecessor are ambiguous:+ completion fails with `binding_failed`, retains `UNKNOWN`, and changes or+ deletes neither grant. If CPA itself reports the failed deletion as an OAuth+ error, the existing `upstream_failed`/unknown-retention path applies.++#### Circuit-breaker diagnosis and scope decision++The earlier review loop assumed migration could happen during any lifecycle+operation. That premise created global reconciliation passes, startup retry+flags and account-identity matching, each with additional failure boundaries.+Direct inspection of the pinned upstream disproved the premise. The unpushed+activation/observation follow-up was withdrawn, not extended.++Remove the global pass, completeness/isolation state, `oauth_identity`+seeding/comparison, and reconciliation from startup, native activation,+revocation, validation, discovery, quota and labels. Those paths return to the+base behavior. Keep only the login-completion rule and its consuming tests.+The manifest, CPA patch, builder, workflow and release guard are frozen.++New findings must establish their trigger against the pinned upstream before+changing code. A proposal to reintroduce general reconciliation or identity+matching, or change the release pipeline, requires a new scope decision.++### Release publication and provenance boundary++Review through `df6fef95c` exposed another recurrence: both publication and+backup recovery implemented draft repair independently, and name-intersection+replacement could never recover an unexpected asset. Both jobs now invoke one+guard-owned draft operation. It verifies the local pinned set, requires an+unpublished release, downloads and verifies the remote set, replaces the entire+draft set when it is unreadable or mismatched, and re-downloads before publication.+This includes interrupted uploads whose listed assets cannot be downloaded;+an already-public release is never rewritten by this operation.++The consuming publication test covers valid, missing, extra and corrupt draft+assets, a corrupt replacement upload, transient and persistent download failures,+and refusal to modify a published release. The old expected-name-only replacement fails the+extra-asset case; the exact-set replacement passes it.++The builder resolves `build.patch` from the manifest, or accepts a local copy+only when its bytes match `build.patch_sha256`. It validates this input before+checkout/build, independently of output hashes: a provenance-only patch change+can leave all binary/archive hashes unchanged and must still be rejected.++### Native Chat token fields++Stock v7.3.16 normalizes `max_completion_tokens` to `max_tokens` when the+per-model `use-max-completion-tokens` option is false. That breaks upstreams+which accept only the caller's native field. Avibe owns this boundary, so the+release assets carry the minimal patch in+`patches/model-hub-cpa-v7.3.16/openai-compat-native-token-field.patch`.++The patched default preserves whichever token-limit field the caller supplied+in both buffered and streaming Chat requests. An explicit true option retains+CPA's canonical `max_completion_tokens` conversion.++## Validation++- Build all four assets from the exact upstream source with the Avibe-owned+ patch, record archive and executable digests, and verify the complete+ manifest asset set with the release guard. The build metadata records only+ host-independent toolchain identity, and the builder validates against the+ checked-in manifest rather than self-verifying a generated one.+- Update the frozen packaged-manifest test together with the production pin.+- Run focused runtime, OAuth/source-identity, release-guard, dependency,+ release-helper, routing, lint, and diff checks.+- Exercise the patched engine with synthetic credentials and loopback+ upstreams through the isolated Model Hub wire harness.+- Bind review and CI evidence to the PR's current head. Do not merge, deploy,+ or restart the user's runtime as part of this change.++## Known by design++- The release assets are Avibe-owned patched builds, not byte-for-byte copies+ of the upstream v7.3.16 archives.+- No new provider entry points or changes to the supported platform matrix.+- No automatic tracking of upstream `latest`.+- Avibe's random prefix is an ownership tag inside its managed auth directory,+ not a tamper-proof signature. Arbitrary external replacement of an account+ while copying another credential's prefix is outside this upgrade's scope;+ no account-identity registry or observational-read hardening is introduced.+- Ambiguous or interrupted logins are retained, not automatically repaired at+ startup. Ordinary legacy files do not need a migration pass to remain usable.+- The capability-driven reasoning intent gap remains a separate existing issue;+ this upgrade does not claim to repair it.+- Synthetic wire tests do not establish live vendor OAuth login/refresh or+ external provider availability.++## Evidence and limits++- The narrowed regressions exercise same-Source login, foreign-Source login,+ predecessor retention, PATCH failure after migration, and unchanged legacy+ use without relogin. The four login cases failed on the base implementation+ for new-prefix rebinding or deletion of the only surviving grant.+- Earlier global-reconciliation test counts are not evidence for this narrowed+ implementation. Run its focused suites and obtain fresh exact-head hosted+ review/CI before close-out.+- The narrowed implementation passed 1,368 tests across runtime, OAuth, native+ takeover, Source identity, quota, API, build, release guard and login migration,+ plus changed-file Ruff and diff checks. All state is test-owned and synthetic.+- Workflow run `36213312402` built and published `model-hub-engine-v7.3.16-3`+ from `df6fef95c078536c4406d1357ea676daaba7160b`. The first guard hit a+ transient public-download 404; failed-job rerun attempt 2 completed+ successfully, including the verified backup. An independent public download+ subsequently verified all nine assets against the unchanged packaged manifest.+- The repeated release workflow `36214619870` succeeded on `fbba8aa10` with+ all three jobs successful; that head's lint run `36214572839` also completed+ with all 18 checks successful. Neither result substitutes for review/CI on+ the next ownership-fix head.+- The four patched archive sizes, archive SHA-256 values, and extracted binary+ SHA-256 values are recorded in the packaged manifest.+- The patch is limited to the helper shared by CPA's buffered and streaming+ OpenAI-compatible Chat paths. The Claude migration remains in Avibe's state+ layer rather than in the CPA binary.+- The existing old-version references in historical Model Hub investigations+ remain historical evidence and are not updated to imply those experiments+ ran against v7.3.16.diff --git a/docs/plans/model-hub-cpa-dependency.md b/docs/plans/model-hub-cpa-dependency.mdindex 49b4ec87c..27d6ef3bd 100644--- a/docs/plans/model-hub-cpa-dependency.md+++ b/docs/plans/model-hub-cpa-dependency.md@@ -59,11 +59,16 @@ Updating CPA for an Avibe release requires changing the packaged manifest in thesame change as its frozen contract test. The release tag and source commit arefixed, and every supported archive records its published byte size, archiveSHA-256, and extracted binary SHA-256. The verified upstream bytes are published-under an Avibe-owned release tag before the manifest is pinned. A scheduled-guard verifies that release and preserves a manifest-keyed backup that can-restore missing assets without overwriting a mismatched asset. For this change,-the reviewed target is CLIProxyAPI `v7.2.149` at source commit-`2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`.+ under an Avibe-owned release tag before the manifest is pinned. For patched+ dependencies, the assets are built from the reviewed source and patch before+ publication. A scheduled guard verifies that release and preserves a+ manifest-keyed backup that can restore missing assets without overwriting a+ mismatched asset. For this change,+the reviewed target is Avibe-owned CLIProxyAPI `v7.3.16` at source commit+`c404af96ebacedf8168b3c2bdbf4449a21cd1c1e`. The release assets are built+from that exact upstream source with the compatibility patch recorded in+`patches/model-hub-cpa-v7.3.16/`; the packaged manifest records the resulting+archive and binary digests.## Acceptance Criteriadiff --git a/patches/model-hub-cpa-v7.3.16/README.md b/patches/model-hub-cpa-v7.3.16/README.mdnew file mode 100644index 000000000..6ab8d4a15--- /dev/null+++ b/patches/model-hub-cpa-v7.3.16/README.md@@ -0,0 +1,45 @@+# Avibe-owned CPA v7.3.16 compatibility patch++This directory records the small source patch carried by Avibe's+`model-hub-engine-v7.3.16-3` build.++Base:++- Repository: `router-for-me/CLIProxyAPI`+- Release: `v7.3.16`+- Source commit: `c404af96ebacedf8168b3c2bdbf4449a21cd1c1e`++## Contract++Avibe owns the OpenAI-compatible Source boundary. When an incoming Chat+request contains `max_completion_tokens`, or `max_tokens`, the engine must+preserve that caller-selected field unless Avibe explicitly selects the+`use-max-completion-tokens` compatibility mode for a model. The stock+v7.3.16 default rewrites the former field to the latter, which breaks+upstreams that accept only the native field.++The patch therefore makes the stock `false` path a preservation path. The+existing explicit `true` path still canonicalizes to+`max_completion_tokens`. Avibe does not set the option today, so both+buffered and streaming requests retain their native token-limit field.++The patch is intentionally limited to the helper used by both OpenAI Chat+execution paths. Claude filename migration is handled in Avibe's credential+state layer and is not encoded in the CPA binary.++## Rebuild++The repository-owned release path checks out `source_sha`, applies this patch,+builds all four supported targets with `CGO_ENABLED=0`, packages deterministic+archives, and verifies the generated bytes against the checked-in manifest+before publication:++```sh+python3 scripts/model_hub_engine_release_guard.py fetch-source \+ --output-dir /tmp/model-hub-engine-patched+```++The same command is available from the manual Model Hub release-guard+workflow. Its uploaded artifact is the source-built publication input; the+runtime manifest is updated only after the generated bytes and release assets+have been reviewed.diff --git a/patches/model-hub-cpa-v7.3.16/openai-compat-native-token-field.patch b/patches/model-hub-cpa-v7.3.16/openai-compat-native-token-field.patchnew file mode 100644index 000000000..229abda3c--- /dev/null+++ b/patches/model-hub-cpa-v7.3.16/openai-compat-native-token-field.patch@@ -0,0 +1,20 @@+diff --git a/internal/runtime/executor/helps/openai_compat_max_tokens.go b/internal/runtime/executor/helps/openai_compat_max_tokens.go+index bceddd20..5ba754b0 100644+--- a/internal/runtime/executor/helps/openai_compat_max_tokens.go++++ b/internal/runtime/executor/helps/openai_compat_max_tokens.go+@@ -55,6 +55,13 @@ func NormalizeOpenAIMaxTokens(payload []byte, useMaxCompletionTokens bool) []byte+ if !hasMaxTokens && !hasMaxCompletionTokens {+ return payload+ }+++ // Avibe leaves the option at its zero value so the caller's native field++ // reaches the upstream unchanged. An explicit true still opts into the++ // canonical max_completion_tokens spelling below.++ if !useMaxCompletionTokens {++ return payload++ }+++ if useMaxCompletionTokens {+ if hasMaxTokens && !hasMaxCompletionTokens {+ val := gjson.GetBytes(payload, "max_tokens")+ if val.Raw != "" {diff --git a/scripts/build_model_hub_engine.py b/scripts/build_model_hub_engine.pynew file mode 100644index 000000000..38a9f876d--- /dev/null+++ b/scripts/build_model_hub_engine.py@@ -0,0 +1,370 @@+#!/usr/bin/env python3+"""Build the Avibe-owned Model Hub engine from a pinned patched source tree."""++from __future__ import annotations++import argparse+import gzip+import hashlib+import io+import json+import os+import platform+import re+import shutil+import subprocess+import tarfile+import tempfile+from pathlib import Path+from typing import Any, Mapping, Sequence++REPO_ROOT = Path(__file__).resolve().parents[1]+DEFAULT_MANIFEST = REPO_ROOT / "vibe" / "model_hub_runtime" / "cliproxyapi_manifest.json"+DEFAULT_SOURCE_REPOSITORY = "https://github.com/router-for-me/CLIProxyAPI.git"++TARGETS = {+ "darwin-arm64": ("darwin", "arm64", "darwin_aarch64"),+ "darwin-x64": ("darwin", "amd64", "darwin_amd64"),+ "linux-amd64": ("linux", "amd64", "linux_amd64"),+ "linux-arm64": ("linux", "arm64", "linux_aarch64"),+}+ARCHIVE_MEMBERS = ("cli-proxy-api", "LICENSE", "README.md", "README_CN.md", "config.example.yaml")+++class BuildError(RuntimeError):+ """Raised when a pinned Model Hub source build cannot be trusted."""+++def _go_toolchain_version(output: str) -> str:+ fields = output.split()+ if len(fields) < 3 or fields[:2] != ["go", "version"] or not fields[2].startswith("go"):+ raise BuildError("Go toolchain identity is unreadable")+ if re.fullmatch(r"go[0-9]+(?:\.[0-9]+){1,2}", fields[2]) is None:+ raise BuildError("Go toolchain version is not stable")+ return fields[2]+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _run(+ command: Sequence[str],+ *,+ cwd: Path | None = None,+ env: Mapping[str, str] | None = None,+) -> str:+ try:+ result = subprocess.run(+ list(command),+ cwd=cwd,+ env=dict(env) if env is not None else None,+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ )+ except OSError as exc:+ raise BuildError(f"unable to run {' '.join(command)}: {exc}") from exc+ if result.returncode:+ raise BuildError(+ f"command failed ({result.returncode}): {' '.join(command)}\n{result.stdout.strip()}"+ )+ return result.stdout+++def _load_manifest(path: Path) -> dict[str, Any]:+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise BuildError(f"cannot read Model Hub engine manifest: {exc}") from exc+ if not isinstance(payload, dict):+ raise BuildError("Model Hub engine manifest must be an object")+ required = ("version", "source_sha", "source_url", "release_tag", "asset_release_tag", "assets")+ if any(not isinstance(payload.get(key), str) or not payload[key] for key in required[:-1]):+ raise BuildError("Model Hub engine manifest has incomplete source identity")+ if not isinstance(payload["assets"], list):+ raise BuildError("Model Hub engine manifest assets must be a list")+ if {item.get("platform") for item in payload["assets"] if isinstance(item, dict)} != set(TARGETS):+ raise BuildError("Model Hub engine manifest platform set is invalid")+ return payload+++def _checkout_source(+ destination: Path,+ *,+ repository: str,+ source_sha: str,+) -> None:+ destination.mkdir(parents=True, exist_ok=False)+ _run(["git", "init", "--quiet", str(destination)])+ _run(["git", "-C", str(destination), "remote", "add", "origin", repository])+ _run(+ ["git", "-C", str(destination), "fetch", "--depth=1", "origin", source_sha],+ )+ _run(["git", "-C", str(destination), "checkout", "--quiet", "--detach", "FETCH_HEAD"])+ actual = _run(["git", "-C", str(destination), "rev-parse", "HEAD"]).strip()+ if actual != source_sha:+ raise BuildError(f"source checkout resolved {actual}, expected {source_sha}")+++def _prepare_source(+ source_root: Path,+ *,+ repository: str,+ source_sha: str,+ patch_path: Path,+) -> Path:+ checkout = source_root / "source"+ _checkout_source(checkout, repository=repository, source_sha=source_sha)+ if not patch_path.is_file() or patch_path.is_symlink():+ raise BuildError("Model Hub compatibility patch is missing or unsafe")+ _run(["git", "apply", "--whitespace=error", str(patch_path)], cwd=checkout)+ return checkout+++def _archive(+ source: Path,+ destination: Path,+ *,+ source_date_epoch: int,+) -> None:+ destination.parent.mkdir(parents=True, exist_ok=True)+ with destination.open("wb") as raw:+ with gzip.GzipFile(fileobj=raw, mode="wb", filename="", mtime=0) as compressed:+ with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as bundle:+ for member_name in ARCHIVE_MEMBERS:+ path = source / member_name+ if not path.is_file() or path.is_symlink():+ raise BuildError(f"source build is missing a safe archive member: {member_name}")+ data = path.read_bytes()+ member = tarfile.TarInfo(member_name)+ member.size = len(data)+ member.mode = 0o755 if member_name == "cli-proxy-api" else 0o644+ member.mtime = source_date_epoch+ member.uid = 0+ member.gid = 0+ member.uname = ""+ member.gname = ""+ bundle.addfile(member, io.BytesIO(data))+++def _asset_name(version: str, platform: str) -> str:+ return f"CLIProxyAPI_{version.removeprefix('v')}_{TARGETS[platform][2]}.tar.gz"+++def _native_target() -> str | None:+ goos = {"Darwin": "darwin", "Linux": "linux"}.get(platform.system())+ goarch = {+ "aarch64": "arm64",+ "amd64": "amd64",+ "arm64": "arm64",+ "x86_64": "amd64",+ }.get(platform.machine().lower())+ if goos is None or goarch is None:+ return None+ return next(+ (+ target+ for target, (target_goos, target_goarch, _asset_arch) in TARGETS.items()+ if target_goos == goos and target_goarch == goarch+ ),+ None,+ )+++def _verify_built_binary(+ binary: Path,+ *,+ version: str,+ target: str,+ checkout: Path,+) -> None:+ try:+ binary_bytes = binary.read_bytes()+ except OSError as exc:+ raise BuildError(f"cannot read built Model Hub binary: {exc}") from exc+ if version.encode("ascii") not in binary_bytes:+ raise BuildError(f"built Model Hub binary does not contain pinned version: {target}")++ if target != _native_target():+ return+ output = _run([str(binary), "--help"], cwd=checkout)+ match = re.search(r"CLIProxyAPI Version:\s*([^,\s]+)", output)+ if match is None or match.group(1) != version:+ reported = match.group(1) if match is not None else "unreadable"+ raise BuildError(+ f"built Model Hub binary reported {reported}, expected {version}: {target}"+ )+++def build_source_release(+ manifest_path: Path,+ output_dir: Path,+ *,+ source_repository: str = DEFAULT_SOURCE_REPOSITORY,+ patch_path: Path | None = None,+ go_binary: str = "go",+) -> Path:+ """Build all pinned targets and return the checked-in manifest path."""++ payload = _load_manifest(manifest_path)+ output_dir = output_dir.resolve()+ if output_dir.exists():+ if not output_dir.is_dir() or output_dir.is_symlink() or any(output_dir.iterdir()):+ raise BuildError("Model Hub build output must be a fresh empty directory")+ else:+ output_dir.mkdir(parents=True)++ build_metadata = payload.get("build")+ if not isinstance(build_metadata, dict):+ build_metadata = {}+ recorded_patch = build_metadata.get("patch")+ patch_digest = build_metadata.get("patch_sha256")+ if (+ not isinstance(recorded_patch, str)+ or not recorded_patch+ or Path(recorded_patch).is_absolute()+ or ".." in Path(recorded_patch).parts+ or not isinstance(patch_digest, str)+ or re.fullmatch(r"[0-9a-f]{64}", patch_digest) is None+ ):+ raise BuildError("Model Hub manifest compatibility patch identity is invalid")+ patch_path = patch_path if patch_path is not None else REPO_ROOT / recorded_patch+ if not patch_path.is_file() or patch_path.is_symlink():+ raise BuildError("Model Hub compatibility patch is missing or unsafe")+ if _sha256(patch_path) != patch_digest:+ raise BuildError("Model Hub compatibility patch checksum differs from pinned manifest")+ source_date_epoch = build_metadata.get("source_date_epoch", 0)+ if isinstance(source_date_epoch, bool) or not isinstance(source_date_epoch, int) or source_date_epoch < 0:+ raise BuildError("Model Hub build source_date_epoch is invalid")++ with tempfile.TemporaryDirectory(prefix="avibe-model-hub-build-") as temporary:+ checkout = _prepare_source(+ Path(temporary),+ repository=source_repository,+ source_sha=str(payload["source_sha"]),+ patch_path=patch_path.resolve(),+ )+ go_version = _go_toolchain_version(_run([go_binary, "version"], cwd=checkout))+ pinned_go_version = build_metadata.get("go_version")+ if isinstance(pinned_go_version, str) and pinned_go_version and go_version != pinned_go_version:+ raise BuildError(+ f"Go toolchain {go_version} differs from pinned manifest toolchain {pinned_go_version}"+ )++ generated_assets: list[dict[str, Any]] = []+ for platform in sorted(TARGETS):+ goos, goarch, _asset_arch = TARGETS[platform]+ build_dir = Path(temporary) / "artifacts" / platform+ build_dir.mkdir(parents=True)+ binary = build_dir / "cli-proxy-api"+ environment = os.environ.copy()+ environment.update(+ {+ "CGO_ENABLED": "0",+ "GOOS": goos,+ "GOARCH": goarch,+ }+ )+ _run(+ [+ go_binary,+ "build",+ "-mod=readonly",+ "-trimpath",+ "-buildvcs=false",+ "-ldflags",+ f"-X main.Version={payload['version']}",+ "-o",+ str(binary),+ "./cmd/server",+ ],+ cwd=checkout,+ env=environment,+ )+ _verify_built_binary(+ binary,+ version=str(payload["version"]),+ target=platform,+ checkout=checkout,+ )+ for member_name in ARCHIVE_MEMBERS[1:]:+ shutil.copy2(checkout / member_name, build_dir / member_name)+ archive_name = _asset_name(str(payload["version"]), platform)+ archive_path = output_dir / archive_name+ _archive(build_dir, archive_path, source_date_epoch=source_date_epoch)+ generated_assets.append(+ {+ "platform": platform,+ "url": next(+ item["url"]+ for item in payload["assets"]+ if isinstance(item, dict) and item.get("platform") == platform+ ),+ "size_bytes": archive_path.stat().st_size,+ "sha256": _sha256(archive_path),+ "binary_sha256": _sha256(binary),+ "bin_path": "cli-proxy-api",+ }+ )+ (output_dir / f"{archive_name}.sha256").write_text(+ f"{generated_assets[-1]['sha256']} {archive_name}\n",+ encoding="utf-8",+ )++ generated_manifest = output_dir / "model-hub-engine-manifest.json"+ generated_manifest.write_bytes(manifest_path.read_bytes())++ # Import lazily so the builder can be unit-tested without importing the+ # network-facing release guard during source preparation.+ try:+ from scripts.model_hub_engine_release_guard import verify_release_assets+ except ModuleNotFoundError as exc:+ if exc.name != "scripts":+ raise+ from model_hub_engine_release_guard import verify_release_assets++ # The checked-in manifest is the publication contract. A generated+ # manifest may describe what this runner produced, but it must not replace+ # the pinned sizes, digests, or metadata used by installed clients.+ verify_release_assets(manifest_path, output_dir)+ return generated_manifest+++def _build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)+ parser.add_argument(+ "--patch", type=Path,+ help="Use a local copy of the manifest-pinned patch (checksum must match).",+ )+ parser.add_argument("--source-repository", default=DEFAULT_SOURCE_REPOSITORY)+ parser.add_argument("--go", default="go", dest="go_binary")+ parser.add_argument("output_dir", type=Path)+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = _build_parser().parse_args(argv)+ try:+ generated_manifest = build_source_release(+ args.manifest,+ args.output_dir,+ source_repository=args.source_repository,+ patch_path=args.patch,+ go_binary=args.go_binary,+ )+ except BuildError as exc:+ print(json.dumps({"ok": False, "error": str(exc)}))+ return 1+ print(json.dumps({"ok": True, "manifest": str(generated_manifest)}))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/model_hub_engine_release_guard.py b/scripts/model_hub_engine_release_guard.pyindex 62a0bcfab..94f128f89 100755--- a/scripts/model_hub_engine_release_guard.py+++ b/scripts/model_hub_engine_release_guard.py@@ -8,6 +8,7 @@ import hashlibimport jsonimport reimport shutil+import subprocessimport sysimport tarfileimport tempfile@@ -240,6 +241,70 @@ def verify_release_assets(manifest_path: Path, asset_dir: Path) -> ReleaseSpec:return spec+def _gh_release(repository: str, *arguments: str) -> str:+ try:+ result = subprocess.run(+ ["gh", "release", *arguments, "--repo", repository],+ check=True,+ capture_output=True,+ text=True,+ )+ except OSError as exc:+ raise ReleaseGuardError(f"unable to invoke GitHub CLI: {exc}") from exc+ except subprocess.CalledProcessError as exc:+ raise ReleaseGuardError(+ f"GitHub release {arguments[0]} failed ({exc.returncode}): "+ f"{(exc.stderr or '').strip()}"+ ) from exc+ return result.stdout+++def publish_draft_release(+ manifest_path: Path, asset_dir: Path, *, repository: str,+) -> ReleaseSpec:+ """Repair an unpublished asset set, verify its bytes, then publish it.++ Both first publication and backup recovery use this boundary. Published+ releases are immutable here. Verified local bytes can replace an incomplete+ or unreadable draft; publication still requires a successful remote check.+ """+ spec = verify_release_assets(manifest_path, asset_dir)+ snapshot = json.loads(+ _gh_release(repository, "view", spec.asset_release_tag, "--json", "isDraft,assets")+ )+ if snapshot.get("isDraft") is not True:+ raise ReleaseGuardError("refusing to replace assets on a published release")+ current_names = {asset["name"] for asset in snapshot["assets"]}++ with tempfile.TemporaryDirectory(prefix="avibe-engine-draft-") as temporary:+ draft_dir = Path(temporary) / "assets"++ def download() -> None:+ draft_dir.mkdir()+ _gh_release(+ repository, "download", spec.asset_release_tag, "--dir", str(draft_dir),+ )++ try:+ download()+ verify_release_assets(manifest_path, draft_dir)+ except ReleaseGuardError as exc:+ print(f"Repairing unverified draft assets: {exc}", file=sys.stderr)+ # Replacement owns the entire unpublished set, including names+ # that are absent from the manifest. Never leave extra draft bytes.+ for name in sorted(current_names):+ _gh_release(repository, "delete-asset", spec.asset_release_tag, name, "--yes")+ _gh_release(+ repository, "upload", spec.asset_release_tag,+ *(str(asset_dir / name) for name in sorted(spec.expected_asset_names)),+ )+ shutil.rmtree(draft_dir)+ download()+ verify_release_assets(manifest_path, draft_dir)+ _gh_release(repository, "edit", spec.asset_release_tag, "--draft=false")+ return spec++def _download(url: str, destination: Path, *, max_bytes: int, attempts: int = 3) -> None:request = urllib.request.Request(url,@@ -320,7 +385,15 @@ def fetch_release_assets(manifest_path: Path, output_dir: Path) -> ReleaseSpec:def fetch_upstream_assets(manifest_path: Path, output_dir: Path) -> ReleaseSpec:- return _materialize(manifest_path, output_dir, from_upstream=True)+ try:+ from scripts.build_model_hub_engine import build_source_release+ except ModuleNotFoundError as exc:+ if exc.name != "scripts":+ raise+ from build_model_hub_engine import build_source_release++ generated_manifest = build_source_release(manifest_path, output_dir)+ return load_release_spec(generated_manifest)def _build_parser() -> argparse.ArgumentParser:@@ -331,11 +404,16 @@ def _build_parser() -> argparse.ArgumentParser:fetch.add_argument("--output-dir", type=Path, required=True)fetch_source = subparsers.add_parser("fetch-source",- help="Fetch verified upstream bytes for initial Avibe release publication.",+ help="Build patched source assets for initial Avibe release publication.",)fetch_source.add_argument("--output-dir", type=Path, required=True)verify = subparsers.add_parser("verify", help="Verify a materialized release directory.")verify.add_argument("--asset-dir", type=Path, required=True)+ publish_draft = subparsers.add_parser(+ "publish-draft", help="Repair and verify a draft using manifest-pinned assets before publication.",+ )+ publish_draft.add_argument("--asset-dir", type=Path, required=True)+ publish_draft.add_argument("--repo", required=True)return parser@@ -346,6 +424,8 @@ def main(argv: list[str] | None = None) -> int:spec = fetch_release_assets(args.manifest, args.output_dir)elif args.command == "fetch-source":spec = fetch_upstream_assets(args.manifest, args.output_dir)+ elif args.command == "publish-draft":+ spec = publish_draft_release(args.manifest, args.asset_dir, repository=args.repo)else:spec = verify_release_assets(args.manifest, args.asset_dir)except ReleaseGuardError as exc:diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.pyindex d09ce5f8d..b4a7a9720 100644--- a/tests/e2e/test_model_hub_routing.py+++ b/tests/e2e/test_model_hub_routing.py@@ -92,10 +92,54 @@ def test_mh_routing_008_real_gateway_cpa_exact_model_and_source(tmp_path, monkeypaths = {"anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions"}prompt = "Original request: \u4e2d\u6587"payload = {"model": menu, "stream": stream}+ tool_name = "lookup_weather"+ tool_id = "call_weather"+ arguments = {"city": "上海"}+ tool_result = "晴朗"+ schema = {+ "type": "object",+ "properties": {"city": {"type": "string"}},+ "required": ["city"],+ }+ function = {"name": tool_name, "description": "Look up weather", "parameters": schema}if protocol == "openai_responses":- payload["input"] = prompt+ payload.update(+ tools=[{"type": "function", **function}],+ input=[+ {"role": "user", "content": prompt},+ {"type": "function_call", "call_id": tool_id, "name": tool_name,+ "arguments": json.dumps(arguments, ensure_ascii=False)},+ {"type": "function_call_output", "call_id": tool_id, "output": tool_result},+ ],+ )+ elif protocol == "anthropic":+ payload.update(+ max_tokens=32,+ tools=[{"name": tool_name, "description": "Look up weather", "input_schema": schema}],+ messages=[+ {"role": "user", "content": prompt},+ {"role": "assistant", "content": [+ {"type": "tool_use", "id": tool_id, "name": tool_name, "input": arguments},+ ]},+ {"role": "user", "content": [+ {"type": "tool_result", "tool_use_id": tool_id, "content": tool_result},+ ]},+ ],+ )else:- payload.update(max_tokens=32, messages=[{"role": "user", "content": prompt}])+ payload.update(+ max_completion_tokens=32,+ tools=[{"type": "function", "function": function}],+ messages=[+ {"role": "user", "content": prompt},+ {"role": "assistant", "tool_calls": [+ {"id": tool_id, "type": "function", "function": {+ "name": tool_name, "arguments": json.dumps(arguments, ensure_ascii=False),+ }},+ ]},+ {"role": "tool", "tool_call_id": tool_id, "content": tool_result},+ ],+ )first.reset_requests()second.reset_requests()try:@@ -109,8 +153,37 @@ def test_mh_routing_008_real_gateway_cpa_exact_model_and_source(tmp_path, monkeyawait gateway.close()captured = [row for row in first.requests() if row["path"] == f"/v1/{paths[protocol]}"]assert len(captured) == 1, first.requests()- assert captured[0]["body"]["model"] == target- assert prompt in json.dumps(captured[0]["body"], ensure_ascii=False)+ received = captured[0]["body"]+ assert received["model"] == target+ assert prompt in json.dumps(received, ensure_ascii=False)+ # CPA may add cache-control metadata; the caller's tool contract survives.+ assert any(+ all(tool.get(key) == value for key, value in payload["tools"][0].items())+ for tool in received["tools"]+ )+ if protocol == "openai_responses":+ call = next(item for item in received["input"] if item.get("type") == "function_call")+ result = next(item for item in received["input"] if item.get("type") == "function_call_output")+ assert call["call_id"] == result["call_id"] == tool_id+ assert call["name"] == tool_name+ assert json.loads(call["arguments"]) == arguments+ assert result["output"] == tool_result+ elif protocol == "anthropic":+ call = received["messages"][1]["content"][0]+ result = received["messages"][2]["content"][0]+ assert call["id"] == result["tool_use_id"] == tool_id+ assert call["name"] == tool_name+ assert call["input"] == arguments+ assert result["content"] == tool_result+ else:+ call = received["messages"][1]["tool_calls"][0]+ result = received["messages"][2]+ assert received.get("max_completion_tokens") == 32+ assert "max_tokens" not in received+ assert call["id"] == result["tool_call_id"] == tool_id+ assert call["function"]["name"] == tool_name+ assert json.loads(call["function"]["arguments"]) == arguments+ assert result["content"] == tool_resultassert not [row for row in second.requests() if row["path"] == f"/v1/{paths[protocol]}"]assert [row.id for row in service.store.load().sources[0].models] == inventoryassert adapter.state_store.get_source(sources[0].id).model_ids == tuple(inventory)diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex a45d1c254..858d6c1d8 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -3676,7 +3676,11 @@ def test_hub_oauth_model_free_observation_closed_loop(else "sk-ant-oat01-test-valid" if credential_valid else "sk-ant-oat01-test-expired")auth_name = "oauth-test.json"- grant = {"access_token": bound_token, "refresh_token": "test-refresh-grant"}+ grant = {+ "type": "codex" if is_openai else "claude",+ "access_token": bound_token,+ "refresh_token": "test-refresh-grant",+ }state_store._secure_write_json(state_store.auth_dir / auth_name, grant)def management_request(method, path, *, query=None, payload=None):@@ -3742,6 +3746,8 @@ def test_hub_oauth_model_free_observation_closed_loop(async def complete_consent(h):flow = adapter.flows[h.flow_id]h.credential_ref = state_store.bind_oauth_credential(flow.source_id, vendor, auth_name)+ grant["prefix"] = state_store.credential_metadata(h.credential_ref)["prefix"]+ state_store._secure_write_json(state_store.auth_dir / auth_name, grant)adapter.flows[h.flow_id] = replace(flow, state="success", credential_ref=h.credential_ref)async def materialize_source(h):@@ -3758,7 +3764,10 @@ def test_hub_oauth_model_free_observation_closed_loop(assert source["state"]["status"] == "standby"assert [model["id"] for model in source["models"]] == ["gpt-5.6"]assert service.list_sources() == [source]- assert all(secret not in json.dumps(terminal) for secret in grant.values())+ assert all(+ grant[key] not in json.dumps(terminal)+ for key in ("access_token", "refresh_token")+ )assert (await service.oauth_status(h.flow_id))["source"] == sourceassert adapter.revoked == []assert len(api_calls) == 1diff --git a/tests/test_github_release.py b/tests/test_github_release.pyindex e5201007f..f44df1ccc 100644--- a/tests/test_github_release.py+++ b/tests/test_github_release.py@@ -455,7 +455,7 @@ def test_finalize_waits_for_release_and_latest_readback(@pytest.mark.parametrize("newer", [False, True])def test_auto_latest_uses_all_official_versions_instead_of_engine_latest(monkeypatch, newer):calls = []- selected_latest = "model-hub-engine-v7.2.149-1"+ selected_latest = "model-hub-engine-v7.3.16-3"release_reads = iter([_release_payload(draft=True), _release_payload(draft=False)])releases = [{"tag_name": selected_latest, "draft": False, "prerelease": False},@@ -500,7 +500,7 @@ def test_serialized_finalizers_keep_highest_version_for_every_admission_order(mo}for tag in order}- latest = "model-hub-engine-v7.2.149-1"+ latest = "model-hub-engine-v7.3.16-3"writes = []inventories = []diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 98030aef5..5296e2136 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -7603,6 +7603,15 @@ def test_completed_orphan_cleanup_replay_clears_surviving_service_journal(payload=None,timeout=None,):+ if (method, path) == ("GET", "/auth-files"):+ return {+ "files": [{+ "id": "claude-account",+ "auth_index": "claude-account",+ "name": auth_file.name,+ "provider": "claude",+ }]+ }assert (method, path) == ("DELETE", "/auth-files")return {"status": "ok"}@@ -7628,13 +7637,18 @@ def test_completed_orphan_cleanup_replay_clears_surviving_service_journal(state = EngineStateStore(tmp_path / "runtime-state")state.prepare_instance("install-1")auth_file = state.auth_dir / "claude-account.json"- auth_file.write_text("{}", encoding="utf-8")- auth_file.chmod(0o600)credential_ref = state.bind_oauth_credential("src_pending01","anthropic",auth_file.name,)+ state._secure_write_json(+ auth_file,+ {+ "type": "claude",+ "prefix": state.credential_metadata(credential_ref)["prefix"],+ },+ )runtime_adapter = CLIProxyEngineAdapter(supervisor=Supervisor(Client()), # type: ignore[arg-type]state_store=state,diff --git a/tests/test_model_hub_claude_login_migration.py b/tests/test_model_hub_claude_login_migration.pynew file mode 100644index 000000000..ca2cd4c32--- /dev/null+++ b/tests/test_model_hub_claude_login_migration.py@@ -0,0 +1,133 @@+"""CPA's login-save filename migration preserves Avibe's prefix ownership."""++import json++import pytest++from core.handlers.model_hub.adapter import RetainedMaterialDisposition+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+from vibe.model_hub_runtime.client import EngineClientError+from vibe.model_hub_runtime.state import EngineStateStore++[email protected]("case", ["same_source", "foreign_source", "legacy_retained", "patch_failure"])+async def test_claude_login_migration_preserves_existing_owner(tmp_path, case):+ # The pinned CPA login saves a canonical file with the old non-token+ # metadata, then deletes its predecessor. No restart/refresh rename is+ # simulated: this side effect happens only when the login completes.+ store = EngineStateStore(tmp_path / "engine")+ old_name = "[email protected]"+ new_name = "[email protected]"+ source_id = "src_original123"+ ref = store.bind_oauth_credential(source_id, "anthropic", old_name)+ original = store.credential_metadata(ref)+ store.write_oauth_auth_file(old_name, {+ "type": "claude", "prefix": original["prefix"],+ "email": "[email protected]", "refresh_token": "old-fixture",+ })+ patches = []+ deletes = []++ class Client:+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if (method, path) == ("GET", "/auth-files"):+ return {"files": [{+ "id": file.name, "name": file.name, "provider": "claude",+ "auth_index": str(index),+ } for index, file in enumerate(sorted(store.auth_dir.glob("*.json")))]}+ if (method, path) == ("GET", "/anthropic-auth-url"):+ return {"state": "fixture-login", "url": "https://example.test/oauth"}+ if (method, path) == ("GET", "/get-auth-status"):+ old_payload = json.loads((store.auth_dir / old_name).read_text())+ store.write_oauth_auth_file(new_name, {+ **old_payload, "refresh_token": "new-fixture",+ })+ if case != "legacy_retained":+ (store.auth_dir / old_name).unlink()+ return {"status": "ok"}+ if (method, path) == ("PATCH", "/auth-files/fields"):+ patches.append(payload)+ if case == "patch_failure":+ raise EngineClientError("fixture patch failure")+ assert payload == {"name": new_name, "prefix": original["prefix"]}+ return {"status": "ok"}+ if (method, path) == ("DELETE", "/auth-files"):+ deletes.append(query["name"])+ store.delete_oauth_auth_file(query["name"])+ return {"status": "ok"}+ raise AssertionError((method, path))++ class Supervisor:+ def client(self):+ return client++ def with_engine_excluded(self, operation):+ return operation(client)++ client = Client()+ adapter = CLIProxyEngineAdapter(supervisor=Supervisor(), state_store=store)+ login_source = "src_foreign1234" if case == "foreign_source" else source_id+ flow = await adapter.start_oauth(login_source, "anthropic")+ result = await adapter.oauth_status(flow.flow_id)++ assert not deletes+ assert (store.auth_dir / new_name).is_file()+ assert json.loads((store.auth_dir / new_name).read_text())["prefix"] == original["prefix"]+ assert len(store._oauth_credentials()) == 1+ if case == "legacy_retained":+ assert result.state == "failed"+ assert result.error_key == "models.oauth.binding_failed"+ assert result.retained_material_disposition is RetainedMaterialDisposition.UNKNOWN+ assert result.retained_credential_ref is None+ assert store.credential_metadata(ref) == original+ assert (store.auth_dir / old_name).is_file()+ assert not patches+ else:+ assert store.credential_metadata(ref) == {**original, "auth_name": new_name}+ assert not (store.auth_dir / old_name).exists()+ if case == "foreign_source":+ assert result.state == "failed"+ assert result.error_key == "models.oauth.account_already_added"+ assert result.retained_material_disposition is RetainedMaterialDisposition.FOREIGN_SOURCE_REF+ assert result.retained_credential_ref is None+ assert not patches+ elif case == "patch_failure":+ assert result.state == "failed"+ assert result.error_key == "models.oauth.binding_failed"+ assert result.retained_material_disposition is RetainedMaterialDisposition.FLOW_SOURCE_REF+ assert result.retained_credential_ref == ref+ else:+ assert result.state == "success"+ assert result.credential_ref == ref+ assert await adapter.oauth_status(flow.flow_id) == result+++async def test_legacy_claude_grant_is_usable_without_relogin_or_migration(tmp_path):+ # A released v7.2 binding has no new identity metadata. CPA loads it under+ # its existing name; normal use must not require a login or a migration.+ store = EngineStateStore(tmp_path / "engine")+ auth_name = "[email protected]"+ ref = store.bind_oauth_credential("src_original123", "anthropic", auth_name)+ metadata = store.credential_metadata(ref)+ store.write_oauth_auth_file(auth_name, {+ "type": "claude", "prefix": metadata["prefix"],+ "email": "[email protected]", "refresh_token": "legacy-fixture",+ })++ class Client:+ def management_request(self, method, path, *, query=None, **_kwargs):+ assert (method, path, query) == ("GET", "/auth-files/models", {"name": auth_name})+ return {"models": [{"id": "claude-sonnet-fixture"}]}++ class Supervisor:+ def client(self):+ return Client()++ adapter = CLIProxyEngineAdapter(supervisor=Supervisor(), state_store=store)+ before = {path: path.read_bytes() for path in store.root.rglob("*") if path.is_file()}+ models = await adapter.discover_models("anthropic", "anthropic", None, ref)+ assert [model.id for model in models] == ["claude-sonnet-fixture"]+ assert adapter.subscription_account_label("src_original123", "anthropic", ref) == "[email protected]"+ assert {path: path.read_bytes() for path in store.root.rglob("*") if path.is_file()} == beforediff --git a/tests/test_model_hub_engine_build.py b/tests/test_model_hub_engine_build.pynew file mode 100644index 000000000..6ba7e739b--- /dev/null+++ b/tests/test_model_hub_engine_build.py@@ -0,0 +1,209 @@+from __future__ import annotations++import hashlib+import json+import subprocess+import tarfile+from pathlib import Path++import pytest++from scripts import build_model_hub_engine as builder+from scripts import model_hub_engine_release_guard as guard+++# Independent fixture contract: do not derive names, contents, or expected+# digests from builder constants or a previous invocation of the builder.+FIXTURE_MEMBERS = {+ "cli-proxy-api": b"CLIProxyAPI v7.3.16",+ "LICENSE": b"LICENSE",+ "README.md": b"README.md",+ "README_CN.md": b"README_CN.md",+ "config.example.yaml": b"config.example.yaml",+}+FIXTURE_TARGETS = {+ "darwin-arm64": "darwin_aarch64",+ "darwin-x64": "darwin_amd64",+ "linux-amd64": "linux_amd64",+ "linux-arm64": "linux_aarch64",+}+++def _manifest(tmp_path: Path, *, source_sha: str, patch: Path) -> Path:+ version = "v7.3.16"+ release_tag = "model-hub-engine-v7.3.16-3"+ assets = [+ {+ "platform": platform,+ "url": (+ f"{guard.OWNED_RELEASE_ROOT}/{release_tag}/"+ f"CLIProxyAPI_7.3.16_{asset_arch}.tar.gz"+ ),+ # USTAR fixture: members above in declared order, epoch 123,+ # root ownership, 0755 executable/0644 docs; gzip mtime 0.+ "size_bytes": 234,+ "sha256": "fb13ef1030f49b5b64993f9596a227ac519b38d637b1a61fa95d3c73fc3d5ab8",+ "binary_sha256": "0e18ced596a1e68e5dfdcc5c8bf98668f405061aeca0fc2a4501aeeeeebf809d",+ "bin_path": "cli-proxy-api",+ }+ for platform, asset_arch in FIXTURE_TARGETS.items()+ ]+ path = tmp_path / "manifest.json"+ path.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "name": "cliproxyapi",+ "version": version,+ "source": "router-for-me/CLIProxyAPI",+ "source_url": f"https://github.com/router-for-me/CLIProxyAPI/tree/{source_sha}",+ "source_sha": source_sha,+ "release_tag": version,+ "asset_release_tag": release_tag,+ "license": "MIT",+ "assets": assets,+ "build": {+ "go_version": "go1.26.0",+ "source_date_epoch": 123,+ "patch": patch.name,+ "patch_sha256": hashlib.sha256(patch.read_bytes()).hexdigest(),+ },+ }+ ),+ encoding="utf-8",+ )+ return path+++ ("patch_mode", "wrong_pinned_size"),+ [("explicit", False), ("default", False), ("explicit", True), ("changed", False)],+)+def test_build_source_release_applies_patch_and_materializes_four_targets(+ tmp_path: Path,+ monkeypatch,+ wrong_pinned_size: bool,+ patch_mode: str,+) -> None:+ source = tmp_path / "source"+ (source / "cmd" / "server").mkdir(parents=True)+ for name, data in FIXTURE_MEMBERS.items():+ if name != "cli-proxy-api":+ (source / name).write_bytes(data)+ subprocess.run(["git", "init", "--quiet", str(source)], check=True)+ subprocess.run(+ ["git", "-C", str(source), "config", "user.email", "[email protected]"],+ check=True,+ )+ subprocess.run(+ ["git", "-C", str(source), "config", "user.name", "Test"],+ check=True,+ )+ subprocess.run(["git", "-C", str(source), "add", "."], check=True)+ subprocess.run(+ ["git", "-C", str(source), "commit", "--quiet", "-m", "fixture"],+ check=True,+ )+ source_sha = subprocess.check_output(+ ["git", "-C", str(source), "rev-parse", "HEAD"],+ text=True,+ ).strip()+ patch = tmp_path / "compat.patch"+ patch.write_text(+ "\n".join(+ [+ "diff --git a/patched-marker.txt b/patched-marker.txt",+ "new file mode 100644",+ "--- /dev/null",+ "+++ b/patched-marker.txt",+ "@@ -0,0 +1 @@",+ "+patched",+ "",+ ]+ ),+ encoding="utf-8",+ )+ manifest = _manifest(tmp_path, source_sha=source_sha, patch=patch)+ monkeypatch.setattr(builder, "REPO_ROOT", tmp_path)+ if patch_mode == "changed":+ # A provenance-only change leaves all compiled/archive bytes intact.+ # Output hash validation alone cannot detect this changed build input.+ patch.write_bytes(b"# changed provenance\n" + patch.read_bytes())+ if wrong_pinned_size:+ pinned = json.loads(manifest.read_text(encoding="utf-8"))+ pinned["assets"][0]["size_bytes"] = 1+ manifest.write_text(json.dumps(pinned), encoding="utf-8")+ commands: list[tuple[list[str], dict[str, str] | None]] = []+ real_run = builder._run++ def fake_run(command, *, cwd=None, env=None):+ commands.append((list(command), dict(env) if env is not None else None))+ if command[:2] == ["go", "version"]:+ return "go version go1.26.0 darwin/arm64\n"+ if command[:2] == ["go", "build"]:+ assert (cwd / "patched-marker.txt").read_text(encoding="utf-8") == "patched\n"+ binary = Path(command[command.index("-o") + 1])+ binary.write_bytes(FIXTURE_MEMBERS["cli-proxy-api"])+ return ""+ if command[0].endswith("cli-proxy-api") and command[1:] == ["--help"]:+ return "CLIProxyAPI Version: v7.3.16, Commit: fixture\n"+ return real_run(command, cwd=cwd, env=env)++ monkeypatch.setattr(builder, "_run", fake_run)+ output = tmp_path / "output"+ if patch_mode == "changed":+ with pytest.raises(builder.BuildError, match="patch.*checksum"):+ builder.build_source_release(+ manifest,+ output,+ patch_path=patch,+ source_repository=str(source),+ )+ assert not commands+ return+ if wrong_pinned_size:+ with pytest.raises(guard.ReleaseGuardError, match="archive size mismatch"):+ builder.build_source_release(+ manifest,+ output,+ patch_path=patch,+ source_repository=str(source),+ go_binary="go",+ )+ return++ generated_manifest = builder.build_source_release(+ manifest,+ output,+ source_repository=str(source),+ go_binary="go",+ **({"patch_path": patch} if patch_mode == "explicit" else {}),+ )++ assert {path.name for path in output.glob("*.tar.gz")} == {+ f"CLIProxyAPI_7.3.16_{arch}.tar.gz" for arch in FIXTURE_TARGETS.values()+ }+ for archive in output.glob("*.tar.gz"):+ with tarfile.open(archive, "r:gz") as bundle:+ assert bundle.getnames() == list(FIXTURE_MEMBERS)+ for member in bundle.getmembers():+ assert member.isfile()+ assert member.mode == (0o755 if member.name == "cli-proxy-api" else 0o644)+ assert member.mtime == 123+ assert (member.uid, member.gid, member.uname, member.gname) == (0, 0, "", "")+ assert bundle.extractfile(member).read() == FIXTURE_MEMBERS[member.name]+ assert generated_manifest.read_bytes() == manifest.read_bytes()+ assert any(command[:3] == ["git", "apply", "--whitespace=error"] for command, _ in commands)+ build_envs = [env for command, env in commands if command[:2] == ["go", "build"]]+ assert len(build_envs) == 4+ assert {(env["GOOS"], env["GOARCH"]) for env in build_envs} == {+ ("darwin", "arm64"), ("darwin", "amd64"), ("linux", "amd64"), ("linux", "arm64"),+ }+ assert {env["CGO_ENABLED"] for env in build_envs} == {"0"}+ build_commands = [command for command, _ in commands if command[:2] == ["go", "build"]]+ assert all(+ "-ldflags" in command and "-X main.Version=v7.3.16" in command+ for command in build_commands+ )++ guard.verify_release_assets(manifest, output)diff --git a/tests/test_model_hub_engine_release_guard.py b/tests/test_model_hub_engine_release_guard.pyindex 810ff8f0f..7630bebc8 100644--- a/tests/test_model_hub_engine_release_guard.py+++ b/tests/test_model_hub_engine_release_guard.py@@ -4,11 +4,13 @@ import gzipimport hashlibimport ioimport json+import subprocessimport tarfilefrom pathlib import Pathimport pytest+from scripts import build_model_hub_enginefrom scripts import model_hub_engine_release_guard as guard@@ -103,7 +105,24 @@ def test_fetch_source_verifies_upstream_bytes_and_builds_publishable_release(monkeypatch: pytest.MonkeyPatch,) -> None:manifest_path, _owned, upstream = _manifest(tmp_path)- monkeypatch.setattr(guard, "_download", _fake_download(upstream))+ def build_source(manifest: Path, output: Path) -> Path:+ output.mkdir()+ output_manifest = output / "model-hub-engine-manifest.json"+ output_manifest.write_bytes(manifest.read_bytes())+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ for raw in payload["assets"]:+ name = Path(raw["url"]).name+ archive = upstream[+ f"{guard.UPSTREAM_RELEASE_ROOT}/{payload['release_tag']}/{name}"+ ]+ (output / name).write_bytes(archive)+ (output / f"{name}.sha256").write_text(+ f"{hashlib.sha256(archive).hexdigest()} {name}\n",+ encoding="utf-8",+ )+ return output_manifest++ monkeypatch.setattr(build_model_hub_engine, "build_source_release", build_source)spec = guard.fetch_upstream_assets(manifest_path, tmp_path / "publish")@@ -187,6 +206,85 @@ def test_manifest_rejects_non_owned_release_url(tmp_path: Path) -> None:guard.load_release_spec(manifest_path)+ "remote_state",+ ["valid", "missing", "extra", "corrupt", "bad_upload", "published", "download_once", "unavailable"],+)+def test_draft_publication_repairs_exact_asset_set_before_becoming_public(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, remote_state: str,+) -> None:+ # Contract: either publish the exact pinned bytes, or preserve the draft.+ # The old workflow deleted only expected names, so an extra asset survived+ # every recovery. Source-text assertions never exercised this transition.+ manifest, owned, _upstream = _manifest(tmp_path)+ monkeypatch.setattr(guard, "_download", _fake_download(owned))+ verified = tmp_path / "verified"+ guard.fetch_release_assets(manifest, verified)+ expected = {path.name: path.read_bytes() for path in verified.iterdir()}+ remote = dict(expected)+ target = next(name for name in expected if name.endswith(".tar.gz"))+ if remote_state == "missing":+ del remote[target]+ elif remote_state == "extra":+ remote["unexpected.txt"] = b"interrupted draft"+ elif remote_state in {"corrupt", "bad_upload"}:+ remote[target] = b"corrupt upload"+ is_draft = remote_state != "published"+ calls = []++ def fake_gh(command, **kwargs):+ nonlocal is_draft+ assert command[:2] == ["gh", "release"]+ assert command[-2:] == ["--repo", "fixture/engine"]+ assert command[3] == "model-hub-engine-v7.2.149-1"+ calls.append(command[2])+ action = command[2]+ stdout = ""+ if action == "view":+ stdout = json.dumps({"isDraft": is_draft, "assets": [{"name": name} for name in remote]})+ elif action == "download":+ if remote_state == "unavailable" or (+ remote_state == "download_once" and calls.count("download") == 1+ ):+ raise subprocess.CalledProcessError(1, command)+ destination = Path(command[command.index("--dir") + 1])+ for name, data in remote.items():+ (destination / name).write_bytes(data)+ elif action == "delete-asset":+ del remote[command[4]]+ elif action == "upload":+ for filename in command[4:-2]:+ path = Path(filename)+ remote[path.name] = path.read_bytes()+ if remote_state == "bad_upload":+ remote[target] = b"corrupt upload"+ elif action == "edit":+ assert "--draft=false" in command+ is_draft = False+ else:+ raise AssertionError(command)+ return subprocess.CompletedProcess(command, 0, stdout=stdout)++ monkeypatch.setattr(guard.subprocess, "run", fake_gh)+ result = guard.main([+ "--manifest", str(manifest), "publish-draft",+ "--asset-dir", str(verified), "--repo", "fixture/engine",+ ])+ if remote_state in {"bad_upload", "published", "unavailable"}:+ assert result == 1+ assert is_draft is (remote_state != "published")+ assert "edit" not in calls+ if remote_state == "published":+ assert "delete-asset" not in calls and "upload" not in calls+ else:+ assert result == 0+ assert not is_draft+ assert remote == expected+ assert calls[-2:] == ["download", "edit"]+ if remote_state == "valid":+ assert "delete-asset" not in calls and "upload" not in calls++def test_workflow_has_scheduled_backup_and_non_clobbering_recovery() -> None:workflow = (guard.REPO_ROOT / ".github/workflows/model-hub-engine-release-guard.yml"@@ -198,7 +296,18 @@ def test_workflow_has_scheduled_backup_and_non_clobbering_recovery() -> None:assert "MANIFEST_SHA: ${{ steps.manifest.outputs.sha256 }}" in workflowassert "model-hub-engine-release-backup-${{ steps.manifest.outputs.sha256 }}" in workflowassert "retention-days: 90" in workflow- assert "--verify-tag" in workflowassert "--latest=false" in workflowassert "missing_assets" in workflowassert "--clobber" not in workflow+ assert "--json isDraft" in workflow+ assert workflow.count("model_hub_engine_release_guard.py publish-draft") == 2+ assert "model_hub_engine_release_guard.py verify" in workflow+ assert "publish-patched-source:" in workflow+ assert "needs: build-patched-source" in workflow+ assert "needs: [publish-patched-source]" in workflow+ assert "needs.publish-patched-source.result == 'success'" in workflow+ assert '--target "$GITHUB_SHA"' in workflow+ assert "actions/download-artifact@" in workflow+ assert "python3 scripts/model_hub_engine_release_guard.py verify" in workflow+ assert 'gh release create "$release_tag"' in workflow+ assert 'python3 scripts/model_hub_engine_release_guard.py fetch' in workflowdiff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex abef0285e..c885d6983 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -885,32 +885,32 @@ def test_packaged_manifest_matches_frozen_runtime_dependency_values(assert manifest == {"name": "cliproxyapi","resolution": "resolved",- "version": "v7.2.149",- "source_sha": "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",+ "version": "v7.3.16",+ "source_sha": "c404af96ebacedf8168b3c2bdbf4449a21cd1c1e","assets": [{"platform": "darwin-arm64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_aarch64.tar.gz",- "size_bytes": 19723285,- "sha256": "90962c9194fe5470dc21f167b0cbf167a4f9ff2961a6bcc88f0b7eec32f1b49b",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_darwin_aarch64.tar.gz",+ "size_bytes": 39534924,+ "sha256": "bc046156ac880beb1c09b2b69a8f80513ce3caec92f34fbc00dbf8aaf2c91754",},{"platform": "darwin-x64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_amd64.tar.gz",- "size_bytes": 21334889,- "sha256": "382f800a4d82fe39ee7158ca4f735a1a71d635fe0f1d9a55a4c5d13993ccc04e",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_darwin_amd64.tar.gz",+ "size_bytes": 41928346,+ "sha256": "6cdc647a2bb0ccc8d179f290cb1f90da28ef3d02e7c2d6aa96f5903760a78328",},{"platform": "linux-amd64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_amd64.tar.gz",- "size_bytes": 21385633,- "sha256": "95d865dd17986da7d08cb39ffafe07d050669c5264d4d00115758ab4de752a72",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_linux_amd64.tar.gz",+ "size_bytes": 39894112,+ "sha256": "88e0843bb5eaecb2748ff7fc5c4d61d301927ccd0aec7b35b1e20efc551957e9",},{"platform": "linux-arm64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_aarch64.tar.gz",- "size_bytes": 19287559,- "sha256": "2d290477295eba4e419bc231f1fb5d548edbdd4cd5654b34d26ed12f8dcd0ee7",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_linux_aarch64.tar.gz",+ "size_bytes": 36618378,+ "sha256": "a289bbc2d409e5a54a2f65c9d331f7e968b0f18fba2f3b56477a30a2a3c08c3a",},],}@@ -1403,34 +1403,34 @@ def test_installing_projection_matches_live_owner_or_resumable_claim(@pytest.mark.parametrize(("host_platform", "asset_platform", "size_bytes", "archive_sha256", "binary_sha256"),[- (- "darwin-arm64",- "darwin-arm64",- 19723285,- "90962c9194fe5470dc21f167b0cbf167a4f9ff2961a6bcc88f0b7eec32f1b49b",- "048c0089aa53948af91249bb97f172b2392cce5968473a5a3dbb06f3d742c2e7",- ),- (- "darwin-x64",- "darwin-x64",- 21334889,- "382f800a4d82fe39ee7158ca4f735a1a71d635fe0f1d9a55a4c5d13993ccc04e",- "05388e65f58493325aff1e2dfa33e727e7fa732b2d9eb651ec13315689e418e5",- ),- (- "linux-x64",- "linux-amd64",- 21385633,- "95d865dd17986da7d08cb39ffafe07d050669c5264d4d00115758ab4de752a72",- "b0f163bfd94e8cd64895000662f26f255d2a72b5c3f5009a97e8dc91ed9b8107",- ),- (- "linux-arm64",- "linux-arm64",- 19287559,- "2d290477295eba4e419bc231f1fb5d548edbdd4cd5654b34d26ed12f8dcd0ee7",- "24799863d478579ec3eef5ccc83769f79df749a30282ce1e2063708a03826e5b",- ),+ (+ "darwin-arm64",+ "darwin-arm64",+ 39534924,+ "bc046156ac880beb1c09b2b69a8f80513ce3caec92f34fbc00dbf8aaf2c91754",+ "bfd39d09fd0f5f922ba5cd1a6d86cb86b928e31bcf1746cb763f5632af13c068",+ ),+ (+ "darwin-x64",+ "darwin-x64",+ 41928346,+ "6cdc647a2bb0ccc8d179f290cb1f90da28ef3d02e7c2d6aa96f5903760a78328",+ "dc1339f5a5a50d7b8254c1b1662177beb9a597aab04ba647ee9b6f555de1b87d",+ ),+ (+ "linux-x64",+ "linux-amd64",+ 39894112,+ "88e0843bb5eaecb2748ff7fc5c4d61d301927ccd0aec7b35b1e20efc551957e9",+ "8c500c984e056a2b191c8a3a2780062ca447659244d7b62b9544c5a4af29b0de",+ ),+ (+ "linux-arm64",+ "linux-arm64",+ 36618378,+ "a289bbc2d409e5a54a2f65c9d331f7e968b0f18fba2f3b56477a30a2a3c08c3a",+ "9ddb102bbd6b80c2651e5eb2939840142efb8068e802521ae0c1eac3877a84b9",+ ),],)def test_engine_installer_selects_verified_packaged_asset(diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex f0c9f42f1..c83d69f61 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -108,7 +108,7 @@ _OAUTH_ENDPOINTS = {# rather than an endpoint Avibe may synthesize a request against.## Read from the engine at the commit `cliproxyapi_manifest.json` pins-# (v7.2.149, `2a6b87ac`); each row is one of its serving surfaces, not a guess:+# (v7.3.16, `c404af96`); each row is one of its serving surfaces, not a guess:## gemini `internal/translator/antigravity/openai/chat-completions/init.go:9`# registers `translator.Register(OpenAI, Antigravity, ...)`, so an@@ -1998,7 +1998,7 @@ class CLIProxyEngineAdapter:]if len(matches) != 1:raise EngineStateError("OAuth credential validation is inconclusive")- # CPA v7.2.149 loses refresh failure details ("token expired") and+ # CPA v7.3.16 loses refresh failure details ("token expired") and# also puts request failures in status_message. None of those# inventory strings proves that a refresh grant was rejected.try:@@ -2873,6 +2873,18 @@ class CLIProxyEngineAdapter:self._fail_flow(flow, "models.oauth.ambiguous_engine_binding")returnauth = candidates[0]+ if flow.auth_provider == "claude":+ try:+ # CPA only migrates Claude names while saving a new login.+ # Restore the existing ref before ownership or cleanup decisions.+ await asyncio.to_thread(self.state_store.reconcile_claude_login, auth.name)+ foreign = await asyncio.to_thread(+ self._foreign_bound_identities, provider_records, flow.source_id,+ )+ except (EngineStateError, OSError):+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)+ self._fail_flow(flow, "models.oauth.binding_failed")+ returnforeign_accounts = {record.account_id for record in provider_records if record.identity in foreign and record.account_id}@@ -2880,10 +2892,10 @@ class CLIProxyEngineAdapter:# The same account is already a Source. A new file for it is this# flow's own material and is removed; an existing one belongs to the# other Source and is never touched.- if auth.identity not in flow.before_auth_fingerprints and await self._delete_auth_files(auth.name):- self._set_retained_material(flow, RetainedMaterialDisposition.NONE)- elif auth.identity in foreign:+ if auth.identity in foreign:self._set_retained_material(flow, RetainedMaterialDisposition.FOREIGN_SOURCE_REF)+ elif auth.identity not in flow.before_auth_fingerprints and await self._delete_auth_files(auth.name):+ self._set_retained_material(flow, RetainedMaterialDisposition.NONE)else:self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)self._fail_flow(flow, "models.oauth.account_already_added")diff --git a/vibe/model_hub_runtime/cliproxyapi_manifest.json b/vibe/model_hub_runtime/cliproxyapi_manifest.jsonindex 89a88e1f8..845095bc1 100644--- a/vibe/model_hub_runtime/cliproxyapi_manifest.json+++ b/vibe/model_hub_runtime/cliproxyapi_manifest.json@@ -1,45 +1,55 @@{"schema_version": 1,"name": "cliproxyapi",- "version": "v7.2.149",+ "version": "v7.3.16","source": "router-for-me/CLIProxyAPI",- "source_url": "https://github.com/router-for-me/CLIProxyAPI/tree/2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",- "source_sha": "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",- "release_tag": "v7.2.149",- "asset_release_tag": "model-hub-engine-v7.2.149-1",+ "source_url": "https://github.com/router-for-me/CLIProxyAPI/tree/c404af96ebacedf8168b3c2bdbf4449a21cd1c1e",+ "source_sha": "c404af96ebacedf8168b3c2bdbf4449a21cd1c1e",+ "release_tag": "v7.3.16",+ "asset_release_tag": "model-hub-engine-v7.3.16-3","license": "MIT","assets": [{"platform": "darwin-arm64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_aarch64.tar.gz",- "size_bytes": 19723285,- "sha256": "90962c9194fe5470dc21f167b0cbf167a4f9ff2961a6bcc88f0b7eec32f1b49b",- "binary_sha256": "048c0089aa53948af91249bb97f172b2392cce5968473a5a3dbb06f3d742c2e7",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_darwin_aarch64.tar.gz",+ "size_bytes": 39534924,+ "sha256": "bc046156ac880beb1c09b2b69a8f80513ce3caec92f34fbc00dbf8aaf2c91754",+ "binary_sha256": "bfd39d09fd0f5f922ba5cd1a6d86cb86b928e31bcf1746cb763f5632af13c068","bin_path": "cli-proxy-api"},{"platform": "darwin-x64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_darwin_amd64.tar.gz",- "size_bytes": 21334889,- "sha256": "382f800a4d82fe39ee7158ca4f735a1a71d635fe0f1d9a55a4c5d13993ccc04e",- "binary_sha256": "05388e65f58493325aff1e2dfa33e727e7fa732b2d9eb651ec13315689e418e5",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_darwin_amd64.tar.gz",+ "size_bytes": 41928346,+ "sha256": "6cdc647a2bb0ccc8d179f290cb1f90da28ef3d02e7c2d6aa96f5903760a78328",+ "binary_sha256": "dc1339f5a5a50d7b8254c1b1662177beb9a597aab04ba647ee9b6f555de1b87d","bin_path": "cli-proxy-api"},{"platform": "linux-amd64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_amd64.tar.gz",- "size_bytes": 21385633,- "sha256": "95d865dd17986da7d08cb39ffafe07d050669c5264d4d00115758ab4de752a72",- "binary_sha256": "b0f163bfd94e8cd64895000662f26f255d2a72b5c3f5009a97e8dc91ed9b8107",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_linux_amd64.tar.gz",+ "size_bytes": 39894112,+ "sha256": "88e0843bb5eaecb2748ff7fc5c4d61d301927ccd0aec7b35b1e20efc551957e9",+ "binary_sha256": "8c500c984e056a2b191c8a3a2780062ca447659244d7b62b9544c5a4af29b0de","bin_path": "cli-proxy-api"},{"platform": "linux-arm64",- "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.2.149-1/CLIProxyAPI_7.2.149_linux_aarch64.tar.gz",- "size_bytes": 19287559,- "sha256": "2d290477295eba4e419bc231f1fb5d548edbdd4cd5654b34d26ed12f8dcd0ee7",- "binary_sha256": "24799863d478579ec3eef5ccc83769f79df749a30282ce1e2063708a03826e5b",+ "url": "https://github.com/avibe-bot/avibe/releases/download/model-hub-engine-v7.3.16-3/CLIProxyAPI_7.3.16_linux_aarch64.tar.gz",+ "size_bytes": 36618378,+ "sha256": "a289bbc2d409e5a54a2f65c9d331f7e968b0f18fba2f3b56477a30a2a3c08c3a",+ "binary_sha256": "9ddb102bbd6b80c2651e5eb2939840142efb8068e802521ae0c1eac3877a84b9","bin_path": "cli-proxy-api"}- ]+ ],+ "build": {+ "builder": "scripts/build_model_hub_engine.py",+ "go_version": "go1.26.0",+ "cgo_enabled": false,+ "trimpath": true,+ "buildvcs": false,+ "patch": "patches/model-hub-cpa-v7.3.16/openai-compat-native-token-field.patch",+ "patch_sha256": "5861e81791cf02adf67e249ddb92fa0119dff477e0ca54f5279ac817acc989e0",+ "source_date_epoch": 0+ }}diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 38cec0e7b..deb3deb51 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -959,6 +959,54 @@ class EngineStateStore:value = payload.get("auth_name") if payload.get("kind") == "oauth" else Nonereturn str(value) if value else None+ def reconcile_claude_login(self, auth_name: str) -> None:+ """Follow a login's preserved prefix, never infer ownership from account fields.++ CPA c404af96 saveTokenRecord saves the new canonical name with the+ previous file's metadata, then deletes that previous file. Only the+ OAuth-completion path calls this; ordinary loads/refreshes keep names.+ """+ auth_name = _validated_oauth_auth_name(auth_name)+ with self._lock:+ payload = self._read_json(self.auth_dir / auth_name)+ if payload is None:+ raise EngineStateError("OAuth credential is unavailable")+ prefix = payload.get("prefix")+ if not isinstance(prefix, str) or not prefix:+ return+ if payload.get("type") != "claude":+ raise EngineStateError("OAuth auth record provider conflicts")+ credentials = self._oauth_credentials()+ owners = [+ (ref, metadata) for ref, metadata in credentials+ if metadata.get("vendor") == "anthropic" and metadata.get("prefix") == prefix+ ]+ if not owners:+ return+ if len(owners) != 1:+ raise EngineStateError("OAuth auth record binding is ambiguous")+ credential_ref, metadata = owners[0]+ if any(+ ref != credential_ref and record.get("auth_name") == auth_name+ for ref, record in credentials+ ):+ raise EngineStateError("OAuth auth record binding is ambiguous")+ previous_name = _validated_oauth_auth_name(str(metadata.get("auth_name") or ""))+ if previous_name == auth_name:+ return+ # A failed legacy-file deletion leaves two grants. Keep both and+ # the original binding; do not choose or clean up either one.+ try:+ (self.auth_dir / previous_name).lstat()+ except FileNotFoundError:+ pass+ else:+ raise EngineStateError("OAuth auth record binding is ambiguous")+ self._secure_write_json(+ self._credential_path(credential_ref),+ {**metadata, "auth_name": auth_name},+ )+def oauth_account_label(self, credential_ref: str, *, source_id: str, vendor: str, auth_provider: str,) -> str | None: