Peach: Local-first video metadata scraper and media manager.
feat: add OpenCode Go model discovery
Peach local maintenance14d058b0d76d
diff --git a/README.md b/README.mdindex 8fa221a39..7d7faf625 100644--- a/README.md+++ b/README.md@@ -57,3 +57,5 @@ cd R:\peach-app## 批处理安全边界`scripts/scrape_codes.py` 默认只把番号发送到已声明的元数据源并写复核 CSV;只有 `--apply` 才写 ledger。`scripts/clean_names.py` 默认只生成改名计划;`--apply` 会先备份 SQLite,并在数据库更新失败时把文件名回滚。两者导入模块时均无副作用,测试不得使用真实路径。++`/api/providers` 是无副作用 capability health;`/api/providers/opencode-go/models` 只在显式访问时拉取 OpenCode Go 的公开模型清单,不发送推理请求或读取本机 CLI 凭据。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex e0f42e050..3a4ea1415 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -22,6 +22,7 @@ Runtime PIDs are observations, not configuration; always re-check them.- Stash transport is centralized in `StashClient`; ledger imports now write stable `media_binding` external IDs and explicit tag/performer provenance. The new importer was verified only against an isolated database and was not run on the real ledger.- Migration `0002` added canonical entity/alias/external-ref/asset-relation tables and backfilled existing performer/tag/studio/creator/series projections. After the post-migration external-metadata reconciliation, the real ledger has 8,603 entities and 131,877 relations. The Stash and external-metadata importers dual-write canonical relations while retaining flattened UI projections.- Passive `/api/providers` health discovery now exposes separate inference/agent capabilities without model calls, credential reads or secret values.+- The OpenCode Go adapter now supports explicit public model discovery through `/api/providers/opencode-go/models`, with a five-minute in-memory cache and normalized secret-free output. It does not invoke inference or read CLI credentials.- Snapshot rows still contain 10,714 pre-split `R:\Resources\Intake\snapshots` paths. Runtime now performs a strict legacy-prefix rebase to `R:\peach-data\generated\snapshots`; it does not mutate the real ledger.- `R:\peach-data` now separates `database/generated/sources/state/secrets/logs/archive/inbox/tools`; the old empty root Inbox and old Resources/Tools compatibility surface are removed.- `web_contract.py` now uses an application-owned database/cache/write-lock context rather than module globals; separate app instances cannot leak databases or caches into each other.@@ -57,5 +58,5 @@ Runtime PIDs are observations, not configuration; always re-check them.## Next work1. Add the first tracked online-follow source adapter; keep metadata scraping as a reviewable batch pipeline.-2. Implement an OpenCode Go inference health/model adapter without enabling automatic ledger writes.-3. Move creator/studio top lists and related-item ranking from compatibility text fields to canonical relations.+2. Move creator/studio top lists and related-item ranking from compatibility text fields to canonical relations.+3. Add reviewed inference requests behind the OpenCode Go adapter; AI output must remain a candidate and cannot write ledger truth directly.diff --git a/docs/adr/0003-ai-provider-boundaries.md b/docs/adr/0003-ai-provider-boundaries.mdindex d5902032b..85d6d82f7 100644--- a/docs/adr/0003-ai-provider-boundaries.md+++ b/docs/adr/0003-ai-provider-boundaries.md@@ -15,6 +15,7 @@ Codex/Claude Code 是带线程、工具和权限的 agent runtime;OpenCode Go- Claude 正式发布默认使用 API key/云 provider。调用用户本机已登录 `claude` 的订阅 adapter 只标为 personal-local experimental;Peach 不实现 Claude.ai 登录、不读取或保存 OAuth 凭据。- 第一阶段只提交接口、配置与无副作用 health 边界,不发送真实模型请求。- 第一阶段 registry 与受认证的 `/api/providers` health 已实现;它只检查本机命令可用性并返回公开 capability,不联网、不读取凭据、不返回可执行文件路径。+- OpenCode Go 的首个真实 adapter 仅实现公开模型发现:显式请求 `/api/providers/opencode-go/models` 时读取官方 `/zen/go/v1/models`,结果缓存 5 分钟并只返回规范字段。它不调用推理端点、不读取 OpenCode CLI 的凭据文件。- AI 只能生成候选、解释与补全;写入 ledger 真相字段必须经过 provenance/confidence/review。## 凭据@@ -26,3 +27,8 @@ Codex/Claude Code 是带线程、工具和权限的 agent runtime;OpenCode Go- 抓浏览器 Cookie 或复制 OAuth token。- 把 Codex/Claude CLI stdout 当稳定的通用推理 API。- 阶段一增加独立 AI gateway 或微服务。++## 协议依据++- OpenCode Go endpoints 与模型列表:<https://opencode.ai/docs/go/>+- Provider/API key 配置边界:<https://opencode.ai/docs/providers>diff --git a/src/peach/api.py b/src/peach/api.pyindex 8420ed61a..36b447d81 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -13,7 +13,7 @@ from .ffmpeg import FFmpegResolverfrom .media import FilesystemMediaService, MediaNotFound, MediaUnavailablefrom .mdns import MdnsPublisherfrom .previews import PreviewService, PreviewUnavailable-from .providers import default_registry+from .providers import OpenCodeGoClient, ProviderUnavailable, default_registryfrom .repository import LedgerRepository@@ -52,6 +52,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled) if settings.mdns_enabled else Noneproviders = default_registry()+ opencode_go = OpenCodeGoClient()@asynccontextmanagerasync def lifespan(_app: FastAPI):@@ -82,6 +83,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:app.state.preview_service = preview_serviceapp.state.mdns = mdnsapp.state.providers = providers+ app.state.opencode_go = opencode_go@app.middleware("http")async def no_store(request: Request, call_next):@@ -201,6 +203,17 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:return JSONResponse({"error": "unauthorized"}, status_code=401)return providers.health()+ @app.get("/api/providers/opencode-go/models")+ def opencode_go_models(request: Request):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ try:+ models = opencode_go.list_models()+ except ProviderUnavailable:+ return JSONResponse({"error": "provider unavailable"}, status_code=502)+ return {"ok": True, "provider": "opencode-go", "models": models}+@app.get("/api/{route:path}")def api_get(route: str, request: Request):args = _first_query_values(request)diff --git a/src/peach/providers.py b/src/peach/providers.pyindex f989a4e0f..1cc428ab3 100644--- a/src/peach/providers.py+++ b/src/peach/providers.py@@ -2,11 +2,78 @@from __future__ import annotationsimport shutil+import json+import threading+import time+import urllib.error+import urllib.requestfrom dataclasses import asdict, dataclassfrom enum import Enumfrom typing import Callable, Protocol+OPENCODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1"+++class ProviderUnavailable(RuntimeError):+ pass+++def _read_http(request: urllib.request.Request, timeout: float) -> bytes:+ with urllib.request.urlopen(request, timeout=timeout) as response:+ return response.read()+++class OpenCodeGoClient:+ """OpenCode Go public model discovery; completion protocols remain separate."""++ def __init__(self, api_key: str | None = None, *, base_url: str = OPENCODE_GO_BASE_URL,+ timeout: float = 10.0,+ transport: Callable[[urllib.request.Request, float], bytes] = _read_http,+ cache_ttl: float = 300.0):+ self._api_key = api_key+ self.base_url = base_url.rstrip("/")+ self.timeout = timeout+ self.transport = transport+ self.cache_ttl = cache_ttl+ self._cache: tuple[float, list[dict]] | None = None+ self._lock = threading.Lock()++ @property+ def configured(self) -> bool:+ return bool(self._api_key)++ def list_models(self) -> list[dict]:+ now = time.monotonic()+ with self._lock:+ if self._cache and now - self._cache[0] < self.cache_ttl:+ return [dict(item) for item in self._cache[1]]+ headers = {"Accept": "application/json", "User-Agent": "Peach/0.2"}+ if self._api_key:+ headers["Authorization"] = "Bearer " + self._api_key+ request = urllib.request.Request(self.base_url + "/models", headers=headers)+ try:+ raw = self.transport(request, self.timeout)+ payload = json.loads(raw.decode("utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError, urllib.error.URLError) as exc:+ raise ProviderUnavailable("OpenCode Go model discovery failed") from exc+ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, list):+ raise ProviderUnavailable("OpenCode Go returned an invalid model list")+ models = []+ for item in data:+ if not isinstance(item, dict) or not item.get("id"):+ continue+ models.append({+ "id": str(item["id"]),+ "object": str(item.get("object") or "model"),+ "owned_by": str(item.get("owned_by") or "opencode"),+ })+ with self._lock:+ self._cache = (now, models)+ return [dict(item) for item in models]++class ProviderKind(str, Enum):INFERENCE = "inference"AGENT = "agent"diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 277de3904..8167fc27d 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -3,6 +3,7 @@ import sqlite3import tempfileimport unittestfrom pathlib import Path+from unittest.mock import patchHAS_DEPS = all(importlib.util.find_spec(name) for name in ("fastapi", "httpx"))@@ -131,6 +132,19 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(len(payload["providers"]), 3)self.assertNotIn("secret_ref", response.text)+ async def test_opencode_models_endpoint_is_explicit_and_normalized(self):+ denied = await self.client.get("/api/providers/opencode-go/models")+ self.assertEqual(denied.status_code, 401)+ with patch("peach.api.OpenCodeGoClient.list_models", return_value=[{+ "id": "kimi-k3", "object": "model", "owned_by": "opencode",+ }]) as discover:+ response = await self.client.get(+ "/api/providers/opencode-go/models?t=secret",+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["models"][0]["id"], "kimi-k3")+ discover.assert_called_once_with()+async def test_post_writes_only_test_database(self):response = await self.client.post("/api/activity", headers={"X-Token": "secret"},diff --git a/tests/test_providers.py b/tests/test_providers.pyindex a673e1f44..ca9e8e20b 100644--- a/tests/test_providers.py+++ b/tests/test_providers.py@@ -1,8 +1,9 @@import unittest+import jsonfrom peach.providers import (- ProviderCapabilities, ProviderKind, ProviderRegistry, ProviderStatus,- default_registry,+ OpenCodeGoClient, ProviderCapabilities, ProviderKind, ProviderRegistry,+ ProviderStatus, ProviderUnavailable, default_registry,)@@ -38,6 +39,38 @@ class ProviderRegistryTests(unittest.TestCase):with self.assertRaisesRegex(ValueError, "duplicate provider id"):registry.register(status)+ def test_opencode_model_discovery_is_normalized_and_cached(self):+ calls = []++ def transport(request, timeout):+ calls.append((request.full_url, request.get_header("Authorization"), timeout))+ return json.dumps({"object": "list", "data": [+ {"id": "kimi-k3", "object": "model", "owned_by": "opencode", "extra": "drop"},+ {"missing": "id"},+ ]}).encode()++ client = OpenCodeGoClient(+ "test-secret", transport=transport, cache_ttl=300, timeout=3,+ )+ first = client.list_models()+ second = client.list_models()++ self.assertTrue(client.configured)+ self.assertEqual(first, [{+ "id": "kimi-k3", "object": "model", "owned_by": "opencode",+ }])+ self.assertEqual(second, first)+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0], (+ "https://opencode.ai/zen/go/v1/models", "Bearer test-secret", 3,+ ))+ self.assertNotIn("test-secret", repr(first))++ def test_opencode_invalid_payload_is_provider_error(self):+ client = OpenCodeGoClient(transport=lambda *_: b'{"unexpected":true}')+ with self.assertRaises(ProviderUnavailable):+ client.list_models()+if __name__ == "__main__":unittest.main()