@wengine-ai/ccr-provider-gemini-agy-acp 0.0.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1 — 2026-11-24
4
+
5
+ Reliable MCP tool exposure and desktop-gateway proxy support. The worker now spawns `agy acp --process-per-session` instead of `agy acp --sandbox`: the sandbox mode restricted the agent toolset and excluded the session MCP servers, so caller tools never reached the model. A session is eagerly connected to the caller's MCP server through the capability-gated `_meta.antigravity.eagerMcpServers` extension, every advertised tool carries `antigravity/alwaysLoad`, and a 18,000-token budget fitter trims only description prose (never schema keys, and it never drops a tool) to stay inside agy's customization limit. A single bounded 250 ms retry absorbs the startup "not logged in" authentication race; quota, 429 and credential failures are never retried. Desktop gateways without inherited proxy variables now resolve the configured proxy and inject it into every agy child, with a loopback `NO_PROXY` exclusion so the local MCP bridge is never proxied. Native agent tools are deliberately left enabled and no client fingerprint is spoofed. The MCP server handed to `session/new` now uses the stdio transport: the agent spawns a bundled newline JSON-RPC forwarder to the in-process loopback bridge, which works around agy's unreliable HTTP-MCP tool exposure and a Windows verbatim `\\?\` executable path that made the agent silently drop the server. The MCP handshake also answers `server/discover` and echoes the string protocol revision. Permission prompts are approved only for the caller-tool bridge and denied for every native agent tool, so the agent can never gain host command execution through an approved permission.
6
+
7
+ 可靠的 MCP 工具暴露与桌面网关代理支持。worker 现在以 `agy acp --process-per-session` 而非 `agy acp --sandbox` 启动:sandbox 模式会限制 agent 工具集并排除会话 MCP 服务,导致调用方工具无法到达模型。会话通过能力门控的 `_meta.antigravity.eagerMcpServers` 扩展主动连接调用方 MCP 服务,每个工具带 `antigravity/alwaysLoad` 标记,并由 18,000 token 预算拟合器只裁剪描述文本(绝不改 schema 键、绝不丢工具)以控制在 agy 定制预算内。单次有界 250ms 重试吸收启动期「未登录」认证竞态;配额、429 与凭据失败绝不重试。无继承代理变量的桌面网关现在会解析配置代理并注入每个 agy 子进程,同时加环回 `NO_PROXY` 排除,确保本地 MCP 桥不走代理。agent 原生工具按合规要求保持启用,且不伪造客户端指纹。交给 `session/new` 的 MCP 服务改用 stdio 传输:agent 启动内置的行式 JSON-RPC 转发进程连接进程内环回桥,绕开 agy 不可靠的 HTTP MCP 工具暴露,以及 Windows verbatim `\\?\` 可执行路径导致 agent 静默丢弃服务的问题;MCP 握手同时应答 `server/discover` 并回显字符串协议版本。权限请求仅对调用方工具桥放行,对所有 agent 原生工具保持拒绝,agent 无法借获批的权限在宿主执行命令。
8
+
9
+ ## 0.2.0 — 2026-11-24
10
+
11
+ Tool calling. A request that declares tools used to be rejected with `400 agy_unsupported_request`; it is now served. The plugin publishes the caller's tools to the agent through an MCP server bound to `127.0.0.1` (ephemeral port, random bearer token compared with `timingSafeEqual`), the agent raises a call, and the caller receives it as `tool_calls`. The ACP session and the MCP call stay warm, so the next request carrying the caller's results resumes the same turn instead of starting a new conversation.
12
+
13
+ The agent never executes anything: every tool result is one the caller returned, and a missing answer is reported back as an error rather than hanging the turn. The bridge descriptor, its token and the tool schemas only ever travel to the agent subprocess through `session/new` — never into a response, usage record or log. A tool set the agent cannot serve produces an explicit `400` naming the reasons instead of a silent answer. Parked calls are keyed per caller, so two interleaved conversations cannot resume each other's turn, and the default worker count is 2 because a parked call holds its worker warm.
14
+
15
+ 工具调用。此前声明了工具的请求会以 `400 agy_unsupported_request` 被拒绝,现在可以正常服务:插件把调用方的工具通过只监听 `127.0.0.1` 的 MCP 服务(随机端口、随机 Bearer token,`timingSafeEqual` 比较)发布给 agent,agent 发起调用,调用方收到 `tool_calls`。ACP 会话与 MCP 调用保持存活,因此带回执行结果的后续请求会续跑同一个回合,而不是新开一段对话。
16
+
17
+ agent 不执行任何工具:每个结果都来自调用方,缺失的结果以错误回传,不会让回合无限等待。桥的描述符、token 与工具 schema 只经 `session/new` 传给 agent 子进程,绝不进入响应、用量记录或日志。agent 无法服务的工具集会得到明确的 `400` 并说明原因,而不是静默作答。挂起的调用按调用方归属,两个交错会话不会互相续跑对方的回合;默认 worker 数为 2,因为挂起的调用需要占用 worker 保温。
18
+
19
+ ## 0.1.0 — 2026-11-19
20
+
21
+ Ship the connect slice. The management card now drives the whole opt-in flow over new local-only admin routes (`/api/gemini-agy-acp/status`, `/connect`, `/disconnect`, `/models/sync`, guarded by the loopback + Origin allowlist shared with the other provider plugins): Connect validates the absolute binary path, probes `agy --version` (5 s cap, 1.5.1+ required), persists the sidecar with the optional API key at 0600 and respawns the worker pool; Disconnect disables the provider and retires the workers; Model sync runs one bounded (≤5 s) temporary worker through the ACP handshake and stores the advertised model catalog. Status reports loaded/enabled/binary/version/model count, a non-reversible credential fingerprint (first 10 hex of the key's SHA-256, so operators can tell WHICH key is connected without exposing it), and the full synced model catalog behind an expandable list — without ever serializing the key. Sidecar edits apply to the next request without a gateway restart, and an explicit sidecar `apiKey` now takes precedence over the `GEMINI_API_KEY` process environment. Synced models are also written to the provider's `models` list in `config.json` (Router untouched), creating the provider entry with the managed marker if missing, and the isolated worker environment forwards standard proxy variables from the CCR process. The hand-written JSON setup instructions are replaced by the card flow; the same sidecar file remains the source of truth. When no agy is detected, the card auto-installs the official release for the current OS/architecture (pinned vendor manifest, HTTPS-only download through the gateway's proxy environment, SHA-512 verification, vendor-host payload allowlist, official default install location); the background install is single-flight with status polling, failures surface stable codes with an explicit retry, and installing never enables the provider — Connect stays the only enabling action. Per-model visibility rounds this out: model list rows show `name · id` with a hide/restore toggle plus a restore-all control, the credential line names the AI Studio key, and a new local-only `POST /api/gemini-agy-acp/models/visibility` route validates ids against the synced catalog and persists a normalized `hiddenModels` set (≤256 bounded entries) in the sidecar — hidden models stay hidden across re-syncs, ids that disappear upstream are dropped from the set silently, and the provider's registered `models` always reflect the visible catalog only. OAuth personal login rounds this out: the card gains a 登录方式 segmented toggle (API key / Google 账号) persisted per connect call, Google-account mode hides the key input entirely and Connect verifies the CLI's real OS-keyring browser login with one bounded ACP handshake (authenticate + session/new) on a temporary worker of the selected binary — `--version` alone cannot prove the login — mapping any handshake failure to a stable terminal sign-in hint. The account email shown on the card comes exclusively from that verified handshake (explicit ACP account metadata, or the verifying child's own bounded captured diagnostics; never stale log files, token stores or other processes' state) and the card shows 账号邮箱未提供 when the CLI provides none. oauth-personal pools spawn on a fresh temporary working directory with a whitelist of only runtime/login-required environment variables — never a blanket `process.env` copy, and never credential variables such as `GEMINI_API_KEY` — while API-key pools keep the fully isolated environment; `settings` rejects any apiKey alongside oauth-personal, switching modes evicts the other mode's stored credential/stale account email, and model sync works without any key in Google-account mode.
22
+
23
+ 新增连接闭环。管理卡片通过全新的仅限本地的管理路由(`/api/gemini-agy-acp/status`、`/connect`、`/disconnect`、`/models/sync`,沿用其他供应商插件的回环 + Origin 白名单守卫)驱动完整启用流程:连接会校验 binary 绝对路径、探测 `agy --version`(5 秒上限,要求 1.5.1+)、把可选 API key 以 0600 权限写入 sidecar 并重建 worker 池;断开停用供应商并回收 worker;同步模型以一个 ≤5 秒的临时 worker 完成 ACP 握手并保存 CLI 公布的模型目录。状态行展示 loaded/enabled/binary/version/模型数量、不可逆的凭据指纹(key 的 SHA-256 前 10 位,便于确认连的是哪把钥匙而不暴露密钥),以及可展开的完整已同步模型列表,且从不序列化密钥。sidecar 修改无需重启网关即可在下一个请求生效;显式的 sidecar `apiKey` 优先于进程环境变量 `GEMINI_API_KEY`。同步出的模型会写入 `config.json` 供应商条目的 `models`(不动 Router);隔离 worker 环境会转发 CCR 进程的标准代理变量。手工 JSON 配置说明由卡片流程取代,sidecar 文件仍是唯一配置来源。未检测到 agy 时,卡片按当前系统/架构自动安装官方发布版(固定厂商清单、仅 HTTPS 且继承网关代理环境、SHA-512 校验、载荷域名白名单、官方默认安装位置);后台安装单飞执行并由卡片轮询状态,失败显示稳定错误码与显式重试,安装绝不启用供应商——连接仍是唯一的启用操作。模型级可见性补全了这一环:模型列表行展示 `name · id` 并带隐藏/恢复切换与一键全部恢复,凭据行标明 AI Studio key;新增仅限本地的 `POST /api/gemini-agy-acp/models/visibility` 路由对照已同步目录校验 id,并把规范化的 `hiddenModels`(≤256 条有界条目)持久化到 sidecar —— 重新同步后隐藏集合保留,上游消失的 id 会被静默清理,供应商注册的 `models` 始终只反映可见目录。Google 账号个人登录补全了这一环:卡片新增登录方式分段切换(API key / Google 账号),随每次连接持久化;Google 账号模式完全隐藏密钥输入框,连接时以选中 binary 的一个有界真实 ACP 握手(authenticate + session/new)验证 CLI 自身的 OS 钥匙串浏览器登录(仅 `--version` 无法证明登录有效),任何握手失败都会映射为稳定的「请先在终端运行一次 agy 完成浏览器登录」提示。卡片展示的账号邮箱只来自本次已验证的握手(显式 ACP 账号元数据,或验证子进程自身有界捕获的诊断输出;绝不读取陈旧日志文件、令牌存储或其他进程的状态),CLI 未提供时显示「账号邮箱未提供」。oauth-personal 工作进程在全新的临时工作目录上、以仅含运行/登录所需环境变量的白名单启动——绝不透传全量 `process.env`,也绝不传递 `GEMINI_API_KEY` 等凭据变量;API key 池仍使用完全隔离环境;`settings` 拒绝 oauth-personal 携带任何 apiKey,切换模式会清除另一模式存储的凭据或陈旧账号邮箱,Google 账号模式下同步模型无需任何密钥。
24
+
25
+ ## 0.0.3 — 2026-11-19
26
+
27
+ Restyle the management card to match the other provider cards: the host settings page stylesheet (Tailwind utilities plus the custom glass-card rule) now drives the look, with the shared container, header, badge variants and section styling. Setup instructions are collapsed by default. The authentication badge identifies API-key billing.
28
+
29
+ 管理卡片样式与其他供应商卡片对齐:改用宿主设置页样式表(Tailwind 工具类与自定义 glass-card 规则),容器、头部、徽章与分区样式保持一致。配置说明默认折叠,认证徽章标明使用 API key 计费。
30
+
3
31
  ## 0.0.2 — 2026-11-19
4
32
 
5
33
  Ship a read-only management card. The settings page reports a card load failure for every enabled plugin without one, so the previous release showed a misleading reinstall hint. The card explains the local opt-in contract and requires no network access.
package/README.md CHANGED
@@ -2,16 +2,16 @@
2
2
 
3
3
  Experimental local provider for CCR 2.3.2433 (provider plugin API 1). A text chat request starts or reuses a local Antigravity CLI worker over ACP stdio. This provider has its own name and configuration, separate from `gemini-oauth`.
4
4
 
5
- **Opt-in and billing.** Use a trusted local `agy` executable and a Gemini API key you are authorized to use. The CLI receives the prompt and may send it to Google's service. API key quotas, charges and terms apply. The CLI runs with the CCR operating system user's permissions. Treat both the executable and the operator configuration as trusted. Consumer OAuth, subscriptions, browser sign-in and account rotation are unsupported.
5
+ **Opt-in and billing.** Use a trusted local `agy` executable and either a Gemini API key you are authorized to use or the CLI's own Google account login (oauth-personal). The CLI receives the prompt and may send it to Google's service. API key quotas, charges and terms apply; Google account usage follows the signed-in account's terms. The CLI runs with the CCR operating system user's permissions. Treat both the executable and the operator configuration as trusted. Consumer subscriptions and account rotation remain unsupported.
6
6
 
7
- **启用与计费。** 本插件为实验原型,默认关闭。仅使用可信的本地 `agy` 程序和有权使用的 Gemini API 密钥。CLI 会收到对话内容,并可能将其发送到 Google 服务。调用受 API 密钥的配额、计费和使用条款约束。CLI 以 CCR 进程的系统用户身份运行。插件不支持个人订阅、浏览器 OAuth 或账号轮换。测试仅使用模拟进程,尚未验证真实账号、费用或上游服务。
7
+ **启用与计费。** 本插件为实验原型,默认关闭。仅使用可信的本地 `agy` 程序,以及有权使用的 Gemini API 密钥或 CLI 自身的 Google 账号登录(oauth-personal)。CLI 会收到对话内容,并可能将其发送到 Google 服务。API 密钥受配额、计费和使用条款约束;Google 账号用量遵循所登录账号的条款。CLI 以 CCR 进程的系统用户身份运行。插件不支持个人订阅或账号轮换。测试仅使用模拟进程,尚未验证真实账号、费用或上游服务。
8
8
 
9
9
  ## Install from npm
10
10
 
11
11
  Run the following in the isolated CCR instance described below. Installing the package leaves the transport disabled until the operator enables it.
12
12
 
13
13
  ```sh
14
- ccr plugin add @wengine-ai/ccr-provider-gemini-agy-acp@0.0.2
14
+ ccr plugin add @wengine-ai/ccr-provider-gemini-agy-acp@0.1.0
15
15
  ```
16
16
 
17
17
  ## Build and install locally
@@ -51,7 +51,34 @@ Place this example in the disposable `$CCR_CONFIG_DIR/config.json`. Replace `mod
51
51
 
52
52
  Use ACP as a **primary route** in an isolated instance with effective `Router.enableFallback` set to `false` and no project or global fallback entries. ACP disables fallback on the primary request once its transformer or dispatcher receives it. Earlier host failures, including `plugin_missing`, occur before the plugin gets the request. CCR can also continue an outer fallback chain if it reached ACP as a fallback candidate. Neither path is controlled by the plugin. Background recovery probes are disabled for this prototype.
53
53
 
54
- To opt in, the local operator writes `$CCR_CONFIG_DIR/gemini-agy-acp.json` before starting the isolated host. This file is read at activation. Omission or `enabled: false` disables execution. `binary` must be an absolute path to a trusted executable (CLI 1.5.1+ with ACP). Worker limit is 1–8 (default 1) and timeout is 1–300000 ms (default 60000). Choose an unused test port and restrict access to these files and the process environment.
54
+ ## Automatic agy install
55
+
56
+ For headless clients, the gateway operator can set `CCR_AGY_INSTALL_ON_USE=1` in the CCR process environment to permit installation on first local model use. With no sidecar or default binary, a direct loopback request starts the same background download and returns `agy_install_in_progress`. After installation, open the local card and connect the account. A saved disconnect is respected. Use the card to retry a failed download.
57
+
58
+ 无界面客户端可在 CCR 网关进程环境设置 `CCR_AGY_INSTALL_ON_USE=1`。首次通过本机直接调用模型时,若尚无连接配置和默认 CLI,会启动后台下载并返回 `agy_install_in_progress`。安装完成后,在本机管理卡连接账号;下载失败可在卡片上重试。
59
+
60
+ When the settings card first opens and no `agy` is detected (no sidecar binary and nothing at the official default location), it starts the official install automatically for the current OS and CPU architecture — macOS/Linux/Windows on x64 or arm64, including the Linux musl builds. The flow mirrors the vendor bootstrappers step for step: the release manifest is queried from the pinned Antigravity updater, the payload downloads over HTTPS only (curl inherits the gateway's `HTTPS_PROXY`/`HTTP_PROXY`/`NO_PROXY` environment), the SHA-512 checksum is verified before anything is placed, and payload URLs are restricted to the vendor's own hosts. The binary lands at `~/.local/bin/agy` on unix and `%LOCALAPPDATA%\agy\bin\agy.exe` on Windows; no remote script is ever piped into a shell.
61
+
62
+ The install runs in the background (single-flight) while the card polls status; a failure shows a stable error code with an explicit **Install agy** retry button and is never retried automatically. Installing never writes the sidecar and never enables the provider — **Connect** remains the only action that persists settings and starts workers. `POST /api/gemini-agy-acp/install` triggers the same flow manually (local-only guard).
63
+
64
+ 首次打开设置卡片时,若未检测到 `agy`(sidecar 未配置 binary,官方默认位置也没有),会按当前系统与 CPU 架构自动安装官方发布版——支持 macOS/Linux/Windows 的 x64 与 arm64(含 Linux musl 构建)。流程与官方引导脚本逐步一致:从固定的 Antigravity 更新器查询发布清单,仅经 HTTPS 下载(curl 继承网关的 `HTTPS_PROXY`/`HTTP_PROXY`/`NO_PROXY` 环境变量),放置任何文件前先校验 SHA-512,下载地址限定厂商自有域名。unix 安装到 `~/.local/bin/agy`,Windows 安装到 `%LOCALAPPDATA%\agy\bin\agy.exe`;绝不把远程脚本管道进 shell。
65
+
66
+ 安装在后台单飞执行,卡片轮询状态;失败时显示稳定错误码与显式「安装 agy」重试按钮,不会自动重试。安装不写 sidecar、不启用供应商——**连接**仍是唯一持久化配置并启动 worker 的操作。`POST /api/gemini-agy-acp/install` 可手动触发同一流程(仅限本机守卫)。
67
+
68
+ ## Enable from the settings card
69
+
70
+ Open the CCR settings page, find the **Local Antigravity CLI (ACP) bridge** card and:
71
+
72
+ 1. Enter the absolute path of your local `agy` executable (CLI 1.5.1+ with ACP).
73
+ 2. Pick the 登录方式 (login mode): **API key** (default) or **Google 账号** (oauth-personal). In API key mode you may optionally enter a Gemini API key — leave the field empty to keep an already stored key or to use the `GEMINI_API_KEY` process environment of the isolated CCR instance. Google-account mode has no key field at all.
74
+ 3. Press **Connect**. The plugin validates that the path points to an executable, probes `agy --version` with a 5 second cap and requires CLI 1.5.1 or later. API-key mode then writes `$CCR_CONFIG_DIR/gemini-agy-acp.json` and respawns its worker pool. Google-account mode additionally verifies the real login with one bounded ACP handshake (authenticate + session/new) on a temporary worker of the selected binary — `--version` alone cannot prove the OS-keyring browser login works — and maps any handshake failure to a stable sign-in hint. Switching between modes evicts the other mode's stored credential or stale account email. The account email shown on the card comes exclusively from that verified handshake (explicit ACP account metadata, or the verifying child's own captured diagnostics) and is never read from stale log files or token stores; when the CLI provides none, the card shows 账号邮箱未提供.
75
+ 4. Press **Sync models** to read the model catalog the CLI advertises over ACP (one temporary worker, bounded to 5 seconds, authenticating exactly like the request pool). The catalog is stored in the sidecar, shown on the card and written to the provider's `models` list in `config.json` (Router entries are left untouched), so synced models are routable immediately. If the provider entry does not exist yet, Sync models creates it with the managed marker and a placeholder URL — no manual `config.json` editing is needed.
76
+
77
+ The CLI makes its own upstream calls to Google. API-key workers run in an isolated environment that forwards the standard proxy variables (`HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY`, `NO_PROXY`) from the CCR process. Google-account workers must see the CLI's own login state, which an isolated runtime does not guarantee — they run on a fresh temporary working directory with a whitelist of only the runtime/login-required environment (real `HOME`/user profile, `PATH`, temp dirs, platform config locations, GUI/DBus session, proxy variables) and never a blanket copy of `process.env`; credential variables such as `GEMINI_API_KEY` or `GOOGLE_APPLICATION_CREDENTIALS` are never forwarded. Key validity is not verified at Connect time in API-key mode (authentication is a local ACP handshake); an invalid key surfaces the CLI's own upstream error text on the first request — never another account's figures.
78
+
79
+ **Disconnect** disables the provider and retires the workers without deleting the stored settings. The status line reports loaded/enabled state, whether the binary was found, the last probed CLI version and the synced model count, plus the credential line: a non-reversible fingerprint for API-key mode, or the handshake-verified account email (or 账号邮箱未提供) for oauth-personal mode. The card and its routes are local-only: they run under the same loopback + Origin allowlist as the other provider plugins and never return the API key — the status shape carries `apiKeyConfigured` only.
80
+
81
+ Connect writes the sidecar `$CCR_CONFIG_DIR/gemini-agy-acp.json` (mode 0600). The file remains the source of truth, and editing it takes effect on the next request without a gateway restart:
55
82
 
56
83
  ```json
57
84
  {
@@ -63,7 +90,9 @@ To opt in, the local operator writes `$CCR_CONFIG_DIR/gemini-agy-acp.json` befor
63
90
  }
64
91
  ```
65
92
 
66
- Supply `GEMINI_API_KEY` through the isolated CCR process environment. Keep it out of request headers, JSON files, transcripts and source control. The only supported method is `gemini-api-key`. A missing key or unsupported auth method fails the request. The provider captures the API key and sidecar settings at activation. Restart the isolated CCR host with the updated environment to rotate the key for every worker.
93
+ An `apiKey` written by Connect is stored inside this file with 0600 permissions and never appears in logs, config.json, transcripts or responses; oauth-personal mode persists no `apiKey` at all. Worker limit is 1–8 (default 1) and timeout is 1–300000 ms (default 60000). Choose an unused test port and restrict access to these files and the process environment.
94
+
95
+ Supply `GEMINI_API_KEY` through the isolated CCR process environment (together with your proxy variables), or store the key once via Connect. An explicit sidecar `apiKey` takes precedence; without one the transport captures the environment key at pool start. Keep the key out of request headers, JSON files other than the 0600 sidecar, transcripts and source control. Supported `authMethod` values are `gemini-api-key` (optional key with environment fallback) and `oauth-personal` (no key allowed; any key alongside it fails closed). A missing key in API-key mode or an unsupported auth method fails the request.
67
96
 
68
97
  ## Text chat
69
98
 
@@ -83,12 +112,12 @@ Use `/v1/chat/completions` or CCR's `/v1/messages` endpoint. CCR handles Anthrop
83
112
  }
84
113
  ```
85
114
 
86
- Each request gets a fresh ACP session. A single user string is passed directly. Multiple turns become an ordered JSON text transcript in one ACP prompt. Role labels in that transcript do not establish separate privileged system instructions inside the CLI. The adapter accepts `system`, `user`, `assistant` and text blocks. Tool definitions, tool calls/results, named roles and non-text content fail explicitly. The model is matched against the provider catalog and passed intact to the transport. Optional OpenAI `reasoning_effort` or CCR-normalized Anthropic effort selects an advertised thinking option. `xhigh` can match an advertised Extra tier. An unavailable explicit selection fails. Omitting effort leaves the CLI's selection unchanged.
115
+ Each request gets a fresh ACP session. A single user string is passed directly. Multiple turns become an ordered JSON text transcript in one ACP prompt. Role labels in that transcript do not establish separate privileged system instructions inside the CLI. The adapter accepts `system`, `user`, `assistant` and text blocks. Named roles and non-text content fail explicitly. Tool requests are served: the plugin publishes the caller's tools to the agent through an MCP server bound to `127.0.0.1` with a random bearer token, the agent's raised call is reported as `tool_calls`, and the next request carrying the caller's results resumes the same turn. The agent never executes a tool, a missing answer is an error rather than a hang, and the bridge descriptor, token and tool schemas only travel to the agent subprocess. The model is matched against the provider catalog and passed intact to the transport. Optional OpenAI `reasoning_effort` or CCR-normalized Anthropic effort selects an advertised thinking option. `xhigh` can match an advertised Extra tier. An unavailable explicit selection fails. Omitting effort leaves the CLI's selection unchanged.
87
116
 
88
- Non-streaming requests return one OpenAI chat completion. Streaming emits role and text deltas, a finish reason, then `[DONE]` on success. Failures before the first text use HTTP errors. A failure after partial output terminates the stream with an error. The host limits output to 1 MiB of text and 8192 nonempty deltas per response. Token usage, sampling controls, caller token limits, structured output and persistent multi-turn ACP sessions are unsupported. Do not depend on token accounting or these controls in this prototype.
117
+ Non-streaming requests return one OpenAI chat completion. Streaming emits role and text deltas, a finish reason, then `[DONE]` on success. Failures before the first text use HTTP errors. A failure after partial output terminates the stream with an error. The host limits output to 1 MiB of text and 8192 nonempty deltas per response. When ACP reports a complete, consistent token count, the completion or final finish-reason chunk includes OpenAI-style `usage`. Prompt tokens include cache reads and writes, and completion tokens include reasoning. The `usage_source` field identifies these counts to CCR. If either standard input or output count is unavailable, the plugin uses the complete pair from `_meta.quota.token_count` when available. Usage is omitted when a reported total cannot identify a unique prompt/completion split. Sampling controls, caller token limits, structured output and persistent multi-turn ACP sessions are unsupported.
89
118
 
90
- The protocol fixture follows Google's documented ACP v1 invocation, API-key method ID, and session selectors. This prototype handles the protocol-driven authentication method (omitted type or `agent`) and rejects other method types before opening a session. The fixture is synthetic. The exact handshake for a production CLI build still needs verification.
119
+ The protocol fixture follows Google's documented ACP v1 invocation, API-key method ID, and session selectors. This prototype handles the protocol-driven authentication method (omitted type or `agent`) and rejects other method types before opening a session. The fixture is synthetic, including the `oauth-personal` method id, the `accountInfo` metadata and the stderr login line — the exact handshake and account-reporting shape of a production CLI build still needs verification.
91
120
 
92
- Local tests use synthetic text, credentials and subprocess fixtures. Live CLI authentication, model availability, actual sandbox guarantees, provider billing, production load and compatibility with other CCR versions remain unverified. CCR 2.3.2433 has no plugin shutdown callback. The transport retires idle workers and bounds each request.
121
+ Local tests use synthetic text, credentials and subprocess fixtures. Live CLI authentication, model availability, provider billing, production load and compatibility with other CCR versions remain unverified. The plugin spawns `agy acp --process-per-session` without a sandbox flag, so it does not confine the agent's own built-in tools; only the caller-provided MCP tools are bridged, and every raised call is executed by the caller, not by the agent. CCR 2.3.2433 has no plugin shutdown callback. The transport retires idle workers and bounds each request.
93
122
 
94
123
  [Antigravity ACP documentation](https://antigravity.google/docs/ide/extensions/acp/) · [ACP session config options](https://agentclientprotocol.com/protocol/v1/session-config-options)
package/dist/card.js CHANGED
@@ -1,6 +1,18 @@
1
- // Read-only management card: a self-contained ES chunk with no imports and no
2
- // network access. It only explains the local opt-in contract; the operator's
3
- // sidecar file and environment remain the single source of truth.
1
+ // Management card for the local ACP bridge. It renders inside the host
2
+ // settings page, so the host's global stylesheet (Tailwind utilities + the
3
+ // custom .glass-card rule) is part of its runtime environment; class names
4
+ // mirror the gemini-oauth / codex card conventions. Import-free,
5
+ // network-free, and all rendered strings go through textContent, never
6
+ // markup assignment. All traffic rides props.callApi, the host's
7
+ // authenticated, sanitized admin bridge (never the raw browser API).
8
+ const BADGE_BASE = 'inline-flex items-center rounded-lg border px-2.5 py-0.5 text-[10px] font-bold transition-colors';
9
+ const BADGE_OUTLINE = 'border-white/10 text-foreground bg-white/5';
10
+ const BADGE_SECONDARY = 'border-white/5 bg-white/5 text-muted-foreground';
11
+ const BUTTON_BASE = 'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl border px-3 py-1.5 text-xs font-semibold shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50';
12
+ const BUTTON_OUTLINE = 'border-input bg-input/50 hover:bg-input/80 hover:border-primary/50';
13
+ const BUTTON_DESTRUCTIVE = 'border-destructive/50 text-destructive hover:bg-destructive hover:text-destructive-foreground';
14
+ const INPUT_CLASS = 'max-w-md flex h-9 w-full rounded-lg border border-input bg-input/50 px-3 py-1 text-sm shadow-sm placeholder:text-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
15
+
4
16
  const el = (tag, className, text) => {
5
17
  const node = document.createElement(tag);
6
18
  if (className) node.className = className;
@@ -8,61 +20,375 @@ const el = (tag, className, text) => {
8
20
  return node;
9
21
  };
10
22
 
23
+ // Stable route-error codes → one-line localized recovery hints. Unknown codes
24
+ // fall back to the sanitized token itself (never an upstream message).
25
+ const CODE_HINTS = {
26
+ acp_unsupported_version: ['需要 agy 1.5.1 或更新版本。', 'agy 1.5.1 or later is required.'],
27
+ acp_invalid_config: ['请检查 binary 路径:必须指向本机存在的可执行文件。', 'Check the binary path: it must point to an executable on this machine.'],
28
+ acp_auth_required: ['缺少可用的 Gemini API key。', 'No usable Gemini API key is configured.'],
29
+ acp_timeout: ['agy 未在时限内响应。', 'agy did not respond in time.'],
30
+ acp_busy: ['worker 池已满,请稍后重试。', 'Worker pool is busy, try again shortly.'],
31
+ acp_worker_failed: ['agy 进程异常退出。', 'The agy process failed.'],
32
+ acp_protocol_error: ['agy 返回了无法解析的协议响应。', 'agy returned an unparseable protocol response.'],
33
+ acp_output_limit: ['agy 输出超出限制。', 'agy output exceeded the limit.'],
34
+ acp_unsupported_option: ['该 CLI 未公开可选模型。', 'This CLI exposes no selectable model options.'],
35
+ agy_disabled: ['尚未启用,请先连接。', 'Not enabled yet — connect first.'],
36
+ agy_config_invalid: ['gemini-agy-acp.json 无效,可在 CCR 配置目录删除后重试。', 'gemini-agy-acp.json is invalid — delete it in the CCR config directory and retry.'],
37
+ agy_config_write_failed: ['写入配置文件失败。', 'Writing the configuration file failed.'],
38
+ agy_unauthorized: ['仅限本机访问。', 'Local access only.'],
39
+ agy_route_failed: ['管理请求失败,请重试。', 'The management request failed, please retry.'],
40
+ agy_install_unsupported_platform: ['当前系统/架构没有官方 agy 构建。', 'No official agy build exists for this OS/architecture.'],
41
+ agy_install_manifest_failed: ['无法访问 agy 发布服务器,请检查网络或代理。', 'Cannot reach the agy release server — check the network or proxy.'],
42
+ agy_install_manifest_invalid: ['agy 发布清单无效。', 'The agy release manifest is invalid.'],
43
+ agy_install_download_failed: ['下载 agy 失败,请检查网络或代理后重试。', 'Downloading agy failed — check the network or proxy and retry.'],
44
+ agy_install_too_large: ['agy 下载体积超出限制。', 'The agy download exceeded the size limit.'],
45
+ agy_install_checksum_mismatch: ['agy 校验失败,已中止安装。', 'The agy checksum failed; installation was aborted.'],
46
+ agy_install_extract_failed: ['解压 agy 失败。', 'Extracting agy failed.'],
47
+ agy_install_write_failed: ['写入 agy 失败,请检查目录权限。', 'Writing agy failed — check directory permissions.'],
48
+ };
49
+
11
50
  export default {
12
- mount(target, props) {
51
+ async mount(target, props) {
13
52
  const zh = props.locale === 'zh';
14
- const t = (en, cn) => (zh ? cn : en);
15
- const root = el('div', 'ccr-agy-acp-card');
16
- const style = root.style;
17
- style.font = '13px/1.6 -apple-system, "Segoe UI", sans-serif';
18
- style.color = 'inherit';
19
-
20
- const head = el('div', null, null);
21
- head.style.display = 'flex';
22
- head.style.alignItems = 'center';
23
- head.style.gap = '8px';
24
- const title = el('strong', null, t('Local Antigravity CLI (ACP) bridge', '本地 Antigravity CLI(ACP)桥'));
25
- const badge = el('span', null, props.disabled ? t('Disabled', '未启用') : t('Enabled', '已启用'));
26
- badge.style.padding = '1px 8px';
27
- badge.style.borderRadius = '999px';
28
- badge.style.fontSize = '12px';
29
- badge.style.border = '1px solid currentColor';
30
- if (!props.disabled) badge.style.opacity = '0.85'; else badge.style.opacity = '0.6';
31
- head.append(title, badge);
32
- root.append(head);
33
-
34
- if (props.plugin?.version) root.append(el('div', null, t('Version', '版本') + ': v' + props.plugin.version));
35
-
36
- for (const line of props.disabled ? [
37
- t('This prototype is off until the operator enables it. In the CCR config directory create gemini-agy-acp.json:',
38
- '原型在运维者显式启用前保持关闭。请在 CCR 配置目录创建 gemini-agy-acp.json:'),
39
- ] : [
40
- t('Workers start only for requests routed to this provider; API-key quotas and charges apply.',
41
- '仅路由到本供应商的请求会启动 worker;调用计入 API key 配额与费用。'),
42
- t('Rotate the key by updating the environment and restarting the isolated CCR host.',
43
- '更换密钥需更新环境变量并重启隔离的 CCR 实例。'),
44
- ]) root.append(el('p', null, line));
45
-
46
- const code = el('pre', null, JSON.stringify({
47
- enabled: true, binary: '/absolute/path/to/agy', authMethod: 'gemini-api-key', maxWorkers: 1, timeoutMs: 60000,
48
- }, null, 2));
49
- code.style.background = 'rgba(127,127,127,.12)';
50
- code.style.padding = '8px 10px';
51
- code.style.borderRadius = '6px';
52
- code.style.overflowX = 'auto';
53
- code.style.whiteSpace = 'pre-wrap';
54
- root.append(code);
55
-
56
- root.append(el('p', null, t(
57
- 'Set GEMINI_API_KEY in the CCR process environment and route a primary model to gemini-agy-acp. Consumer OAuth and subscriptions are unsupported.',
58
- '在 CCR 进程环境设置 GEMINI_API_KEY,并把主路由模型指向 gemini-agy-acp。不支持个人订阅与浏览器 OAuth。')));
59
-
60
- target.append(root);
61
- this._root = root;
53
+ const t = (cn, en) => (zh ? cn : en);
54
+ const call = typeof props.callApi === 'function' ? props.callApi : null;
55
+
56
+ const card = el('div', 'glass-card rounded-2xl overflow-hidden mb-4');
57
+ const layout = el('div', 'flex flex-col gap-4 p-5');
58
+ const body = el('div', 'min-w-0 flex-1 space-y-3');
59
+
60
+ const header = el('div', 'flex flex-wrap items-center gap-2');
61
+ header.append(
62
+ el('p', 'text-lg font-bold tracking-tight text-foreground', t('本地 Antigravity CLI(ACP)桥', 'Local Antigravity CLI (ACP) bridge')),
63
+ el('span', BADGE_BASE + ' ' + BADGE_OUTLINE + ' border-amber-500/40 text-amber-600', t('实验原型', 'Experimental')),
64
+ el('span', BADGE_BASE + ' ' + BADGE_SECONDARY, 'API key'),
65
+ );
66
+ body.append(header);
67
+
68
+ body.append(el('p', 'max-w-md truncate text-xs font-medium text-muted-foreground/60', props.plugin?.version ? 'v' + props.plugin.version : ''));
69
+ body.append(el('p', 'max-w-md text-xs text-muted-foreground',
70
+ t('通过官方 agy 二进制以 ACP stdio 提供纯文本对话,走 Gemini API key 配额或已登录的 Google 账号。',
71
+ 'Text-only chat through the official agy binary over ACP stdio, billed to the Gemini API key or the signed-in Google account.')));
72
+
73
+ const statusLine = el('p', 'max-w-md text-xs font-medium text-muted-foreground', '');
74
+ body.append(statusLine);
75
+ // Synced model list (collapsed by default) and credential fingerprint.
76
+ const modelsBox = el('details', 'max-w-md text-xs text-muted-foreground');
77
+ modelsBox.append(el('summary', null, t('模型列表', 'Model list')));
78
+ const modelsList = el('ul', 'list-disc pl-5');
79
+ modelsBox.append(modelsList);
80
+ const restoreAll = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE + ' mt-1 px-2 py-0.5 text-[10px]',
81
+ t('恢复全部', 'Restore all'));
82
+ restoreAll.type = 'button';
83
+ restoreAll.hidden = true;
84
+ modelsBox.append(restoreAll);
85
+ modelsBox.hidden = true;
86
+ body.append(modelsBox);
87
+
88
+ const binaryInput = el('input', INPUT_CLASS);
89
+ binaryInput.type = 'text';
90
+ binaryInput.placeholder = t('/绝对路径/to/agy', '/absolute/path/to/agy');
91
+ const keyInput = el('input', INPUT_CLASS);
92
+ keyInput.type = 'password';
93
+ keyInput.placeholder = t('Gemini API key(可选,留空沿用现有密钥或环境变量)',
94
+ 'Gemini API key (optional; leave empty to keep the stored key or environment variable)');
95
+ keyInput.setAttribute('autocomplete', 'new-password');
96
+ keyInput.value = ''; // the stored apiKey is never rendered back into the form
97
+ // 登录方式 segmented toggle: the choice persists per connect call as the
98
+ // sidecar's authMethod (reported back by /status). Google-account mode
99
+ // hides the key input entirely — its credential is the CLI's own browser
100
+ // login, verified by connect through one real ACP handshake. The account
101
+ // email is shown only when that handshake explicitly provided one;
102
+ // otherwise the explicit 账号邮箱未提供 placeholder is shown.
103
+ let authMode = 'gemini-api-key';
104
+ const OAUTH_LOGIN_HINT = ['请先在终端运行一次 agy 完成浏览器登录', 'Run agy once in a terminal to complete the browser sign-in first'];
105
+ const authToggle = el('div', 'flex max-w-md items-center gap-2');
106
+ const keyModeButton = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('API key', 'API key'));
107
+ const oauthModeButton = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('Google 账号', 'Google account'));
108
+ keyModeButton.type = oauthModeButton.type = 'button';
109
+ authToggle.append(keyModeButton, oauthModeButton);
110
+ const accountLine = el('p', 'max-w-md truncate text-xs font-semibold text-foreground', '');
111
+ const form = el('div', 'max-w-md space-y-2');
112
+ form.append(binaryInput, keyInput);
113
+ body.append(authToggle, accountLine, form);
114
+
115
+ const renderAuthMode = () => {
116
+ const oauth = authMode === 'oauth-personal';
117
+ keyInput.hidden = oauth;
118
+ accountLine.hidden = !oauth || !accountLine.textContent;
119
+ keyModeButton.className = BUTTON_BASE + ' ' + BUTTON_OUTLINE + (oauth ? ' opacity-60' : ' border-primary/60 bg-input/80');
120
+ oauthModeButton.className = BUTTON_BASE + ' ' + BUTTON_OUTLINE + (oauth ? ' border-primary/60 bg-input/80' : ' opacity-60');
121
+ keyModeButton.setAttribute('aria-pressed', String(!oauth));
122
+ oauthModeButton.setAttribute('aria-pressed', String(oauth));
123
+ };
124
+ keyModeButton.onclick = () => { authMode = 'gemini-api-key'; renderAuthMode(); };
125
+ oauthModeButton.onclick = () => { authMode = 'oauth-personal'; renderAuthMode(); };
126
+
127
+ const statusText = status => {
128
+ if (status?.installing) {
129
+ return t('正在自动安装 agy(官方发布,SHA-512 校验)…', 'Installing agy automatically (official release, SHA-512 verified)…');
130
+ }
131
+ if (!status || status.enabled !== true) {
132
+ return t('未启用 — 填写 binary 后按连接', 'Not enabled — fill in the binary path and press Connect');
133
+ }
134
+ const parts = [status.loaded ? t('已连接', 'Connected') : t('已启用,等待首个请求', 'Enabled, waiting for the first request')];
135
+ if (status.binaryFound === false) parts.push(t('binary 未找到', 'binary not found'));
136
+ else if (status.version) parts.push(`agy ${status.version}`);
137
+ if (Array.isArray(status.models) && status.models.length) {
138
+ // The count stays the TOTAL catalog size; hidden ones are extra info.
139
+ const hiddenCount = Array.isArray(status.hiddenModels) ? status.hiddenModels.length : 0;
140
+ parts.push(t(`${status.models.length} 个模型`, `${status.models.length} models`) +
141
+ (hiddenCount > 0 ? t(`(已隐藏 ${hiddenCount})`, ` (${hiddenCount} hidden)`) : ''));
142
+ } else if (typeof status.modelsSyncedAt === 'number') {
143
+ parts.push(t('0 个模型', '0 models'));
144
+ }
145
+ // Credential line: oauth pools report the handshake-verified account
146
+ // (or the explicit not-provided placeholder); API-key pools keep the
147
+ // fingerprint line.
148
+ if (status?.authMethod === 'oauth-personal') {
149
+ parts.push(status.accountEmail
150
+ ? t(`账号 ${status.accountEmail}`, `account ${status.accountEmail}`)
151
+ : t('账号邮箱未提供', 'account email not provided'));
152
+ } else if (status.apiKeyFingerprint) {
153
+ parts.push(t(`AI Studio key 凭据 ${status.apiKeyFingerprint}…`, `AI Studio key credential ${status.apiKeyFingerprint}…`));
154
+ } else if (status.apiKeyConfigured !== true) parts.push(t('缺少 API key', 'no API key'));
155
+ if (status.lastError?.code) parts.push(t(`上次错误 ${status.lastError.code}`, `last error ${status.lastError.code}`));
156
+ return parts.join(' · ');
157
+ };
158
+
159
+ const message = el('p', 'max-w-md text-xs text-destructive', '');
160
+ const notice = el('p', 'max-w-md text-xs font-medium text-emerald-600', '');
161
+ const setMessage = text => { message.textContent = text || ''; };
162
+ const setNotice = text => { notice.textContent = text || ''; };
163
+ const errorText = error => {
164
+ const code = error?.reason ?? error?.code;
165
+ // OAuth login failures surface the terminal sign-in hint instead of the
166
+ // API-key hint; every other code keeps its static mapping.
167
+ if (code === 'acp_auth_required' && authMode === 'oauth-personal') return t(OAUTH_LOGIN_HINT[0], OAUTH_LOGIN_HINT[1]);
168
+ const hint = typeof code === 'string' ? CODE_HINTS[code] : null;
169
+ if (hint) return t(hint[0], hint[1]);
170
+ return typeof code === 'string' ? `${t('操作失败', 'The action failed')} (${code})` : t('操作失败', 'The action failed');
171
+ };
172
+
173
+ const connect = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('连接', 'Connect'));
174
+ const sync = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('同步模型', 'Sync models'));
175
+ const disconnect = el('button', BUTTON_BASE + ' ' + BUTTON_DESTRUCTIVE, t('断开', 'Disconnect'));
176
+ // Manual install / retry: shown only while no agy is detected anywhere or
177
+ // the last auto-install failed. The first card view auto-starts it.
178
+ const install = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('安装 agy', 'Install agy'));
179
+ install.hidden = true;
180
+ for (const button of [connect, sync, disconnect, install]) button.type = 'button';
181
+ const controls = [connect, sync, disconnect, install];
182
+ const buttons = el('div', 'flex flex-wrap items-center gap-2');
183
+ buttons.append(connect, sync, disconnect, install);
184
+ body.append(buttons, notice, message);
185
+
186
+ let busyDepth = 0;
187
+ let latestStatus = null;
188
+ let installingNow = false;
189
+ let wasInstalling = false;
190
+ let pollTimer = null;
191
+ const BUSY_LABELS = new Map([[connect, t('连接中…', 'Connecting…')], [sync, t('同步中…', 'Syncing…')], [disconnect, t('断开中…', 'Disconnecting…')], [install, t('安装中…', 'Installing…')]]);
192
+ // Per-model visibility controls live inside the freshly rendered list;
193
+ // setBusy keeps them disabled together with the three fixed actions and
194
+ // the auth-mode toggle.
195
+ let rowButtons = [];
196
+ let currentHiddenIds = [];
197
+ const applyDisabled = () => {
198
+ const busy = busyDepth > 0;
199
+ for (const button of [...controls, ...rowButtons, restoreAll, keyModeButton, oauthModeButton]) {
200
+ // A running background install locks the actions too: connecting a
201
+ // half-downloaded binary must not be possible from the card.
202
+ button.disabled = busy || !call || installingNow;
203
+ const busyLabel = BUSY_LABELS.get(button);
204
+ if (busy && busyLabel) button.textContent = busyLabel;
205
+ }
206
+ if (!busy) {
207
+ connect.textContent = t('连接', 'Connect');
208
+ sync.textContent = t('同步模型', 'Sync models');
209
+ disconnect.textContent = t('断开', 'Disconnect');
210
+ install.textContent = installingNow ? t('安装中…', 'Installing…') : t('安装 agy', 'Install agy');
211
+ }
212
+ };
213
+ const setBusy = active => {
214
+ busyDepth = Math.max(0, busyDepth + (active ? 1 : -1));
215
+ applyDisabled();
216
+ props.onBusy?.(busyDepth > 0);
217
+ };
218
+
219
+ const renderStatus = status => {
220
+ latestStatus = status;
221
+ installingNow = Boolean(status?.installing);
222
+ // Poll while the background download runs; surface the outcome once it
223
+ // finishes (success prefills the detected binary, failure shows the hint).
224
+ if (installingNow && !pollTimer && !target.__agyDisposed) {
225
+ pollTimer = setInterval(() => { void refresh(); }, 3000);
226
+ target.__agyPollTimer = pollTimer;
227
+ } else if (!installingNow && pollTimer) {
228
+ clearInterval(pollTimer);
229
+ pollTimer = null;
230
+ target.__agyPollTimer = null;
231
+ }
232
+ // A detected binary supersedes any stale install failure: the operator
233
+ // may have installed agy manually after a failed auto-install.
234
+ const binaryPresent = Boolean(status?.binary || status?.detectedBinary);
235
+ if (wasInstalling && !installingNow) {
236
+ if (status?.detectedBinary) setNotice(t('agy 已安装,可直接连接', 'agy installed — press Connect'));
237
+ else if (status?.installError && !binaryPresent) setMessage(errorText({ code: status.installError.code }));
238
+ }
239
+ wasInstalling = installingNow;
240
+ install.hidden = binaryPresent;
241
+ if (status?.installError && !installingNow && !binaryPresent) setMessage(errorText({ code: status.installError.code }));
242
+ statusLine.textContent = statusText(status);
243
+ // ACP key auth exposes no account email; the fingerprint lets the
244
+ // operator match WHICH key is connected without revealing it.
245
+ statusLine.title = status?.apiKeyFingerprint
246
+ ? t('凭据指纹 = Gemini API key 的 SHA-256 前 10 位', 'credential fingerprint = first 10 hex of the Gemini API key SHA-256')
247
+ : '';
248
+ const modelEntries = Array.isArray(status?.models) ? status.models : [];
249
+ currentHiddenIds = Array.isArray(status?.hiddenModels) ? status.hiddenModels.filter(id =>
250
+ typeof id === 'string' && modelEntries.some(model => model?.id === id)) : [];
251
+ const hiddenSet = new Set(currentHiddenIds);
252
+ rowButtons = [];
253
+ const busy = busyDepth > 0;
254
+ modelsList.replaceChildren(...modelEntries.map(model => {
255
+ const id = model?.id ?? '';
256
+ const isHidden = hiddenSet.has(id);
257
+ const li = el('li', isHidden ? 'text-muted-foreground/50' : null,
258
+ (typeof model?.name === 'string' && model.name ? model.name + ' · ' : '') + id +
259
+ (isHidden ? t(' 已隐藏', ' hidden') : ''));
260
+ const toggle = isHidden
261
+ ? el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE + ' ml-2 px-2 py-0.5 text-[10px]', t('恢复', 'Restore'))
262
+ : el('button', 'ml-1 inline-flex items-center align-middle rounded p-0.5 text-muted-foreground/60 transition-colors hover:bg-white/10 hover:text-foreground focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-40');
263
+ if (!isHidden) {
264
+ const ns = 'http://www.w3.org/2000/svg';
265
+ const icon = document.createElementNS(ns, 'svg');
266
+ icon.setAttribute('viewBox', '0 0 24 24');
267
+ icon.setAttribute('width', '12');
268
+ icon.setAttribute('height', '12');
269
+ icon.setAttribute('fill', 'none');
270
+ icon.setAttribute('stroke', 'currentColor');
271
+ icon.setAttribute('stroke-width', '2');
272
+ icon.setAttribute('stroke-linecap', 'round');
273
+ icon.setAttribute('aria-hidden', 'true');
274
+ const path = document.createElementNS(ns, 'path');
275
+ path.setAttribute('d', 'M18 6 6 18 M6 6l12 12');
276
+ icon.append(path);
277
+ toggle.append(icon);
278
+ toggle.title = t('隐藏模型 ' + id, 'Hide model ' + id);
279
+ toggle.setAttribute('aria-label', toggle.title);
280
+ }
281
+ toggle.type = 'button';
282
+ toggle.disabled = busy || !call || installingNow;
283
+ toggle.onclick = () => runAction('/models/visibility', isHidden ? { restore: [id] } : { hide: [id] });
284
+ rowButtons.push(toggle);
285
+ li.append(toggle);
286
+ return li;
287
+ }));
288
+ restoreAll.hidden = modelEntries.length === 0 || currentHiddenIds.length === 0;
289
+ restoreAll.disabled = busy || !call || installingNow;
290
+ restoreAll.onclick = () => runAction('/models/visibility', { restore: [...currentHiddenIds] });
291
+ modelsBox.hidden = modelEntries.length === 0;
292
+ // The persisted auth method wins after every status refresh (it is what
293
+ // the last connect call stored), then the account line re-renders.
294
+ if (status?.authMethod === 'oauth-personal' || status?.authMethod === 'gemini-api-key') authMode = status.authMethod;
295
+ accountLine.textContent = status?.accountEmail ? t('账号:', 'Account: ') + status.accountEmail
296
+ : status?.authMethod === 'oauth-personal' ? t('账号邮箱未提供', 'account email not provided') : '';
297
+ renderAuthMode();
298
+ // Prefill only the binary path (an operator setting, not a secret) —
299
+ // the sidecar's configured path, or an agy detected at the official
300
+ // default location; the key input is never populated from stored state.
301
+ const prefill = typeof status?.binary === 'string' ? status.binary
302
+ : typeof status?.detectedBinary === 'string' ? status.detectedBinary : null;
303
+ if (!binaryInput.value && prefill) binaryInput.value = prefill;
304
+ // Re-apply the lock AFTER the row buttons are rebuilt so a running
305
+ // install disables the freshly created visibility toggles too.
306
+ applyDisabled();
307
+ };
308
+
309
+ const refresh = async () => {
310
+ if (target.__agyDisposed) return;
311
+ if (!call) {
312
+ renderStatus(null);
313
+ return;
314
+ }
315
+ try {
316
+ renderStatus(await call('/status', { timeoutMs: 15000 }));
317
+ } catch (error) {
318
+ setMessage(errorText(error));
319
+ }
320
+ };
321
+
322
+ const runAction = async (path, requestBody, onDone) => {
323
+ if (!call || busyDepth > 0) return;
324
+ setMessage('');
325
+ setNotice('');
326
+ setBusy(true);
327
+ try {
328
+ const response = await call(path, {
329
+ method: 'POST',
330
+ body: JSON.stringify(requestBody ?? {}),
331
+ timeoutMs: 30000,
332
+ });
333
+ const doneNotice = onDone?.(response);
334
+ await refresh();
335
+ // Explicit confirmation: these actions are idempotent, so without a
336
+ // success notice a repeated click looks like it did nothing.
337
+ const done = new Date();
338
+ const at = `${String(done.getHours()).padStart(2, '0')}:${String(done.getMinutes()).padStart(2, '0')}:${String(done.getSeconds()).padStart(2, '0')}`;
339
+ setNotice(`${doneNotice ?? t('已完成', 'Done')} · ${at}`);
340
+ } catch (error) {
341
+ setMessage(errorText(error));
342
+ } finally {
343
+ setBusy(false);
344
+ }
345
+ };
346
+
347
+ connect.onclick = () => runAction('/connect', {
348
+ ...(binaryInput.value.trim() ? { binary: binaryInput.value.trim() } : {}),
349
+ authMethod: authMode,
350
+ // The API key only ever travels in gemini-api-key mode; oauth-personal
351
+ // mode never sends credential material.
352
+ ...(authMode === 'gemini-api-key' && keyInput.value ? { apiKey: keyInput.value } : {}),
353
+ }, response => {
354
+ keyInput.value = ''; // never keep the typed key in the DOM
355
+ return t(`已连接(agy ${response?.version ?? ''})`, `Connected (agy ${response?.version ?? ''})`);
356
+ });
357
+ sync.onclick = () => runAction('/models/sync', {}, response =>
358
+ t(`已同步 ${response?.models?.length ?? 0} 个模型`, `Synced ${response?.models?.length ?? 0} models`));
359
+ disconnect.onclick = () => runAction('/disconnect', {}, () => t('已断开', 'Disconnected'));
360
+ install.onclick = () => runAction('/install', {}, () => t('已开始安装 agy', 'agy install started'));
361
+ setBusy(false);
362
+
363
+ const section = el('details', 'max-w-md text-xs text-muted-foreground');
364
+ section.append(el('summary', 'cursor-pointer select-none font-medium', t('配置说明', 'Setup instructions')));
365
+ section.append(el('p', 'mt-2 text-xs text-muted-foreground',
366
+ t('在上方填入 agy 的绝对路径(可选 API key)并按连接,写入 CCR 配置目录的 gemini-agy-acp.json(API key 以 0600 权限保存);断开仅停用,不删除配置。',
367
+ 'Enter the absolute agy path above (optionally an API key) and press Connect. This writes gemini-agy-acp.json in the CCR config directory (the API key is stored with 0600 permissions); Disconnect only disables, it does not delete settings.')));
368
+ section.append(el('p', 'max-w-md text-[11px] text-muted-foreground/60',
369
+ t('Google 账号模式需先在终端运行一次 agy 完成浏览器登录;连接时通过一次真实 ACP 握手验证登录状态,账号邮箱仅在本次握手明确提供时显示。请为主路由配置 enableFallback: false 的隔离实例。',
370
+ 'Google account mode requires running agy once in a terminal to complete the browser sign-in first; Connect verifies the login with one real ACP handshake. The account email is shown only when that handshake explicitly provides it. Run it as a primary route on an isolated instance with enableFallback: false.')));
371
+
372
+ body.append(section);
373
+ layout.append(body);
374
+ card.append(layout);
375
+ target.append(card);
376
+
377
+ await refresh();
378
+ // First view with no agy anywhere: start the official install right away.
379
+ // A previous failure is never retried automatically — the Install button
380
+ // is the explicit retry, so a broken network cannot loop downloads.
381
+ const first = latestStatus;
382
+ if (call && first && !first.binary && !first.detectedBinary && !first.installing && !first.installError) {
383
+ await runAction('/install', {}, () => t('已开始自动安装 agy', 'Automatic agy install started'));
384
+ }
62
385
  },
63
386
  unmount(el) {
64
- this._root?.remove();
65
- this._root = null;
387
+ el.__agyDisposed = true;
388
+ if (el.__agyPollTimer) {
389
+ clearInterval(el.__agyPollTimer);
390
+ el.__agyPollTimer = null;
391
+ }
66
392
  el.replaceChildren();
67
393
  },
68
394
  };