From edb7cd75c96e872ea34c31d9c9f24c9227bad5e2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:12:49 +0000 Subject: [PATCH] upstream agy-cli 0.1.199 (magpie-community/plugins@f115ddb88f88f3beb3ceb8d6709f4e9ef4862a02) --- README.en.md | 106 ++- README.md | 56 +- agy-cli.test.mjs | 1 + cloak.mjs | 35 +- cloak.test.mjs | 64 +- documents.mjs | 6 +- hosted-search.mjs | 1193 +++++++++++++++++++++++++++++++++ index.mjs | 932 +++++++++++++++++++------- model-ids.mjs | 14 +- package.json | 6 +- spilled.mjs | 437 ++++++++++++ test/catalog.mjs | 400 +++++++---- test/conversation-key.mjs | 38 ++ test/hosted-search.mjs | 1325 +++++++++++++++++++++++++++++++++++++ test/image-bytes.mjs | 84 +++ test/media-input.mjs | 53 +- test/repeat-batch.mjs | 36 +- test/same-opening.mjs | 33 + test/smoke.mjs | 27 +- test/spilled-output.mjs | 161 ++++- test/steer-in-session.mjs | 174 +++-- test/testkit.mjs | 17 +- test/usage.mjs | 175 ++++- usage.mjs | 147 +++- 24 files changed, 4997 insertions(+), 523 deletions(-) create mode 100644 hosted-search.mjs create mode 100644 spilled.mjs create mode 100644 test/hosted-search.mjs diff --git a/README.en.md b/README.en.md index 0a741a6..bb52641 100644 --- a/README.en.md +++ b/README.en.md @@ -17,9 +17,18 @@ response. - The work is done by the real agy CLI over the ACP channel it ships with. The ACP handshake's `clientInfo` is the plugin's own package name and version - (`opencode-agy-cli-auth`), not Zed or any other editor. The plugin calls - none of Google's endpoints itself: the quota too is read through agy alone + (`opencode-agy-cli-auth`), not Zed or any other editor. Model requests all + go through `agy acp`, and the quota too is read through agy alone (`agy -p /usage`, see "Usage quota"), never with agy's stored token. + The plugin sends Google one request of its own with the account: when a + sign-in finishes (Sign in, Add another Google account, an import) and + agy's stored sign-in doesn't name its email (no `id_token_email`), it asks + `https://www.googleapis.com/oauth2/v2/userinfo` once with the access token + agy stored, and reads only the account's email from it, to name the + account in Magpie. That is at most once per sign-in; the answer isn't + cached, and an expired token isn't renewed for it. A sign-in that names + its email sends nothing. Downloading and update checks of the plugin's own + copy of agy (see "Requirements") carry no account. - Tools that belong to the client, such as file reads, writes and shell commands, are exposed to the model over MCP. The client runs them and the results flow back into the same agy conversation, so the model sees ordinary native tool @@ -93,12 +102,14 @@ MCP server. The control port listens on loopback only, with a token per process. - **The models agy offers**: the list follows the model option agy advertises in the ACP session. A model `agy models` lists but the session does not offer this client (agy may keep Claude and GPT-OSS for clients it recognises) is - left out. To list models, the plugin opens one session with `agy acp` (no - prompt is sent) and reads what it offers; until it has, only Gemini is listed. - The last list agy gave and offered is kept in `models.json` beside the session - state file, so after a restart that list is served while agy is asked again: - both what it lists and what a session offers, and again whenever the list - changes (another account or plan). + left out. An idle account sends Google nothing of its own: `agy models` runs + at sign-in, when you refresh the model list, or when there is no list yet. + What agy offers comes from each request's own session; apart from that, + `agy acp` is asked once (a session, no prompt) at sign-in and on a refresh, + run as a request runs it (telemetry off, no default customizations). Until + agy has said, only Gemini is listed. What agy listed and offered, and the + account's tier, are kept in `models.json` beside the session state file and + served as they are after a restart, without asking agy again. Models and thinking levels can be switched mid-conversation without losing history. `agy models` runs with `--settings '{"modelProvider":""}'`, so a @@ -119,6 +130,10 @@ MCP server. The control port listens on loopback only, with a token per process. otherwise. A video or audio URL, or one sent to a model other than Gemini, gets HTTP 400. `count_tokens` counts a video or audio clip as one image, so a long clip is undercounted. +- **PDF input** (Gemini models, since 0.1.189): a PDF attached to the message + (base64) is written to `attachments/.pdf` as a video is, and agy's + own file reader hands it to Gemini. Sent to a model other than Gemini, it + gets HTTP 400. - **Tool calls**: parallel and consecutive calls both work. A tool that runs past 150 seconds first gets a "still running" placeholder; once the real result arrives, the same turn continues, and the client executes each call exactly once. @@ -145,6 +160,40 @@ MCP server. The control port listens on loopback only, with a token per process. (SillyTavern presets, "continue"/"impersonate", bot frameworks) are served instead of rejected; the session ledger stays aligned across turns. See "Assistant prefill" below. +- **Batched web search (opt-in, off by default)**: by default Magpie + handles client `web_search` / `web_fetch` tools one by one. To let the model + submit batched Anthropic hosted `web_search` and `web_fetch` calls inside the + live `agy` session (up to 10 search queries or 3 URL fetches per call, running + at most 2 MCP calls at a time without dropping the live session), enable + **"Batched web search"** under **Providers › Antigravity (local agy CLI)**, run + `magpie plugin options agy-cli '{"hosted_search":true}'`, or set + `AGY_BRIDGE_HOSTED_SEARCH=1`. Restart Magpie after changing the switch. It + calls Magpie's local loopback `/mcp/magpie/web-search` endpoint (reusing + configured search providers, keys, and proxies; loopback calls need and send + no gateway key and never read `caller-keys.json`, while non-loopback URLs + require setting `AGY_BRIDGE_SEARCH_URL` explicitly and only send an explicit + `AGY_BRIDGE_SEARCH_KEY`), defaults to 20 searches per turn when `max_uses` is + omitted (`AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES` can lower that cap within 1–20, + never past 20), rejects keyword-less `site:`-only queries before spending + quota, and never bills failed searches in `usage.server_tool_use`. `web_fetch` + defaults to 20,000 characters (up to 100,000 per call, split across batched + URLs) when the client provides a + file-reading or shell tool (such as Claude Code, Codex, or OpenCode), or fits + within 7,500 UTF-8 bytes with exact code-point `offset`s for inline-only + clients (staying below `agy`'s ~10 KiB single-tool-output spill cliff), + supporting per-URL continuation via single-URL `url` + `offset` or + `requests: [{ url, offset, max_chars }]`. + Notes: `allowed_domains` and `blocked_domains` check initial URLs only (not + redirect targets), and `web_fetch` accepts any public URL the model writes + (Magpie's fetcher blocks private and loopback addresses); do not manually + select `agy-cli/` as Magpie's model searcher while this switch is on, + and note that with **"Antigravity (agy)"** (`agy-cli:agy`) as Magpie's search + source every query opens a separate `agy` session on the signed-in Google + account (so avoid pairing that search source with this switch). Known limitation (verified on `magpie v0.1.5384`): + while enabled, Anthropic non-streaming `/v1/messages` and OpenAI + `/v1/responses` (streaming and non-streaming) execute searches and answer from + them, while omitting search result blocks (`server_tool_use` / + `web_search_call`) and `server_tool_use` usage counts from the response. - **Web search**: the plugin gives Magpie's web search `agy-cli:agy` (`magpie search add agy-cli`), through agy's own `search_web`. It opens a default-agent session whose workspace hook allows only `search_web`, asks @@ -239,7 +288,8 @@ After installing, sign in from Magpie; no terminal needed. minutes. Google credentials stay with agy (in the system keyring); the plugin never stores them, and counts the sign-in as done only once `agy models` lists the account's models. Magpie names the account by the - Google email agy stored (the one thing read from the keyring for it). + Google email agy stored (read from the keyring; when the sign-in doesn't + name it, Google is asked once with agy's stored token, see "What it is"). To add another Google account, click agy-cli's Add another account (or Sign in) and pick "Add another Google account". The new account gets an agy home of its own (under `~/.local/state/magpie-agy-bridge/accounts/`), @@ -324,9 +374,13 @@ read asks Google about twelve times, one after another, which usually takes 5–10 seconds and longer on a first start, on Windows, for a newly added account or behind a slow network or proxy, so the plugin gives it 45 seconds. Magpie waits 20 seconds for a read: past that the account says agy is still reading -its quota, agy reads on, and the next refresh shows what it read without -running agy again. A read that doesn't finish in 45 seconds says so, names a -slow network or proxy as the usual cause, and is tried again a minute later. +its quota, agy reads on, and the next refresh shows what it read: within +three minutes without running agy again; later, agy reads again and what it +read before answers if agy is slow again. What it read is kept until a +refresh takes it, a window in it resets or five hours pass, the account +signs out or changes, or a read after it fails. A read that doesn't finish +in 45 seconds says so, names a slow network or proxy as the usual cause, and +is tried again a minute later. When agy refuses `/usage` for the account's region ("not currently available in your location"), the plugin asks agy acp which tier it serves the account on. Google can name a tier the account can't have (the free one, in a region @@ -359,8 +413,9 @@ only `config/config.json` differs, without `gateway` and `models`. Your While agy's access token has ended or ends within two minutes (with a refresh token to renew it), agy isn't run for usage: a renewal that fails there can open a Google sign-in in the browser (#1234). The account says agy's sign-in is -due to be renewed; agy renews it on the account's next chat and the quota is -read after that. Until then the last quota read stays shown. +due to be renewed; agy renews it on the account's next chat, and a refresh +after that chat reads the quota (nothing reads it by itself). Until then the +last quota read stays shown. A signed-out agy opens Google's sign-in page in the browser when it runs, so before running agy for usage or the model list, the plugin looks at agy's stored @@ -419,6 +474,13 @@ The plugin gets these from magpie's own process, so set them before magpie start | `AGY_CLI_DISABLE_AUTO_UPDATE` | `true` for the plugin's agy processes | agy's own variable. When you set it, agy gets your value; see "Requirements" | | `AGY_BRIDGE_PREFILL` | on | Set to `0` to restore the stock 400 reject for assistant prefill tails; see "Assistant prefill" | | `AGY_BRIDGE_PREFILL_CARRIER_NOTE` | English system note | The note line rendered before a prefill fragment (sent to the model) | +| `AGY_BRIDGE_HOSTED_SEARCH` | off (follows UI switch) | Override the "Batched web search" switch: `1` forces on, `0` forces off | +| `AGY_BRIDGE_SEARCH_URL` | auto-discovered local loopback Magpie | Explicit URL for Magpie's `/mcp/magpie/web-search` endpoint (only way to target a non-loopback host) | +| `AGY_BRIDGE_SEARCH_KEY` | unset | Explicit Bearer key sent only when `AGY_BRIDGE_SEARCH_URL` targets a non-loopback host (loopback calls send no key; `caller-keys.json` is never read) | +| `AGY_BRIDGE_MAGPIE_CONFIG_DIR` | auto-discovered Magpie config dir | Explicit Magpie config directory containing `gateway.json` / `settings.json` | +| `AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES` | 20 | Default per-turn cap for in-bridge hosted search/fetch when the client omits `max_uses` (1–20; can lower the cap, never raise past 20; client `max_uses` wins) | +| `AGY_BRIDGE_FETCH_MAX_CHARS` / `AGY_BRIDGE_SEARCH_MCP_MAX_CHARS` | 20000 (7500-byte fit for inline-only clients) / 7500 | Default character budget per `web_fetch` call (20000 split across URLs when the client provides a file-reading tool, or fitted within 7500 UTF-8 bytes with exact code-point `offset`s for inline-only clients) / UTF-8 byte cap per inline MCP reply returned to agy | +| `AGY_BRIDGE_SEARCH_TIMEOUT_MS` / `AGY_BRIDGE_FETCH_TIMEOUT_MS` | 30000 / 30000 | Per-call timeout in ms for hosted `web_search` / `web_fetch` | ## Minimal agent (`AGY_BRIDGE_MINIMAL_AGENT=1`, no longer has an effect) @@ -479,6 +541,12 @@ implicit DOM, route, or screenshot context." in its Web GUI paragraph (#1105) get the 429 as written too, so they go as "You're …" and "The browser gives …". +WorkBuddy's first line, "This conversation is powered by " (#1871), +gets the 429 whichever model it names, in the system prompt and in a +user's turn alike. The whole line, model and any label after it, goes as +"This conversation is powered by an AI model.", in the system prompt, a +user's turn and a tool result. + agy reads a command name anywhere in a prompt as the user running that command: `/learn` (or `/plan`, `/goal`, …, or a skill of the session's) between spaces, or at the start or end, gets the command's whole text added @@ -512,11 +580,11 @@ without it. Paths, URLs, `/learn.`, `/Learn`, `` `/learn` `` and - **Image requests return HTTP 400**: the running agy does not advertise image support (1.5.0 or later is needed). Only inline base64 is accepted; image URLs are rejected. -- **Documents**: agy reads text and images only. A text document (plain text, - base64 text/JSON/XML) goes as its text, and a URL document goes as its URL, - for the model to fetch with a tool. A PDF read by a tool reaches the model as - a note to extract its text another way; a PDF attached to the message itself - gets HTTP 400 saying so. Paste its text or attach its pages as images instead. +- **Documents**: a text document (plain text, base64 text/JSON/XML) goes as + its text, and a URL document goes as its URL, for the model to fetch with a + tool. A PDF attached to the message: see PDF input above. A PDF read by a + tool reaches the model as a note to extract its text another way; another + binary file attached to the message gets HTTP 400 saying so. - **A reply contains "Agent execution terminated due to error."**: that is agy's in-band error marker. The plugin reads the real cause from agy's log and ends the turn with an error instead of passing the marker through as text. agy diff --git a/README.md b/README.md index f1bc6c6..d0905f5 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,13 @@ OpenCode、Claude Code 等客户端经由 Magpie 调用 agy 向本插件开放 流式响应。 - 底层是真正的 agy CLI,走它自带的 ACP 通道。ACP 握手里的 `clientInfo` 是本插件自己的 - 包名和版本(`opencode-agy-cli-auth`),不冒充 Zed 或其它编辑器。插件自己不请求 Google 的接口: + 包名和版本(`opencode-agy-cli-auth`),不冒充 Zed 或其它编辑器。模型请求全部经由 `agy acp`; 额度也只经 agy 自己读(`agy -p /usage`,见「额度」),不拿 agy 存的登录令牌去直接查。 + 插件自己带着账号向 Google 发的请求只有一个:登录完成时(Sign in、添加另一个 Google 账号、 + 导入账号),如果 agy 存的登录里没写是哪个邮箱(没有 `id_token_email`),插件用 agy 存的 + access token 请求一次 `https://www.googleapis.com/oauth2/v2/userinfo`,只读取账号的邮箱, + 用来在 Magpie 里给账号命名。每次登录最多一次,结果不缓存,令牌过期也不为它续期;登录里 + 写了邮箱时不发。插件自己装的那份 agy 的下载和更新检查(见「环境要求」)不带账号。 - 客户端自己的工具(读写文件、执行命令等)通过 MCP 暴露给模型。工具由客户端执行,结果 回传到同一轮 agy 对话里,模型看到的是原生工具调用。 - 账号风险不由插件决定。Google 的使用政策变化时,插件无法替你保证账号不受限制。 @@ -60,9 +65,11 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy - **agy 开放的模型**:模型列表以 ACP 会话里 agy 给出的模型选项为准。`agy models` 列出的 模型如果没有在会话里向本客户端开放(agy 可能只向它认可的客户端开放 Claude、GPT-OSS), - 就不会出现在列表里。列模型时插件会先用 `agy acp` 开一个会话(不发 prompt)问 agy 开放了哪些, - 问到之前只列 Gemini。上次 agy 列出并开放的模型存在会话状态文件旁边的 `models.json`, - 重启后先列它,同时再问一次 agy:列出的和会话开放的都再问,列表变了(换了账号或套餐)也再问。模型和思考等级可以在会话中切换, + 就不会出现在列表里。空闲的账号不会自己向 Google 发任何请求:`agy models` 只在登录、 + 你刷新模型列表、或还没有列表时运行;agy 开放了哪些模型来自每个请求自己的会话,另外只在 + 登录和刷新时用 `agy acp` 开一个会话(不发 prompt)问一次,参数和请求的一样(关遥测、 + 不载默认定制)。还不知道开放了哪些时只列 Gemini。agy 列出并开放的模型和账号档位存在会话 + 状态文件旁边的 `models.json`,重启后照旧用,不再问 agy。模型和思考等级可以在会话中切换, 历史保留。`agy models` 带 `--settings '{"modelProvider":""}'` 运行,所以 settings.json 里的 `"modelProvider": "gemini"`(AI Studio 密钥)不影响这里的列表, 列出的是 Google 账号的模型;AI Studio 密钥请在 Magpie 的 Providers 页加成 Google Gemini。 @@ -75,6 +82,9 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy 读取,Gemini 由此拿到画面和声音。只有带着视频或音频的对话才有 `view_file`,其余时候 agy 的工具都关着。视频或音频给的是 URL,或发给 Gemini 以外的模型时,返回 HTTP 400。 `count_tokens` 把一段视频或音频按一张图片计数,长片段会少算。 +- **PDF 输入**(Gemini 型号,0.1.189 起):直接附在消息里的 PDF(base64)和视频一样写到 + `attachments/.pdf`,由 agy 自己的文件读取工具交给 Gemini。发给 Gemini 以外的模型 + 时返回 HTTP 400。 - **工具调用**:支持并行和连续调用。运行超过 150 秒的工具会先收到 "still running" 的 占位响应,真正的结果送达后继续同一轮对话,每个调用只在客户端执行一次。 - **会话续接**:每轮结束后记录会话,工具循环进行中的每一步也记录。重启 Magpie 或插件后, @@ -87,6 +97,18 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy 也允许 agy 的 `read_file` 或 `view_file`。桥接仍检查权限。客户端工具在客户端自己的权限下运行。 - **助手预填**:以 assistant 结尾的预填请求(SillyTavern 预设、继续写、bot 框架)不再 400 拒绝:预填留在本轮并渲染为续写载体,会话跨轮保持对齐,见下文「助手预填」。 +- **批量联网搜索(可选,默认关闭)**:默认仍由 Magpie 自身逐条处理客户端的 `web_search` / `web_fetch`; + 如需在同一次活跃 `agy` 会话内批量执行联网搜索与网页读取(单次调用最多提交 10 条搜索或 3 个 URL,后台每次最多同时执行 2 个,不触发会话重开), + 可在 Magpie 的 **Providers › Antigravity (local agy CLI)** 开关里开启 **「批量联网搜索」**,或运行 + `magpie plugin options agy-cli '{"hosted_search":true}'`(也可用 `AGY_BRIDGE_HOSTED_SEARCH=1` 覆盖)。 + 修改后重启 Magpie 生效。该模式复用 Magpie 本机回环地址 `/mcp/magpie/web-search`(沿用已配置的 Tavily 等搜索源、密钥轮换与代理; + 本机回环调用无需也不发送网关密钥,不会读取 `caller-keys.json`;只有显式设置 `AGY_BRIDGE_SEARCH_URL` 指向非本机地址时,才允许非回环地址并附带显式配置的 `AGY_BRIDGE_SEARCH_KEY`), + 默认单轮上限 20 次搜索(尊重客户端 `max_uses`,`AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES` 仅允许在 1–20 内调低)、扣减额度前拦截无关键词的纯 `site:` 查询、失败请求不计入 + `usage.server_tool_use`。`web_fetch` 在客户端提供读文件或命令行读取工具(如 Claude Code、Codex、OpenCode)时默认预算 20,000 字符(单次调用最高共 100,000 字符,多 URL 平分), + 纯内联客户端则控制在 7,500 UTF-8 字节内以避开 `agy` 约 10 KiB 的单条工具输出落盘截断,支持单 URL `offset` 或 `requests: [{ url, offset, max_chars }]` 按 URL 独立续读。 + 注意:`allowed_domains` / `blocked_domains` 仅检查初始请求 URL(不检查跳转后的目标地址),`web_fetch` 可抓取模型写出的任意公网 URL(Magpie 抓取器会拦截私网与回环地址); + 开启本开关时请勿在 Magpie 设置中手动将 `agy-cli/<模型>` 选为模型搜索器;另外若将 Magpie 搜索源设为「Antigravity (agy)」(`agy-cli:agy`),每条查询都会在当前登录的 Google 账号上单独开启一个 `agy` 会话,不建议与本开关搭配使用。 + 已知限制(实测于 `magpie v0.1.5384`):开启时 Anthropic 非流式 `/v1/messages` 与 OpenAI `/v1/responses`(流式及非流式)均会正常执行搜索并据此作答,但响应中会省略搜索结果块(`server_tool_use` / `web_search_call`)和 `usage.server_tool_use` 计数。 - **网页搜索**:给 Magpie 的网页搜索提供 `agy-cli:agy`(`magpie search add agy-cli`), 用的是 agy 自己的 `search_web`。插件开一个默认 Agent 会话,工作区钩子只允许调用 `search_web`,从 agy 保存的搜索步骤里读出摘要和来源,然后取消这一轮,模型不写回答。搜索由 agy 在 @@ -150,7 +172,8 @@ magpie plugin add @magpie-community/opencode-agy-cli-auth 登录后把页面显示的授权码(或整个页面地址)粘贴回 Magpie。Magpie 在服务器或 Docker 里也一样。登录的有效期是 15 分钟。Google 凭据始终由 agy 自己保管(系统钥匙串), 插件不保存;agy 列出账号的模型(`agy models`)后才算登录成功。账号在 Magpie 里以 agy - 存的 Google 邮箱命名(只从钥匙串里读这一项)。 + 存的 Google 邮箱命名(从钥匙串里读这一项;登录里没写邮箱时,用 agy 存的令牌问一次 Google, + 见「这是什么」)。 要再加一个 Google 账号,点 agy-cli 的 Add another account(或 Sign in),选「添加另一个 Google 账号」。新账号有自己的 agy 主目录(`~/.local/state/magpie-agy-bridge/accounts/` 下),它的登录保存在那个目录里的文件中,不动系统钥匙串里原来那个账号。每个账号单独一行, @@ -211,7 +234,9 @@ magpie quota refresh agy-cli --json agy 存的登录令牌去直接请求 Google 的额度接口,也不替 agy 续期令牌(Google 已经提醒过,第三方工具 这样直接读可能让账号被标记)。agy 自己读一次要向 Google 依次请求十来次,通常 5–10 秒, 冷启动、Windows、新加的账号或网络/代理慢时更久,所以插件给它 45 秒。Magpie 一次只等 20 秒: -超过时账号显示「agy 还在读这个账号的额度」,agy 接着读完,下次刷新直接显示结果,不再运行一次 agy。 +超过时账号显示「agy 还在读这个账号的额度」,agy 接着读完,下次刷新显示结果:三分钟内直接显示,不再运行一次 agy; +更晚时 agy 再读一次,若又慢,先显示上次读到的结果。读到的结果一直留到下次刷新取走,额度窗口重置、 +超过五小时、账号登出或切换、或之后一次读取失败时作废。 45 秒内仍没读完时,账号说明 agy 自己的读取没在 45 秒内完成、通常是网络或代理慢,一分钟后再试。 agy 因地区拒绝 `/usage`("not currently available in your location")时,插件先问 agy acp 这个账号在哪个档位上服务。Google 可能在账号实际用的付费档位旁边,再列一个它用不了的档位(未开放地区的 @@ -233,7 +258,7 @@ Antigravity 应用的网关打开时(`~/.gemini/config/config.json` 里 `gatew agy 的访问令牌已到期或两分钟内到期(有刷新令牌)时,插件不为额度运行 agy:agy 续期失败时 可能在浏览器里打开 Google 登录页(#1234)。账号显示「agy 的登录待续期」,agy 在这个账号下次对话时 -自己续期,之后再读额度;在此之前显示上次读到的额度。 +自己续期,那次对话之后再刷新一次即可读到额度(不会自动读);在此之前显示上次读到的额度。 未登录的 agy 一运行就会在浏览器里打开 Google 登录页,所以插件在为额度或模型列表运行 agy 之前, 先看系统钥匙串(macOS)或凭据管理器(Windows)里 agy 存的登录,只读有没有、何时到期。没有登录、 @@ -286,6 +311,13 @@ macOS 上,以 LaunchDaemon 方式运行的 Magpie 不在你的登录会话里 | `AGY_CLI_DISABLE_AUTO_UPDATE` | 插件启动的 agy 设为 `true` | agy 自己的变量。你设置了就原样传给 agy,见「环境要求」 | | `AGY_BRIDGE_PREFILL` | 开启 | 设为 `0` 恢复对 assistant 预填尾巴的原生 400 拒绝,见「助手预填」 | | `AGY_BRIDGE_PREFILL_CARRIER_NOTE` | 英文系统提示行 | 预填片段渲染时的提示行文本(发给模型) | +| `AGY_BRIDGE_HOSTED_SEARCH` | 关闭(跟随 UI 开关) | 覆盖「批量联网搜索」开关:`1` 强制开启、`0` 强制关闭 | +| `AGY_BRIDGE_SEARCH_URL` | 自动发现本机回环 Magpie | 显式指定 Magpie 的 `/mcp/magpie/web-search` 地址(唯一允许非本机地址的方式) | +| `AGY_BRIDGE_SEARCH_KEY` | 未设置 | 显式设置非本机 `AGY_BRIDGE_SEARCH_URL` 时附带的 Bearer 密钥(本机回环调用不发送密钥,也不读取 `caller-keys.json`) | +| `AGY_BRIDGE_MAGPIE_CONFIG_DIR` | 自动查找 Magpie 配置目录 | 显式指定包含 `gateway.json` / `settings.json` 的 Magpie 配置目录 | +| `AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES` | 20 | 客户端未传 `max_uses` 时,单轮桥接内托管搜索/抓取的默认上限(仅允许在 1–20 内调低,不可超过 20;客户端 `max_uses` 优先) | +| `AGY_BRIDGE_FETCH_MAX_CHARS` / `AGY_BRIDGE_SEARCH_MCP_MAX_CHARS` | 20000(纯内联客户端按 7500 字节自适应) / 7500 | 单次 `web_fetch` 的默认字符预算(有读文件工具的客户端默认 20000、多 URL 平分;纯内联客户端控制在 7500 UTF-8 字节内并按码点精确计算续读 `offset`)/ 纯内联场景返回给 agy 的单条输出字节上限 | +| `AGY_BRIDGE_SEARCH_TIMEOUT_MS` / `AGY_BRIDGE_FETCH_TIMEOUT_MS` | 30000 / 30000 | 单次托管搜索 / 抓取请求的超时时间(毫秒) | ## 精简 agent(`AGY_BRIDGE_MINIMAL_AGENT=1`,已不起作用) @@ -320,6 +352,10 @@ DeepSeek Harness 的第一句 "You are an AI agent powered by DeepSeek Harness." "The browser provides no implicit DOM, route, or screenshot context."(#1105)原样发出也会被回 429, 分别改成 "You're …" 和 "The browser gives …" 再发。 +WorkBuddy 的第一行 "This conversation is powered by <模型>"(#1871)不论写的是哪个模型,在系统提示词 +和用户轮次里都会被回 429。插件把整行(模型名和后面的标注)换成 "This conversation is powered by an AI +model." 再发,系统提示词、用户轮次和工具结果里都一样。 + agy 会把提示词里任何位置的命令名当成用户在运行这个命令:前后是空白(或在开头、结尾)的 `/learn` (或 `/plan`、`/goal` 等,以及会话自己的技能)会让 agy 把这个命令的整段说明加进本轮。系统提示词或技能 列表里提到命令名,比如 Cindy 的 "invokes /learn or /skill:learn in Pi",曾让每一轮都启动 agy 的 @@ -343,9 +379,9 @@ URL、`/learn.`、`/Learn`、`` `/learn` `` 和 `/skill:learn` 在 agy 看来不 把 agy 升级到 1.5.19 或更新版本。 - **图片请求返回 HTTP 400**:当前 agy 没有声明图片能力。另外只接受 内联 base64,URL 图片会被拒绝。 -- **文档**:agy 只读文字和图片。文本文档(纯文本,或 base64 的文本/JSON/XML)按文字发过去; - URL 文档发的是网址,由模型用工具去取。工具读到的 PDF 会变成一条说明,提示模型换个方式 - 提取文字;直接附在消息里的 PDF 返回 HTTP 400 并说明原因,请改为粘贴文字或把页面作为图片附上。 +- **文档**:文本文档(纯文本,或 base64 的文本/JSON/XML)按文字发过去;URL 文档发的是网址, + 由模型用工具去取。直接附在消息里的 PDF 见上面的“PDF 输入”。工具读到的 PDF 会变成一条说明, + 提示模型换个方式提取文字;其他二进制文件返回 HTTP 400 并说明原因。 - **回复里出现 "Agent execution terminated due to error."**:这是 agy 的错误标记。插件会 从 agy 的日志中取出真实原因,并以错误结束本轮,不会当作正常回复输出。agy 1.5.8 的 "There was a network issue connecting to the server" 和 "Your AI credits balance is diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index 0e73f00..e150b25 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -47,6 +47,7 @@ for (const [name, mocks] of [ ["masking-drift.mjs", false], ["spilled-output.mjs", false], ["web-search.mjs", false], + ["hosted-search.mjs", false], ["tool-result-prefill.mjs", false], ["tool-step-retry.mjs", false], ["image-bytes.mjs", false], diff --git a/cloak.mjs b/cloak.mjs index c0c5098..35fa6be 100644 --- a/cloak.mjs +++ b/cloak.mjs @@ -47,6 +47,15 @@ // within the Claude Agent SDK" its SDK's), is turned away too (#1151, // KevinXC5, 3 of 3 through agy on gemini-4-hydrogen with Claude Code // 2.1.325); "You're …" and "This agent is …" each went through 3 of 3. +// Since 12-02 so is WorkBuddy's first line, "This conversation is powered +// by {{ modelName }}" (its templates/workbuddy-*-prompt.tpl, 5.5.6), with +// whatever model the user picked in it (#1871, djj532, on a real account +// through agy on gemini-4-carbon with "gemini-4-carbon-high", streamed or +// not; the line in the first user turn, where agy-cli puts the system +// prompt by default). "This conversation is powered by an AI model." and +// the prompt without the line each went through. The model's name is the +// rest of the line, a WorkBuddy label after it included ("GLM-5.3 · +// AutoClaw 国内 (Zhipu)", #466), so the line is matched to its end. // Codex's prompt for GPT-6 ("You are Codex, an agent based on GPT-6."), // the rest of Claude Code's, Gemini CLI's, Qwen Code's, Cline's, Kilo's, goose's, Amp's, // Droid's, Kimi CLI's, Aider's and Cursor's went through as written. @@ -64,6 +73,7 @@ export const TURNED_AWAY = [ "you are an ai agent powered by deepseek harness", "you are claude code, anthropic's official cli for claude", "the browser provides no implicit dom, route, or screenshot context.", + "this conversation is powered by", ] // INVISIBLE are the characters Google's check reads past: since 11-14 a @@ -85,11 +95,17 @@ const escape = (c) => c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") // "RFC 2119" as it did on one line, while a missing period, a space dropped // after a comma or the words in another order went through (a real // account, 11-14). Claude Code's billing line is matched to its end, since -// it goes whole. +// it goes whole, and so is WorkBuddy's, whose end is the model's name: up +// to the line's end, a quote or a backslash (a prompt quoted as JSON in a +// tool result), or a period that ends a sentence. Its rewording, "… an AI +// model.", is not matched again. +const TAIL = { + "x-anthropic-billing-header:": "[^\\n]*\\n?", + "this conversation is powered by": `${INVISIBLE}*[^\\S\\n\\r]+${INVISIBLE}*(?!an ai model\\.)[^\\s"\\\\][^\\n\\r"\\\\]*?(?:\\.(?=\\s|$)|(?=[\\n\\r"\\\\]|$))`, +} const lineRe = (line) => { const words = line.split(" ").map((w) => [...w].map(escape).join(`${INVISIBLE}*`)) - const tail = line === "x-anthropic-billing-header:" ? "[^\\n]*\\n?" : "" - return new RegExp(words.join(`${INVISIBLE}*\\s+${INVISIBLE}*`) + tail, "gi") + return new RegExp(words.join(`${INVISIBLE}*\\s+${INVISIBLE}*`) + (TAIL[line] ?? ""), "gi") } const TURNED_AWAY_RE = TURNED_AWAY.map(lineRe) const has = (s, re) => { @@ -125,6 +141,9 @@ export function turnsAway(system) { // for "provides" (3 of 3 alone and in its paragraph on 11-17, #1105). // - omp's RFC 2119 line goes as "key words", the RFC's own term (10 of 10 // on 11-14, eric_li8983 on X). +// - WorkBuddy's first line goes as "This conversation is powered by an AI +// model.", the rewording #1871 saw answered, for whichever model it +// names: nothing else on the line, or after it, changes. const youre = (line) => line.replace(/^(you)\s+are/i, "$1're") const SAID_AS = { "x-anthropic-billing-header:": () => "", @@ -140,6 +159,7 @@ const SAID_AS = { "you are an ai agent powered by deepseek harness": youre, "you are claude code, anthropic's official cli for claude": youre, "the browser provides no implicit dom, route, or screenshot context.": (line) => line.replace(/provides/i, "gives"), + "this conversation is powered by": (line) => line.replace(/^(this\s+conversation\s+is\s+powered\s+by)[^\S\n\r]+[\s\S]*$/i, "$1 an AI model."), } // USER_TURNED_AWAY are the lines Antigravity also turns away in a user's @@ -151,7 +171,10 @@ const SAID_AS = { // (packages/antigravity's USER_TURNED_AWAY). Everything agy-cli hands agy as // a prompt goes to Antigravity in a user's turn, the history it replays and // the tool results it renders included, so cloakUser runs over all of it. -export const USER_TURNED_AWAY = TURNED_AWAY.filter((l) => l.startsWith("you are codex, ")) +// WorkBuddy's first line was turned away in a user's turn (#1871: the +// system prompt goes in the first one by default), so it is reworded there +// too, a WorkBuddy prompt quoted in a tool result included. +export const USER_TURNED_AWAY = TURNED_AWAY.filter((l) => l.startsWith("you are codex, ") || l === "this conversation is powered by") // cloak rewords the lines of only, or of TURNED_AWAY when only is left out export function cloak(system, only) { @@ -313,6 +336,9 @@ const DSH_HINT = const RFC_HINT = "Antigravity answers this 429 to the line \"RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.\" that starts oh-my-pi (omp)'s system prompt, and to any prompt that has it, whatever quota is left, so it is not a quota and waiting won't help; magpie sends that line as \"RFC 2119 key words: …\", which goes through, so this one came from a copy of it that was worded another way" +const WORKBUDDY_HINT = + "Antigravity answers this 429 to WorkBuddy's first line (\"This conversation is powered by \") whatever quota is left, so it is not a quota and waiting won't help; magpie sends that line as \"This conversation is powered by an AI model.\", which goes through, so use another provider for these chats, or put one after Antigravity in a routing group" + export function hint(system) { system = String(system ?? "") if (said(system, "rfc 2119 keywords: must, required, should, recommended, may, optional.")) return RFC_HINT @@ -322,5 +348,6 @@ export function hint(system) { if (said(system, "you are opencode")) return OPENCODE_HINT if (said(system, "a coding assistant running inside pi")) return PI_HINT if (said(system, "you are an ai agent powered by deepseek harness") || said(system, "the browser provides no implicit dom, route, or screenshot context.")) return DSH_HINT + if (said(system, "this conversation is powered by")) return WORKBUDDY_HINT return HINT } diff --git a/cloak.test.mjs b/cloak.test.mjs index b0a4e38..1d16500 100644 --- a/cloak.test.mjs +++ b/cloak.test.mjs @@ -32,6 +32,8 @@ const samples = [ "Codex's GPT-6 prompt goes as written: You are Codex, an agent based on GPT-6.", "You're Hermes Agent, an intelligent AI assistant created by Nous Research.", "Nothing to see here; Claude Agent SDK alone is fine.", + "This conversation is powered by gemini-4-carbon-high\n\nYour main goal is to follow the USER's instructions at each message, denoted by the tag.", + "This conversation is powered by an AI model.", "", ] @@ -62,12 +64,72 @@ test("a turned-away line wrapped or widened by white space is reworded too", () }) test("a turned-away line broken up by invisible characters is reworded too", () => { - for (const line of [...TURNED_AWAY, ...samples.filter((s) => turnsAway(s)).map((s) => s.replace(/[A-Za-z0-9]{3,}/g, (w) => w[0] + ZW + w[1] + ZW + w.slice(2)))]) { + // WorkBuddy's line is turned away with a model after it, not bare + for (const line of [...TURNED_AWAY.map((l) => l === "this conversation is powered by" ? `${l} gemini-4-carbon-high` : l), ...samples.filter((s) => turnsAway(s)).map((s) => s.replace(/[A-Za-z0-9]{3,}/g, (w) => w[0] + ZW + w[1] + ZW + w.slice(2)))]) { expect(turnsAway(line)).toBe(true) expect(turnsAway(cloak(line))).toBe(false) } }) +// plugins#1871 (djj532): WorkBuddy's prompt opens with "This conversation +// is powered by " (templates/workbuddy-prompt.tpl, WorkBuddy 5.5.6), +// and Antigravity answers a bare 429 to any prompt holding it. With "an AI +// model." in place of the model, or with the line gone, it answered 200. +const WB_REST = "Your main goal is to follow the USER's instructions at each message, denoted by the tag." +const AI_MODEL = "This conversation is powered by an AI model." + +test("WorkBuddy's first line goes as \"This conversation is powered by an AI model.\", whatever the model (#1871)", () => { + expect(turnsAway("This conversation is powered by gemini-4-carbon-high")).toBe(true) + expect(cloak("This conversation is powered by gemini-4-carbon-high")).toBe(AI_MODEL) + for (const model of [ + "gemini-4-carbon-high", + "claude-sonnet-4-6", + "gemini-3.8-flash-high.", + "Auto", + "GLM-5.3 · AutoClaw 国内 (Zhipu)", + ]) { + const sys = `This conversation is powered by ${model}\n\n${WB_REST}` + expect(turnsAway(sys)).toBe(true) + expect(cloak(sys)).toBe(`${AI_MODEL}\n\n${WB_REST}`) + expect(outgoing(sys)).toBe(`${AI_MODEL}\n\n${WB_REST}`) + expect(turnsAway(cloak(sys))).toBe(false) + } + expect(cloak("This conversation is powered by Gemini 3.8 Flash (High). You are good.")).toBe(`${AI_MODEL} You are good.`) + expect(cloak("Rules:\r\nthis Conversation\nis powered by\tgemini-4-carbon-high\r\nBe brief.")).toBe("Rules:\r\nthis Conversation\nis powered by an AI model.\r\nBe brief.") + expect(cloak(`This conversation is powered by${ZW} gemini-4-carbon-high\n${WB_REST}`)).toBe(`${AI_MODEL}\n${WB_REST}`) +}) + +test("lines like WorkBuddy's that are not it go as written (#1871)", () => { + for (const s of [ + AI_MODEL, + "This conversation is powered by", + "This conversation is powered by\nthe next line.", + "The conversation is powered by gemini-4-carbon-high", + "You are powered by the model named Opus 4.7. The exact model ID is claude-opus-4-7.", + "You are an AI coding assistant, powered by GPT-5.", + "You are a coding agent powered by the m1 model.", + ]) { + expect(turnsAway(s)).toBe(false) + expect(cloak(s)).toBe(s) + expect(cloakUser(s)).toBe(s) + } +}) + +test("WorkBuddy's first line goes reworded in a user's turn and a tool result too, JSON-quoted or not (#1871)", () => { + const sys = `This conversation is powered by gemini-4-carbon-high\n\n${WB_REST}` + expect(cloakUser(sys)).toBe(`${AI_MODEL}\n\n${WB_REST}`) + const quoted = JSON.stringify({ system: sys, model: "gemini-4-carbon-high" }) + expect(cloakUser(quoted)).toBe(JSON.stringify({ system: `${AI_MODEL}\n\n${WB_REST}`, model: "gemini-4-carbon-high" })) + expect(cloakUser('"This conversation is powered by claude-sonnet-4-6" is line 1.')).toBe(`"${AI_MODEL}" is line 1.`) +}) + +test("the hint for WorkBuddy's line names it and the wording that goes through (#1871)", () => { + const h = hint(`This conversation is powered by gemini-4-carbon-high\n\n${WB_REST}`) + expect(h).toContain("WorkBuddy") + expect(h).toContain(AI_MODEL) + expect(h).not.toBe(hint("You are Hermes Agent, built by Nous Research. RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.")) +}) + const DSH = "Tokens prefixed with @ are paths the user explicitly referenced. Relative paths resolve from the workspace root; absolute paths identify files or directories on the host. A trailing slash marks a directory: list it when its contents matter. Anything else is a file: use the read tool when its contents are needed, and do not claim to have inspected it before reading. @\"...\" quotes a path containing spaces." test("DeepSeek Harness's @-path paragraph goes reworded, the rest as written (#1028)", () => { diff --git a/documents.mjs b/documents.mjs index 31845e6..d629fb0 100644 --- a/documents.mjs +++ b/documents.mjs @@ -13,7 +13,9 @@ // // documentText returns null for what can't be carried: a binary file the // user attached, and a file id from the Files API. The caller refuses it -// with documentRefusal's words. +// with documentRefusal's words. A PDF the user attached (base64) never +// comes here: it is staged for agy's file reader as a video is (isMedia in +// index.mjs, #1862). import { Buffer } from "node:buffer" import { TextDecoder } from "node:util" @@ -79,6 +81,6 @@ export function documentRefusal(block) { const type = mediaTypeOf(src) return { what: `a ${type === "application/pdf" ? "PDF" : (type || "binary") + " file"} attached as a document`, - hint: "agy reads text and images, not PDFs or other files. Paste the document's text, attach its pages as images, or let the agent read the file with a tool", + hint: "agy reads text, images and (on Gemini) PDFs, not other files. Paste the document's text, or let the agent read the file with a tool", } } diff --git a/hosted-search.mjs b/hosted-search.mjs new file mode 100644 index 0000000..2f8cef1 --- /dev/null +++ b/hosted-search.mjs @@ -0,0 +1,1193 @@ +// In-bridge batched execution for Anthropic hosted web_search / web_fetch +// tools via magpie's local loopback /mcp/magpie/web-search endpoint. +// +// When enabled via Magpie's `hosted_search` provider switch (off by default), +// `agy-cli` advertises provider-level `searches: true` in `config` so Magpie +// passes Anthropic requests carrying hosted `web_search_*` / `web_fetch_*` +// tools straight to the plugin instead of running its outer serial loop. +// The bridge exposes batch-capable MCP tools inside the live `agy` session, +// runs at most 2 MCP calls in flight per batch, streams native Anthropic +// `server_tool_use` and `web_search_tool_result` / `web_fetch_tool_result` +// blocks, and hands results back without dropping the live session. + +import { randomBytes } from "node:crypto" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" + +export const HOSTED_SEARCH_OPTION = "hosted_search" + +const HOSTED_WEB_SEARCH_RE = /^web_search(?:_\d{8}|_latest)?$/ +const HOSTED_WEB_FETCH_RE = /^web_fetch(?:_\d{8}|_latest)?$/ + +const DEFAULT_SEARCH_COUNT = 6 +const MAX_SEARCH_COUNT = 20 +const MAX_SEARCH_BATCH = 10 +const MAX_FETCH_BATCH = 3 +const MAX_BATCH_CONCURRENCY = 2 +const DEFAULT_MAX_USES = 20 +const DEFAULT_SEARCH_TIMEOUT_MS = 30_000 +const DEFAULT_FETCH_TIMEOUT_MS = 30_000 +// agy fails an ide-tools MCP call after a fixed 180s; cap total batch wall time +// well below that so a hung search backend never triggers an agy MCP timeout. +const DEFAULT_BATCH_DEADLINE_MS = 120_000 +const DEFAULT_FETCH_MAX_CHARS = 20_000 +const MAX_FETCH_MAX_CHARS = 100_000 +const DEFAULT_MCP_MAX_CHARS = 7_500 +const MAX_QUERY_CHARS = 512 + +const DEFAULT_USER_AGENT = (() => { + try { + const pkg = JSON.parse(fs.readFileSync(new URL("./package.json", import.meta.url), "utf8")) + const ver = typeof pkg?.version === "string" && pkg.version.trim() ? pkg.version.trim() : "0.0.0" + return `agy-cli/${ver}` + } catch { + return "agy-cli/0.0.0" + } +})() + +function positiveInt(raw, fallback, max = Number.MAX_SAFE_INTEGER) { + if (raw === undefined || raw === null || String(raw).trim() === "") return fallback + const n = Math.floor(Number(raw)) + return Number.isFinite(n) && n > 0 ? Math.min(n, max) : fallback +} + +export function hostedSearchForcedOff(env = process.env) { + const raw = String(env?.AGY_BRIDGE_HOSTED_SEARCH ?? "").trim().toLowerCase() + return raw === "0" || raw === "false" || raw === "off" || raw === "no" +} + +export function hostedSearchEnabled(env = process.env, { magpieOption, pluginOptions } = {}) { + const raw = String(env?.AGY_BRIDGE_HOSTED_SEARCH ?? "").trim().toLowerCase() + if (raw === "1" || raw === "true" || raw === "on" || raw === "yes") return true + if (raw === "0" || raw === "false" || raw === "off" || raw === "no") return false + if (typeof magpieOption === "boolean") return magpieOption + if (typeof pluginOptions?.hosted_search === "boolean") return pluginOptions.hosted_search + if (typeof pluginOptions?.hostedSearch === "boolean") return pluginOptions.hostedSearch + return false +} + +export function isHostedWebSearchTool(tool) { + return Boolean( + tool && + typeof tool === "object" && + !Array.isArray(tool) && + typeof tool.type === "string" && + HOSTED_WEB_SEARCH_RE.test(tool.type) && + !tool.input_schema, + ) +} + +export function isHostedWebFetchTool(tool) { + return Boolean( + tool && + typeof tool === "object" && + !Array.isArray(tool) && + typeof tool.type === "string" && + HOSTED_WEB_FETCH_RE.test(tool.type) && + !tool.input_schema, + ) +} + +export function isHostedSearchOrFetchTool(tool) { + return isHostedWebSearchTool(tool) || isHostedWebFetchTool(tool) +} + +function cleanDomainList(value) { + if (!Array.isArray(value)) return [] + return value + .filter((item) => typeof item === "string" && item.trim()) + .map((item) => item.trim()) +} + +// Converts an Anthropic hosted web_search_* or web_fetch_* tool declaration +// into: +// - mcpTool: pure MCP tool spec exposed to agy (supports batched calls) +// - config: internal metadata kept on Proc.hostedTools (never sent to agy) +export function buildHostedTool(tool) { + if (isHostedWebSearchTool(tool)) { + const name = typeof tool.name === "string" && tool.name.trim() ? tool.name.trim() : "web_search" + const allowedDomains = cleanDomainList(tool.allowed_domains) + const blockedDomains = cleanDomainList(tool.blocked_domains) + const maxUses = Number.isInteger(tool.max_uses) && tool.max_uses > 0 ? tool.max_uses : null + const mcpTool = { + name, + description: + "Search the live web for current information, news, releases, docs, or facts. " + + "When you need multiple searches, pass ALL independent queries together in `queries` in ONE call (up to 10 per call); " + + "use `query` for a single lookup. Cite the returned URLs.", + inputSchema: { + type: "object", + properties: { + queries: { + type: "array", + items: { type: "string" }, + description: "List of search queries (up to 10 per call) to submit in a single step (preferred whenever you have 2 or more queries).", + }, + query: { + type: "string", + description: "Single search query (use `queries` instead when running multiple searches).", + }, + count: { + type: "integer", + description: "Results per query, 1 to 20 (default 6).", + }, + recency_days: { + type: "integer", + description: "Optional: only include pages from the last N days.", + }, + }, + }, + } + return { + mcpTool, + config: { + kind: "web_search", + name, + type: tool.type, + allowedDomains, + blockedDomains, + maxUses, + }, + } + } + if (isHostedWebFetchTool(tool)) { + const name = typeof tool.name === "string" && tool.name.trim() ? tool.name.trim() : "web_fetch" + const allowedDomains = cleanDomainList(tool.allowed_domains) + const blockedDomains = cleanDomainList(tool.blocked_domains) + const maxUses = Number.isInteger(tool.max_uses) && tool.max_uses > 0 ? tool.max_uses : null + const maxContentTokens = Number.isInteger(tool.max_content_tokens) && tool.max_content_tokens > 0 + ? tool.max_content_tokens + : null + const mcpTool = { + name, + description: + "Fetch readable text from http(s) web pages. " + + "Use `url` (with optional `offset`) to read or continue a single page, `urls` to preview up to 3 pages from the start in one step, " + + "or `requests` when fetching multiple pages with per-URL `offset` values.", + inputSchema: { + type: "object", + properties: { + url: { + type: "string", + description: "Single http(s) URL to fetch (required when continuing a page with `offset` > 0).", + }, + urls: { + type: "array", + items: { type: "string" }, + description: "Up to 3 http(s) URLs to fetch in one step from the start (offset 0 only).", + }, + requests: { + type: "array", + description: "Up to 3 per-URL fetch requests, each with its own `url` and optional `offset` / `max_chars`.", + items: { + type: "object", + properties: { + url: { type: "string" }, + offset: { type: "integer" }, + max_chars: { type: "integer" }, + }, + required: ["url"], + }, + }, + max_chars: { + type: "integer", + description: "Maximum characters to return per page (default 20000 when spilled-output reading is available; inline-only clients cap each reply under 7500 UTF-8 bytes and report the exact `offset` to continue).", + }, + offset: { + type: "integer", + description: "Character offset for continuing a single `url` (default 0; do not combine non-zero `offset` with multiple `urls`).", + }, + }, + }, + } + return { + mcpTool, + config: { + kind: "web_fetch", + name, + type: tool.type, + allowedDomains, + blockedDomains, + maxUses, + maxContentTokens, + }, + } + } + return null +} + +// Anthropic domain matching: host + subdomains, plus optional path prefix. +export function matchesDomain(rawUrl, domain) { + let parsed + try { + parsed = new URL(rawUrl) + } catch { + return false + } + const slash = domain.indexOf("/") + const host = (slash < 0 ? domain : domain.slice(0, slash)).replace(/^\*\./, "").toLowerCase() + const prefix = slash < 0 ? "" : domain.slice(slash) + const h = parsed.hostname.toLowerCase() + return (h === host || h.endsWith("." + host)) && (!prefix || parsed.pathname.startsWith(prefix)) +} + +export function domainAllowed(rawUrl, allowedDomains = [], blockedDomains = []) { + if (allowedDomains.length && !allowedDomains.some((d) => matchesDomain(rawUrl, d))) return false + if (blockedDomains.length && blockedDomains.some((d) => matchesDomain(rawUrl, d))) return false + return true +} + +// Detects queries containing only site:/-site: operators (plus boolean glue / +// punctuation) with no real search keywords left. Used purely for validation; +// valid queries are still forwarded verbatim with site: intact. +export function isSiteOnlyQuery(query) { + const raw = String(query || "").trim() + if (!raw) return true + if (!/\bsite:/i.test(raw)) return false + const stripped = raw + .replace(/-?\bsite:(?:"[^"]*"|\S+)/gi, " ") + .replace(/\b(?:OR|AND|NOT)\b/gi, " ") + .replace(/[()|"']/g, " ") + return !/[\p{L}\p{N}]/u.test(stripped) +} + +export function extractSearchQueriesInfo(args) { + const maxBatch = MAX_SEARCH_BATCH + const rawList = [] + if (Array.isArray(args?.queries)) { + for (const item of args.queries) { + if (typeof item === "string") rawList.push(item) + } + } + if (typeof args?.query === "string") rawList.push(args.query) + const seen = new Set() + const unique = [] + for (const raw of rawList) { + const q = raw.trim() + if (!q) continue + const key = q.toLowerCase() + if (seen.has(key)) continue + seen.add(key) + unique.push(q) + } + const queries = unique.slice(0, maxBatch) + return { queries, omittedCount: Math.max(0, unique.length - queries.length), maxBatch } +} + +export function extractSearchQueries(args) { + return extractSearchQueriesInfo(args).queries +} + +function nonNegativeInt(value, fallback = 0) { + if (value === undefined || value === null || value === "") return fallback + const n = Number(value) + return Number.isInteger(n) && n >= 0 ? n : -1 +} + +export function extractFetchTasksInfo(args) { + const maxBatch = MAX_FETCH_BATCH + const topOffset = nonNegativeInt(args?.offset, 0) + if (topOffset < 0) { + return { items: [], invalidError: "offset must be a non-negative integer.", omittedCount: 0, maxBatch } + } + + const rawItems = [] + if (Array.isArray(args?.requests) && args.requests.length > 0) { + for (const req of args.requests) { + if (!req || typeof req !== "object" || typeof req.url !== "string") continue + const u = req.url.trim() + if (!u) continue + const itemOffset = nonNegativeInt(req.offset, 0) + if (itemOffset < 0) { + return { items: [], invalidError: `offset for ${u} must be a non-negative integer.`, omittedCount: 0, maxBatch } + } + rawItems.push({ url: u, offset: itemOffset, maxChars: req.max_chars }) + } + } + + const urlStrings = [] + if (Array.isArray(args?.urls)) { + for (const item of args.urls) { + if (typeof item === "string" && item.trim()) urlStrings.push(item.trim()) + } + } + if (typeof args?.url === "string" && args.url.trim()) { + urlStrings.push(args.url.trim()) + } + const uniquePlainUrls = [...new Set(urlStrings)] + if (topOffset > 0 && uniquePlainUrls.length > 1) { + return { + items: [], + multiUrlOffsetError: true, + attemptedUrl: uniquePlainUrls[0], + offset: topOffset, + omittedCount: 0, + maxBatch, + } + } + for (const u of uniquePlainUrls) { + rawItems.push({ url: u, offset: topOffset, maxChars: undefined }) + } + + const seen = new Set() + const unique = [] + for (const item of rawItems) { + const key = `${item.url}#${item.offset}` + if (seen.has(key)) continue + seen.add(key) + unique.push(item) + } + const items = unique.slice(0, maxBatch) + return { items, omittedCount: Math.max(0, unique.length - items.length), maxBatch } +} + +export function extractFetchUrlsInfo(args) { + const info = extractFetchTasksInfo(args) + return { urls: info.items.map((it) => it.url), omittedCount: info.omittedCount, maxBatch: info.maxBatch } +} + +export function extractFetchUrls(args) { + return extractFetchUrlsInfo(args).urls +} + +// Parses magpie's /mcp/magpie/web-search text response: +// 1. Title — https://example.com/a +// Snippet text... +// +// 2. Another Title — Sub — https://example.com/b +// Snippet text... +const HEADER_RE = /^(\d+)\.\s+(?:(.+)\s+[—–-]\s+)?(https?:\/\/\S+)\s*$/ + +export function parseMagpieSearchText(text) { + if (typeof text !== "string" || !text.trim()) return [] + const lines = text.replace(/\r\n/g, "\n").split("\n") + const hits = [] + let current = null + for (const line of lines) { + const match = HEADER_RE.exec(line.trim()) + if (match) { + if (current) { + current.snippet = current.snippetLines.join("\n").trim() + delete current.snippetLines + hits.push(current) + } + const rawUrl = match[3].replace(/[)>.,;]+$/, "") + let title = (match[2] || "").trim() + if (!title) { + try { title = new URL(rawUrl).hostname } catch { title = rawUrl } + } + current = { title, url: rawUrl, snippetLines: [] } + continue + } + if (current) current.snippetLines.push(line) + } + if (current) { + current.snippet = current.snippetLines.join("\n").trim() + delete current.snippetLines + hits.push(current) + } + return hits +} + +function findPortableMagpieDataDir() { + try { + let dir = path.dirname(fileURLToPath(import.meta.url)) + for (let i = 0; i < 10; i++) { + const dataDir = path.join(dir, "data") + if (fs.existsSync(path.join(dataDir, "settings.json")) || fs.existsSync(path.join(dataDir, "gateway.json"))) { + return dataDir + } + const up = path.dirname(dir) + if (up === dir) break + dir = up + } + } catch {} + return "" +} + +// Matches magpie's own internal/appdir/appdir.go: portable installs (`data` +// folder beside Magpie) come first, then $XDG_CONFIG_HOME/magpie, then +// ~/.config/magpie on every OS. +export function magpieConfigDirs(env = process.env) { + const explicit = String(env?.AGY_BRIDGE_MAGPIE_CONFIG_DIR || "").trim() + if (explicit) return [explicit] + const magpieDir = String(env?.MAGPIE_CONFIG_DIR || "").trim() + if (magpieDir) return [magpieDir] + + const dirs = [] + const push = (d) => { + if (d && !dirs.includes(d)) dirs.push(d) + } + push(findPortableMagpieDataDir()) + const xdg = String(env?.XDG_CONFIG_HOME || "").trim() + if (xdg) { + push(path.join(xdg, "magpie")) + return dirs + } + const home = String(env?.HOME || env?.USERPROFILE || os.homedir() || "").trim() + if (home) push(path.join(home, ".config", "magpie")) + return dirs +} + +export function isLoopbackHost(hostname) { + const h = String(hostname || "").trim().replace(/^\[|\]$/g, "").toLowerCase() + if (h === "localhost" || h === "::1" || h === "0:0:0:0:0:0:0:1") return true + const m = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h) + return Boolean(m && Number(m[1]) <= 255 && Number(m[2]) <= 255 && Number(m[3]) <= 255) +} + +export function isLoopbackUrl(rawUrl) { + try { + const parsed = new URL(String(rawUrl || "").trim()) + return isLoopbackHost(parsed.hostname) + } catch { + return false + } +} + +// Auto-discovered endpoints only accept loopback addresses (wildcard binds map +// to 127.0.0.1). Non-loopback URLs require setting AGY_BRIDGE_SEARCH_URL. +function normalizeAddrToHttpBase(addr) { + const s = String(addr || "").trim() + if (!s) return "" + if (/^https?:\/\//i.test(s)) { + try { + const parsed = new URL(s) + if (!isLoopbackHost(parsed.hostname)) return "" + return s.replace(/\/+$/, "") + } catch { + return "" + } + } + const m = /^(?:\[(::|::1|[^\]]+)\]|([^:]*)):(\d+)$/.exec(s) + if (!m) return "" + const hostRaw = m[1] || m[2] || "" + const port = m[3] + const host = !hostRaw || hostRaw === "0.0.0.0" || hostRaw === "::" || hostRaw === "*" ? "127.0.0.1" : hostRaw + if (!isLoopbackHost(host)) return "" + const bracketed = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host + return `http://${bracketed}:${port}` +} + +function readConfiguredHttpBase(dir) { + try { + const gw = JSON.parse(fs.readFileSync(path.join(dir, "gateway.json"), "utf8")) + const base = normalizeAddrToHttpBase(gw?.addr) + if (base) return base + } catch {} + try { + const settings = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8")) + const addrBase = normalizeAddrToHttpBase(settings?.addr ?? settings?.gatewayAddr) + if (addrBase) return addrBase + const rawPort = settings?.port ?? settings?.gatewayPort ?? settings?.listen + const portBase = normalizeAddrToHttpBase(rawPort) + if (portBase) return portBase + const port = Number(rawPort) + if (Number.isInteger(port) && port > 0 && port < 65536) return `http://127.0.0.1:${port}` + } catch {} + return "" +} + +export function resolveSearchEndpoint(env = process.env) { + const explicit = String(env?.AGY_BRIDGE_SEARCH_URL || "").trim() + if (explicit) return explicit + const fromAddr = normalizeAddrToHttpBase(env?.MAGPIE_ADDR) + if (fromAddr) return `${fromAddr}/mcp/magpie/web-search` + for (const dir of magpieConfigDirs(env)) { + const base = readConfiguredHttpBase(dir) + if (base) return `${base}/mcp/magpie/web-search` + } + return "http://127.0.0.1:3425/mcp/magpie/web-search" +} + +// Loopback calls to Magpie's MCP server need no key at all (sending a key from +// caller-keys.json would charge another caller's limits/attribution or hit 403 +// on restricted keys). Only non-loopback AGY_BRIDGE_SEARCH_URL endpoints use an +// explicitly configured AGY_BRIDGE_SEARCH_KEY. +export function resolveSearchApiKey(env = process.env, endpoint = "") { + const target = endpoint || resolveSearchEndpoint(env) + if (isLoopbackUrl(target)) return "" + return String(env?.AGY_BRIDGE_SEARCH_KEY || "").trim() +} + +function parseMcpBody(rawText, contentType = "") { + const text = String(rawText || "").trim() + if (!text) throw new Error("empty MCP search response") + if (contentType.includes("text/event-stream") || text.startsWith("event:") || text.startsWith("data:")) { + const dataLines = text + .split(/\r?\n/) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).trim()) + .filter(Boolean) + for (let i = dataLines.length - 1; i >= 0; i--) { + try { + return JSON.parse(dataLines[i]) + } catch {} + } + throw new Error("unparseable SSE response from MCP search endpoint") + } + return JSON.parse(text) +} + +function mcpTextOf(result) { + if (!result || typeof result !== "object") return "" + if (Array.isArray(result.content)) { + return result.content + .filter((part) => part?.type === "text" && typeof part.text === "string") + .map((part) => part.text) + .join("\n") + } + if (typeof result.text === "string") return result.text + return "" +} + +function sanitizeErrorMessage(err) { + return String(err?.message || err || "search failed") + .replace(/Bearer\s+\S+/gi, "Bearer ***") + .replace(/\b(?:sk|tvly|mpk|ksk)[-_][A-Za-z0-9._-]{6,}/gi, "***") + .slice(0, 300) +} + +let rpcSerial = 0 + +async function callMagpieMcpTool(toolName, toolArgs, { + signal, + env = process.env, + fetchImpl = fetch, + timeoutMs = DEFAULT_SEARCH_TIMEOUT_MS, + userAgent = DEFAULT_USER_AGENT, +} = {}) { + const endpoint = resolveSearchEndpoint(env) + const apiKey = resolveSearchApiKey(env, endpoint) + const headers = { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + "User-Agent": userAgent || DEFAULT_USER_AGENT, + ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), + } + const timeoutSignal = AbortSignal.timeout(timeoutMs) + const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal + const res = await fetchImpl(endpoint, { + method: "POST", + headers, + body: JSON.stringify({ + jsonrpc: "2.0", + id: ++rpcSerial, + method: "tools/call", + params: { name: toolName, arguments: toolArgs }, + }), + signal: combinedSignal, + }) + const raw = await res.text() + if (!res.ok) { + let detail = raw.slice(0, 200) + try { + const parsed = JSON.parse(raw) + detail = parsed?.error?.message || detail + } catch {} + const err = new Error(`MCP ${toolName} HTTP ${res.status}: ${detail}`) + err.status = res.status + throw err + } + const payload = parseMcpBody(raw, res.headers?.get?.("content-type") || "") + if (payload?.error) { + const err = new Error(`MCP ${toolName} error: ${payload.error.message || JSON.stringify(payload.error)}`) + err.code = payload.error.code + throw err + } + const result = payload?.result ?? {} + const text = mcpTextOf(result) + if (result.isError) { + const err = new Error(text || `MCP ${toolName} returned isError`) + err.isToolError = true + throw err + } + return text +} + +function newServerToolId() { + return "srvtoolu_" + randomBytes(12).toString("hex") +} + +function errorCodeOf(err) { + if (err?.status === 429) return "too_many_requests" + return "unavailable" +} + +function formatHitsForModel(hits) { + if (!hits.length) return "No results found." + return hits + .map((hit, i) => `${i + 1}. ${hit.title} — ${hit.url}${hit.snippet ? "\n" + hit.snippet : ""}`) + .join("\n\n") +} + +function sliceUtf8CodePoints(text, maxBytes) { + const s = String(text || "") + if (maxBytes <= 0) return "" + if (Buffer.byteLength(s, "utf8") <= maxBytes) return s + let lo = 0 + let hi = s.length + while (lo < hi) { + const mid = (lo + hi + 1) >> 1 + if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid + else hi = mid - 1 + } + if (lo > 0 && s.charCodeAt(lo - 1) >= 0xd800 && s.charCodeAt(lo - 1) <= 0xdbff) lo-- + return s.slice(0, lo) +} + +function truncateUtf8(text, maxBytes) { + const s = String(text || "") + if (maxBytes <= 0) return "" + if (Buffer.byteLength(s, "utf8") <= maxBytes) return s + const suffix = "…" + const limit = Math.max(0, maxBytes - Buffer.byteLength(suffix, "utf8")) + return sliceUtf8CodePoints(s, limit).trimEnd() + suffix +} + +function compactWhitespace(text) { + return String(text || "").replace(/\s+/g, " ").trim() +} + +// agy spills any single MCP tool response above ~10 KB (10,240 bytes) to disk +// and hands the model only a ~9.9 KB head+tail preview, dropping middle queries +// of a batch. Keep the combined search MCP text strictly within `maxBytes` +// while preserving every query section, hit title, and URL. +export function formatSearchOutcomesForModel(outcomes, maxBytes = DEFAULT_MCP_MAX_CHARS) { + const render = (items) => ( + items.length === 1 + ? items[0].text + : items.map((o, i) => `=== Search query ${i + 1}: ${o.query} ===\n${o.text}`).join("\n\n") + ) + const rawCombined = render(outcomes) + if (Buffer.byteLength(rawCombined, "utf8") <= maxBytes) return rawCombined + + const multi = outcomes.length > 1 + const sepBytes = multi ? 2 * (outcomes.length - 1) : 0 + const headers = multi ? outcomes.map((o, i) => `=== Search query ${i + 1}: ${o.query} ===\n`) : outcomes.map(() => "") + const headerBytes = headers.reduce((sum, h) => sum + Buffer.byteLength(h, "utf8"), 0) + const available = Math.max(256, maxBytes - sepBytes - headerBytes) + const perQueryBytes = Math.max(120, Math.floor(available / outcomes.length)) + + const parts = outcomes.map((o, idx) => { + const header = headers[idx] + if (!o.ok || !Array.isArray(o.hits) || !o.hits.length) { + return header + truncateUtf8(compactWhitespace(o.text), perQueryBytes) + } + const maxHits = outcomes.length >= 5 ? 3 : outcomes.length >= 3 ? 4 : o.hits.length + const chosen = o.hits.slice(0, maxHits) + const perHitBytes = Math.max(80, Math.floor((perQueryBytes - Math.max(0, chosen.length - 1) * 2) / chosen.length)) + const lines = [] + let used = 0 + for (let i = 0; i < chosen.length; i++) { + const hit = chosen[i] + const head = `${i + 1}. ${compactWhitespace(hit.title)} — ${hit.url}` + const headBytes = Buffer.byteLength(head, "utf8") + const remaining = perQueryBytes - used - (lines.length ? 2 : 0) + if (lines.length > 0 && headBytes > remaining) break + const snippetBudget = Math.min(perHitBytes, remaining) - headBytes - 1 + const snippet = snippetBudget >= 32 && hit.snippet + ? truncateUtf8(compactWhitespace(hit.snippet), snippetBudget) + : "" + const entry = snippet ? `${head}\n${snippet}` : truncateUtf8(head, Math.max(60, remaining)) + lines.push(entry) + used += (lines.length > 1 ? 2 : 0) + Buffer.byteLength(entry, "utf8") + } + return header + (lines.length ? lines.join("\n\n") : truncateUtf8(compactWhitespace(o.text), perQueryBytes)) + }) + return truncateUtf8(parts.join("\n\n"), maxBytes) +} + +// Matches Magpie's internal/gateway/search_fetch.go `fetchPart` layout: +// URL: \n +// Title: \n (optional) +// \n +// <body runes> +// \n\n[<rem> more characters: call web_fetch with offset=<end> to read on] +const MAGPIE_FETCH_HEADER_RE = /^(URL: [^\n]*\n(?:Title: [^\n]*\n)?\n)/ +const MAGPIE_FETCH_FOOTER_RE = /\n\n\[(\d+) more characters: call web_fetch with offset=(\d+) to read on\]\s*$/ + +// Fits a `web_fetch` page response within `byteBudget` UTF-8 bytes for clients +// that have no file-reading tool to inspect agy's spilled output, computing the +// exact next `offset` in Unicode code points (matching Go `[]rune` indexing in +// Magpie's `fetchPart`). +export function fitMagpieFetchOutput(pageText, url, reqOffset, byteBudget, toolName = "web_fetch") { + const raw = String(pageText || "") + const hm = MAGPIE_FETCH_HEADER_RE.exec(raw) + const header = hm ? hm[1] : "" + const afterHeader = hm ? raw.slice(header.length) : raw + const fm = MAGPIE_FETCH_FOOTER_RE.exec(afterHeader) + const body = fm ? afterHeader.slice(0, fm.index) : afterHeader + const extraMoreRunes = fm ? Number(fm[1]) : 0 + + if (Buffer.byteLength(raw, "utf8") <= byteBudget) { + if (!fm) return raw + const totalBodyRunes = Array.from(body).length + const nextOffset = reqOffset + totalBodyRunes + const rewritten = `${header}${body}\n\n[${extraMoreRunes} more characters: call ${toolName} with url=${JSON.stringify(url)} and offset=${nextOffset} to read on]` + return Buffer.byteLength(rewritten, "utf8") <= byteBudget ? rewritten : raw + } + + const totalChunkRunes = Array.from(body).length + const totalRemainingFromStart = totalChunkRunes + extraMoreRunes + // Worst-case footer length with full remaining count and offset digits. + const sampleFooter = `\n\n[${totalRemainingFromStart} more characters: call ${toolName} with url=${JSON.stringify(url)} and offset=${reqOffset + totalChunkRunes} to read on]` + const footerReserve = Buffer.byteLength(sampleFooter, "utf8") + const headerBytes = Buffer.byteLength(header, "utf8") + const bodyBudget = Math.max(64, byteBudget - headerBytes - footerReserve) + const keptBody = sliceUtf8CodePoints(body, bodyBudget) + const keptRunes = Array.from(keptBody).length + const nextOffset = reqOffset + keptRunes + const remainingRunes = Math.max(1, totalRemainingFromStart - keptRunes) + const footer = `\n\n[${remainingRunes} more characters: call ${toolName} with url=${JSON.stringify(url)} and offset=${nextOffset} to read on]` + return `${header}${keptBody}${footer}` +} + +function effectiveMaxUses(config, env = process.env) { + if (config?.maxUses != null) return config.maxUses + return positiveInt(env.AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES, DEFAULT_MAX_USES, DEFAULT_MAX_USES) +} + +// Per-batch (never process-global) worker pool so each session runs at most +// `concurrency` MCP calls in flight at once without queueing unrelated users. +async function runBatchWithConcurrency(items, concurrency, fn) { + const results = new Array(items.length) + let nextIndex = 0 + const workerCount = Math.min(Math.max(1, concurrency), items.length) + const workers = Array.from({ length: workerCount }, async () => { + while (true) { + const idx = nextIndex++ + if (idx >= items.length) break + results[idx] = await fn(items[idx], idx) + } + }) + await Promise.all(workers) + return results +} + +function appendBudgetFooters(bodyText, footers, maxMcpBytes) { + const validFooters = footers.filter(Boolean) + if (!validFooters.length) return truncateUtf8(bodyText, maxMcpBytes) + const suffix = "\n\n" + validFooters.join("\n") + const suffixBytes = Buffer.byteLength(suffix, "utf8") + const bodyBudget = Math.max(128, maxMcpBytes - suffixBytes) + return truncateUtf8(bodyText, bodyBudget) + suffix +} + +// Executes a hosted web_search MCP call (single or batched, at most 2 in flight) +// and emits Anthropic server_tool_use / web_search_tool_result events onto `emit`. +// Returns { usedDelta, allMaxUsesRejected, mcpResult } for the MCP reply to agy. +export async function executeHostedWebSearch(config, args, { + emit, + usedCount = 0, + rejectedStreak = 0, + onReserve, + signal, + env = process.env, + fetchImpl = fetch, + userAgent = DEFAULT_USER_AGENT, + batchDeadlineMs = DEFAULT_BATCH_DEADLINE_MS, +} = {}) { + const { queries, omittedCount, maxBatch } = extractSearchQueriesInfo(args) + if (!queries.length) { + const id = newServerToolId() + emit?.({ type: "server_tool_use", id, name: config.name, input: { query: "" } }) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_search_tool_result", + content: { type: "web_search_tool_result_error", error_code: "invalid_tool_input" }, + counted: false, + kind: "web_search", + }) + return { + usedDelta: 0, + allMaxUsesRejected: false, + mcpResult: { + content: [{ type: "text", text: "Web search error: provide a non-empty `queries` array or `query` string." }], + isError: true, + }, + } + } + + const defaultCount = queries.length >= 5 ? 3 : queries.length >= 3 ? 4 : DEFAULT_SEARCH_COUNT + const count = positiveInt(args?.count, defaultCount, MAX_SEARCH_COUNT) + const recencyDays = Number.isInteger(args?.recency_days) && args.recency_days > 0 ? args.recency_days : null + const timeoutMs = positiveInt(env.AGY_BRIDGE_SEARCH_TIMEOUT_MS, DEFAULT_SEARCH_TIMEOUT_MS, 120_000) + const batchDeadlineAt = Date.now() + positiveInt(batchDeadlineMs, DEFAULT_BATCH_DEADLINE_MS, DEFAULT_BATCH_DEADLINE_MS) + const maxMcpBytes = positiveInt(env.AGY_BRIDGE_SEARCH_MCP_MAX_CHARS, DEFAULT_MCP_MAX_CHARS, 64_000) + + const maxUses = effectiveMaxUses(config, env) + let remainingUses = Math.max(0, maxUses - usedCount) + let reserved = 0 + + const outcomes = await runBatchWithConcurrency(queries, MAX_BATCH_CONCURRENCY, async (query) => { + if (signal?.aborted) { + return { query, ok: false, skipped: true, text: "Search cancelled.", hits: [] } + } + + const id = newServerToolId() + let rejectedCode = null + let rejectedReason = null + if (query.length > MAX_QUERY_CHARS) { + rejectedCode = "query_too_long" + rejectedReason = "too_long" + } else if (isSiteOnlyQuery(query)) { + rejectedCode = "invalid_tool_input" + rejectedReason = "site_only" + } else if (remainingUses <= 0) { + rejectedCode = "max_uses_exceeded" + rejectedReason = "max_uses" + } + + if (rejectedCode) { + emit?.({ type: "server_tool_use", id, name: config.name, input: { query } }) + const content = { type: "web_search_tool_result_error", error_code: rejectedCode } + emit?.({ + type: "server_tool_result", + id, + resultType: "web_search_tool_result", + content, + counted: false, + kind: "web_search", + }) + let reason + if (rejectedReason === "site_only") { + reason = "query contains only site: filter(s) without search keywords; include topic keywords alongside site:." + } else if (rejectedCode === "max_uses_exceeded") { + reason = rejectedStreak >= 1 + ? `STOP calling ${config.name}. Search budget for this turn is exhausted (0 remaining). Do NOT call ${config.name} again; write your complete final answer now using only the information already collected.` + : "maximum search limit reached for this turn; answer now using what you already found." + } else { + reason = "query exceeds maximum length." + } + return { query, ok: false, rejectedCode, text: `Web search skipped (${rejectedCode}): ${reason}`, hits: [] } + } + + const msLeft = batchDeadlineAt - Date.now() + if (msLeft <= 0) { + return { + query, + ok: false, + skipped: true, + text: "Web search skipped: batch time limit reached before this query started.", + hits: [], + } + } + + remainingUses-- + reserved++ + onReserve?.(1) + emit?.({ type: "server_tool_use", id, name: config.name, input: { query } }) + + const mcpArgs = { + query, + count, + ...(config.allowedDomains.length ? { allowed_domains: config.allowedDomains } : {}), + ...(config.blockedDomains.length ? { blocked_domains: config.blockedDomains } : {}), + ...(recencyDays ? { recency_days: recencyDays } : {}), + } + const taskTimeoutMs = Math.min(timeoutMs, msLeft) + + try { + const rawText = await callMagpieMcpTool("web_search", mcpArgs, { signal, env, fetchImpl, timeoutMs: taskTimeoutMs, userAgent }) + if (signal?.aborted) return { query, ok: false, text: "Search cancelled.", hits: [] } + let hits = parseMagpieSearchText(rawText) + const domainFiltered = config.allowedDomains.length > 0 || config.blockedDomains.length > 0 + if (domainFiltered && hits.length) { + hits = hits.filter((hit) => domainAllowed(hit.url, config.allowedDomains, config.blockedDomains)) + } + const blocks = hits.map((hit) => ({ + type: "web_search_result", + url: hit.url, + title: hit.title, + encrypted_content: "", + page_age: null, + })) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_search_tool_result", + content: blocks, + counted: true, + kind: "web_search", + }) + const modelText = domainFiltered + ? formatHitsForModel(hits) + : (rawText.trim() || "No results found.") + return { query, ok: true, text: modelText, hits } + } catch (err) { + if (signal?.aborted) return { query, ok: false, text: "Search cancelled.", hits: [] } + const code = errorCodeOf(err) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_search_tool_result", + content: { type: "web_search_tool_result_error", error_code: code }, + counted: false, + kind: "web_search", + }) + return { query, ok: false, text: `Web search failed (${code}): ${sanitizeErrorMessage(err)}`, hits: [] } + } + }) + + const allMaxUsesRejected = outcomes.length > 0 && outcomes.every((o) => o.rejectedCode === "max_uses_exceeded") + const anyOk = outcomes.some((o) => o.ok) + let combined + if (allMaxUsesRejected && rejectedStreak >= 1) { + combined = `STOP calling ${config.name}. Your search budget for this turn is exhausted (0 remaining). Do NOT call ${config.name} again; write your complete final answer right now using only the results already collected.` + } else { + const footers = [] + if (omittedCount > 0 && remainingUses > 0) { + footers.push(`[Note: capped at ${maxBatch} queries per call (${omittedCount} omitted); call ${config.name} again for remaining queries if needed.]`) + } + if (reserved > 0) { + if (remainingUses === 0) { + footers.push(`[Search budget: 0 searches remaining for this turn. Do not call ${config.name} again; write your final answer now using the results collected so far.]`) + } else if (remainingUses <= 5) { + footers.push(`[Search budget: ${remainingUses} search${remainingUses === 1 ? "" : "es"} remaining for this turn.]`) + } + } + const footerBytes = footers.length ? Buffer.byteLength("\n\n" + footers.join("\n"), "utf8") : 0 + const body = formatSearchOutcomesForModel(outcomes, Math.max(256, maxMcpBytes - footerBytes)) + combined = appendBudgetFooters(body, footers, maxMcpBytes) + } + + return { + usedDelta: reserved, + allMaxUsesRejected, + mcpResult: { + content: [{ type: "text", text: combined }], + isError: !anyOk, + }, + } +} + +// Executes a hosted web_fetch MCP call (single or batched, at most 2 in flight) +// and emits Anthropic server_tool_use / web_fetch_tool_result events onto `emit`. +export async function executeHostedWebFetch(config, args, { + emit, + usedCount = 0, + rejectedStreak = 0, + canReadSpilled = false, + onReserve, + signal, + env = process.env, + fetchImpl = fetch, + userAgent = DEFAULT_USER_AGENT, + batchDeadlineMs = DEFAULT_BATCH_DEADLINE_MS, +} = {}) { + const extracted = extractFetchTasksInfo(args) + if (extracted.multiUrlOffsetError) { + const id = newServerToolId() + emit?.({ type: "server_tool_use", id, name: config.name, input: { url: extracted.attemptedUrl, offset: extracted.offset } }) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_fetch_tool_result", + content: { type: "web_fetch_tool_result_error", error_code: "invalid_input" }, + counted: false, + kind: "web_fetch", + }) + return { + usedDelta: 0, + allMaxUsesRejected: false, + mcpResult: { + content: [{ + type: "text", + text: `Web fetch error (invalid_input): non-zero offset (${extracted.offset}) applies to a single URL only; call ${config.name} with one \`url\` and \`offset\`, or pass per-URL \`requests: [{ url, offset }]\`.`, + }], + isError: true, + }, + } + } + if (extracted.invalidError || !extracted.items.length) { + const id = newServerToolId() + emit?.({ type: "server_tool_use", id, name: config.name, input: { url: "" } }) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_fetch_tool_result", + content: { type: "web_fetch_tool_result_error", error_code: "invalid_input" }, + counted: false, + kind: "web_fetch", + }) + return { + usedDelta: 0, + allMaxUsesRejected: false, + mcpResult: { + content: [{ type: "text", text: `Web fetch error: ${extracted.invalidError || "provide a valid `url`, `urls`, or `requests` list."}` }], + isError: true, + }, + } + } + + const { items, omittedCount, maxBatch } = extracted + const perUrlMaxChars = Math.max(1000, Math.floor(MAX_FETCH_MAX_CHARS / items.length)) + const tokenCapChars = config.maxContentTokens + ? Math.max(256, Math.floor(Math.min(MAX_FETCH_MAX_CHARS, config.maxContentTokens * 4) / items.length)) + : perUrlMaxChars + const timeoutMs = positiveInt(env.AGY_BRIDGE_FETCH_TIMEOUT_MS, DEFAULT_FETCH_TIMEOUT_MS, 120_000) + const batchDeadlineAt = Date.now() + positiveInt(batchDeadlineMs, DEFAULT_BATCH_DEADLINE_MS, DEFAULT_BATCH_DEADLINE_MS) + const maxMcpBytes = positiveInt(env.AGY_BRIDGE_SEARCH_MCP_MAX_CHARS, DEFAULT_MCP_MAX_CHARS, 64_000) + const configuredMaxChars = env.AGY_BRIDGE_FETCH_MAX_CHARS + ? positiveInt(env.AGY_BRIDGE_FETCH_MAX_CHARS, DEFAULT_FETCH_MAX_CHARS, MAX_FETCH_MAX_CHARS) + : null + + const maxUses = effectiveMaxUses(config, env) + let remainingUses = Math.max(0, maxUses - usedCount) + let reserved = 0 + + const worstCaseFooterBytes = 240 + const bodyBudget = Math.max(512, maxMcpBytes - worstCaseFooterBytes) + const batchHeaderBytes = items.length > 1 + ? items.reduce((sum, it, i) => sum + Buffer.byteLength(`=== Fetched URL ${i + 1}: ${it.url} ===\n`, "utf8"), 0) + 2 * (items.length - 1) + : 0 + const perUrlByteBudget = Math.max(384, Math.floor((bodyBudget - batchHeaderBytes) / items.length)) + + const outcomes = await runBatchWithConcurrency(items, MAX_BATCH_CONCURRENCY, async (item) => { + if (signal?.aborted) { + return { url: item.url, ok: false, skipped: true, text: "Fetch cancelled." } + } + + const id = newServerToolId() + const input = item.offset > 0 ? { url: item.url, offset: item.offset } : { url: item.url } + let rejectedCode = null + let parsed = null + try { parsed = new URL(item.url) } catch {} + if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) rejectedCode = "invalid_input" + else if (!domainAllowed(item.url, config.allowedDomains, config.blockedDomains)) rejectedCode = "url_not_allowed" + else if (remainingUses <= 0) rejectedCode = "max_uses_exceeded" + + if (rejectedCode) { + emit?.({ type: "server_tool_use", id, name: config.name, input }) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_fetch_tool_result", + content: { type: "web_fetch_tool_result_error", error_code: rejectedCode }, + counted: false, + kind: "web_fetch", + }) + return { url: item.url, ok: false, rejectedCode, text: `Web fetch skipped (${rejectedCode}).` } + } + + const msLeft = batchDeadlineAt - Date.now() + if (msLeft <= 0) { + return { + url: item.url, + ok: false, + skipped: true, + text: "Web fetch skipped: batch time limit reached before this URL started.", + } + } + + remainingUses-- + reserved++ + onReserve?.(1) + emit?.({ type: "server_tool_use", id, name: config.name, input }) + + // Clients with a file-read or shell tool handled by `spilled.mjs` can read + // agy's spilled output, so give them Magpie's full 20,000-character budget. + // Inline-only chat clients (Kelivo) have none, so keep each MCP reply within + // `maxMcpBytes` (7500 UTF-8 bytes) and report the exact Go-rune `offset`. + let reqMaxChars + const rawMaxChars = item.maxChars ?? args?.max_chars + if (canReadSpilled) { + const defaultFull = configuredMaxChars != null + ? Math.min(configuredMaxChars, perUrlMaxChars) + : (items.length > 1 ? Math.max(2000, Math.floor(DEFAULT_FETCH_MAX_CHARS / items.length)) : DEFAULT_FETCH_MAX_CHARS) + reqMaxChars = Math.min(positiveInt(rawMaxChars, defaultFull, perUrlMaxChars), perUrlMaxChars, tokenCapChars) + if (configuredMaxChars != null) reqMaxChars = Math.min(reqMaxChars, configuredMaxChars) + } else { + const inlineProbe = configuredMaxChars ?? Math.min(perUrlMaxChars, Math.max(400, perUrlByteBudget + 512)) + reqMaxChars = Math.min(positiveInt(rawMaxChars, inlineProbe, perUrlMaxChars), inlineProbe, perUrlMaxChars, tokenCapChars) + } + + const taskTimeoutMs = Math.min(timeoutMs, msLeft) + + try { + let pageText = await callMagpieMcpTool("web_fetch", { + url: item.url, + max_chars: reqMaxChars, + offset: item.offset, + }, { signal, env, fetchImpl, timeoutMs: taskTimeoutMs, userAgent }) + if (signal?.aborted) return { url: item.url, ok: false, text: "Fetch cancelled." } + if (!canReadSpilled) { + pageText = fitMagpieFetchOutput(pageText, item.url, item.offset, perUrlByteBudget, config.name) + } + emit?.({ + type: "server_tool_result", + id, + resultType: "web_fetch_tool_result", + content: { + type: "web_fetch_result", + url: item.url, + content: { + type: "document", + source: { type: "text", media_type: "text/plain", data: pageText }, + title: "", + }, + retrieved_at: new Date().toISOString(), + }, + counted: true, + kind: "web_fetch", + }) + return { url: item.url, ok: true, text: pageText || "(empty page)" } + } catch (err) { + if (signal?.aborted) return { url: item.url, ok: false, text: "Fetch cancelled." } + const code = errorCodeOf(err) + emit?.({ + type: "server_tool_result", + id, + resultType: "web_fetch_tool_result", + content: { type: "web_fetch_tool_result_error", error_code: code }, + counted: false, + kind: "web_fetch", + }) + return { url: item.url, ok: false, text: `Web fetch failed (${code}): ${sanitizeErrorMessage(err)}` } + } + }) + + const allMaxUsesRejected = outcomes.length > 0 && outcomes.every((o) => o.rejectedCode === "max_uses_exceeded") + const anyOk = outcomes.some((o) => o.ok) + const footers = [] + if (omittedCount > 0 && remainingUses > 0) { + footers.push(`[Note: capped at ${maxBatch} URLs per call (${omittedCount} omitted); call ${config.name} again if needed.]`) + } + if (reserved > 0) { + if (remainingUses === 0) { + footers.push(`[Fetch budget: 0 fetches remaining for this turn. Answer now using the results collected so far.]`) + } else if (remainingUses <= 5) { + footers.push(`[Fetch budget: ${remainingUses} fetch${remainingUses === 1 ? "" : "es"} remaining for this turn.]`) + } + } + + let combined + if (allMaxUsesRejected && rejectedStreak >= 1) { + combined = `STOP calling ${config.name}. Your fetch budget for this turn is exhausted (0 remaining). Write your complete final answer now using only the information already collected.` + } else { + const body = outcomes.length === 1 + ? outcomes[0].text + : outcomes.map((o, i) => `=== Fetched URL ${i + 1}: ${o.url} ===\n${o.text}`).join("\n\n") + combined = !canReadSpilled + ? appendBudgetFooters(body, footers, maxMcpBytes) + : (footers.length ? `${body}\n\n${footers.join("\n")}` : body) + } + + return { + usedDelta: reserved, + allMaxUsesRejected, + mcpResult: { + content: [{ type: "text", text: combined }], + isError: !anyOk, + }, + } +} + +export async function executeHostedTool(config, args, opts) { + if (config.kind === "web_fetch") return executeHostedWebFetch(config, args, opts) + return executeHostedWebSearch(config, args, opts) +} diff --git a/index.mjs b/index.mjs index 0029011..9494c59 100644 --- a/index.mjs +++ b/index.mjs @@ -8,8 +8,8 @@ import net from "node:net" import os from "node:os" import path from "node:path" import { fileURLToPath } from "node:url" -import { ACCOUNT_DISABLED_REFUSED, agyRefusal, createUsageReader, isEligibilityRefusal, verifyLinkIn, verifyRefused } from "./usage.mjs" -import { catalogRows, storeCatalogRows } from "./model-ids.mjs" +import { ACCOUNT_DISABLED_REFUSED, agyRefusal, createUsageReader, isEligibilityRefusal, verifyAskedAtSignIn, verifyLinkIn, verifyRefused } from "./usage.mjs" +import { catalogRows, isOrchestrator, storeCatalogRows } from "./model-ids.mjs" import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, heldByAnother, homeForOwn, isKeptId, keepOwn, keptFor, keptOthers, notHeldError, ownerUnknown, signedInEmail, storedEmail, storedSignIn, storedSignInNow, unknownOwnerError, whoOf } from "./signin.mjs" import { sanitizePatternFields } from "./re2-pattern.mjs" import { startLogin } from "./login.mjs" @@ -27,8 +27,16 @@ import { IMAGE_MODEL_ID, handleImageFetch, imageModelEntry, imageRoute } from ". import { reapOneshotChildren } from "./oneshot-acp.mjs" import { agentSummaryMode, agentSummaryRewrite, runAgentSummary } from "./agent-summary.mjs" import { writeDefaultAgentFiles } from "./default-agent.mjs" +import { spilledOutput } from "./spilled.mjs" import { appGatewayOn as gatewayIn, gatewayFreeDir } from "./gateway-free.mjs" import { agyTooOld } from "./agy-version.mjs" +import { + HOSTED_SEARCH_OPTION, + buildHostedTool, + executeHostedTool, + hostedSearchEnabled, + hostedSearchForcedOff, +} from "./hosted-search.mjs" export { agyTooOld, MIN_AGY_VERSION } from "./agy-version.mjs" @@ -263,7 +271,8 @@ function noteMinimalAgent() { // …" (#1151), and with only agy's own prompt the same account answers // (bzs_1 on X, 11-15). The client's system prompt goes in the first user // turn instead, as <external_system_instructions>, where only Codex's GPT-5 -// lines were turned away (cloak.mjs, USER_TURNED_AWAY). AGY_BRIDGE_SYSTEM_APPEND=1 +// lines were turned away, and since 12-02 WorkBuddy's first line (cloak.mjs, +// USER_TURNED_AWAY). AGY_BRIDGE_SYSTEM_APPEND=1 // goes back to the session instructions. const systemAppend = () => /^(?:1|true|on|yes)$/i.test(process.env.AGY_BRIDGE_SYSTEM_APPEND || "") const FORWARD_THINKING = process.env.AGY_BRIDGE_THINKING !== "0" @@ -555,24 +564,33 @@ function offeredList() { return out.length ? out : null } -// listOffered asks agy acp, on the bridge's folder, what it offers now. -async function listOffered(agyPath) { +// listOffered is what agy acp offers this account. ask (a sign-in, or the +// user's refresh): agy acp, on the bridge's folder, is asked now (askOffer). +// Otherwise it is what a turn's session said last, and agy isn't started. +async function listOffered(agyPath, { ask = false } = {}) { + if (!ask) return offeredList() ms().offeredStale = true - await probeOfferedOnce(agyPath) + await askOfferOnce(agyPath) return ms().offeredStale ? null : offeredList() } -async function listAgyModels(agyPath) { +// ask: the list is being asked for (a sign-in, a refresh, or no list yet), +// so agy acp may be asked in place of `agy models`; asked says it was. +async function listAgyModels(agyPath, { ask = false, asked = {} } = {}) { // a listing nobody asked for doesn't run an agy that would start its own // Google sign-in (signin.mjs); the catalog it has stays if (await backgroundBlocked()) return null - if (await gatewayListed(agyPath)) return listOffered(agyPath) + if (await gatewayListed(agyPath)) { + asked.offer = ask + return listOffered(agyPath, { ask }) + } const { err, stdout, stderr, code, timedOut } = await execOnce(agyPath, await modelsArgs(agyPath), { timeoutMs: 15_000, unrefTimer: true }) // null, not FALLBACK_MODELS: a failed listing must not overwrite a dynamic catalog. if (err || timedOut || code !== 0) { if (err || timedOut) return null const why = agyRefusal(`${stderr}\n${stdout}`) - const served = await servedDespite(agyPath, why) + if (ask && isEligibilityRefusal(why)) asked.offer = true + const served = await servedDespite(agyPath, why, { ask }) noteRefusal(served ? "" : why) return served } @@ -586,12 +604,14 @@ async function listAgyModels(agyPath) { // refuse on that entry ("Eligibility check failed"), while agy acp, which // every turn runs on, serves the account. So an eligibility refusal is the // account's only when agy acp names no tier for it either or offers no -// model; otherwise what agy acp offers is the account's list. -async function servedDespite(agyPath, why) { +// model; otherwise what agy acp offers is the account's list. agy acp is +// asked only when the list is (ask: a sign-in, a refresh, no list yet); +// otherwise the tier and offer a turn's session named last are what it +// says (kept in models.json across restarts). +async function servedDespite(agyPath, why, { ask = false } = {}) { if (!isEligibilityRefusal(why)) return null - const list = await listOffered(agyPath) + const list = await listOffered(agyPath, { ask }) if (!ms().acpTier) return null - // asked within the last minute (probeOfferedOnce): what it offered then return list || offeredList() } @@ -681,7 +701,9 @@ function parseAgyModels(stdout) { // exit code alone can't say so, so a listing without one model in it is // not signed in either. The listing it read is the catalog's, and what agy // acp offers is asked at once (#1064): `agy models` and the session each -// take seconds on a real agy, and the host lists models right after. +// take seconds on a real agy, and the host lists models right after. A +// sign-in is one of the two times agy acp is asked with no turn (the +// other is the user's refresh): the user just added the account. const OFFERED_SIGNIN_WAIT_MS = 3_000 async function probeSignedIn(agy) { @@ -691,7 +713,7 @@ async function probeSignedIn(agy) { const blocked = await backgroundBlocked({ fresh: true }) if (blocked) return { ok: false, why: blocked } if (await gatewayListed(agy)) { - const list = await listOffered(agy) + const list = await listOffered(agy, { ask: true }) if (!list) return { ok: false, why: "agy acp offered no model: agy is not signed in to Google" } useAgyPath(agy) storeListedCatalog(agy, list, Date.now()) @@ -705,15 +727,14 @@ async function probeSignedIn(agy) { if (list) { useAgyPath(agy) storeListedCatalog(agy, list, Date.now()) - ms().wantOfferedProbe = true - await briefly(probeOfferedOnce(agy), OFFERED_SIGNIN_WAIT_MS) + await briefly(askOfferOnce(agy), OFFERED_SIGNIN_WAIT_MS) } return { ok: true } } // Google turned the account away (#3501): signing in again took, and // Google still refuses it; say so, not agy's last line alone const refused = !probe.err && !probe.timedOut ? agyRefusal(`${probe.stderr}\n${probe.stdout}`) : "" - const served = await servedDespite(agy, refused) + const served = await servedDespite(agy, refused, { ask: true }) if (served) { noteRefusal("") useAgyPath(agy) @@ -731,23 +752,22 @@ async function probeSignedIn(agy) { } const EFFORT_ORDER = ["minimal", "low", "medium", "high", "xhigh", "max"] +// How long a listing is taken as what agy lists now: a request for a model +// it lacks is turned away at once when another account lists it (#1542). +// A listing older than this is still served, and isn't asked again for its +// age: agy is asked for the list only at a sign-in, when the user refreshes +// it, or when there is none (loadModelCatalog). const MODEL_CATALOG_TTL_MS = 5 * 60 * 1000 const MODEL_CATALOG_FAST_WAIT_MS = 500 const MODEL_CATALOG_RETRY_MS = 5_000 -// How long what agy acp offered is believed: Google can swap the offered -// model ids server-side, and a learned offer then filters the catalog to -// models ACP no longer offers while hiding the ones it does (2026-11-27: -// the gateway listed claude-4-6 / gemini-3.1-flash-image and omitted -// gemini-4-neon/carbon/argon and claude-5-5 for hours). Past this, the -// offer is stale and asked again. 60 minutes: the offer changes rarely, -// and a probe is a fresh agy acp spawn per account, so re-probing on the -// catalog's 5-minute cadence would spawn far more often than the job -// needs. A request for a model the offer lacks while `agy models` lists it -// asks again sooner (recheckOffer, plugins#1804). -const OFFERED_TTL_MS = 60 * 60 * 1000 -// How often a request may ask agy acp again for its account's offer: the -// offer lacks the model asked for while `agy models` lists it and another +// How long models() waits for a refresh the user asked for: the host gives +// a listing about 15s (listWait), and a real agy takes seconds for `agy +// models` and as long again for agy acp's session. +const MODEL_CATALOG_REFRESH_WAIT_MS = 12_000 +// How often a request may turn the offer stale for its account: the offer +// lacks the model asked for while `agy models` lists it and another // account's list has it, which would turn the request away (plugins#1804). +// The request's own session then says what agy acp offers now. const OFFER_RECHECK_MS = 5 * 60 * 1000 // What is learnt of the models is each account's own (#1229): accounts on @@ -756,23 +776,29 @@ const OFFER_RECHECK_MS = 5 * 60 * 1000 // account's models() in that account (inAccount), serves their union, and // sends a request for a model only to an account that lists it. // +// An idle account sends Google nothing of its own (Discord, 12-03: Google +// banned an Antigravity account no agent had used, while the plugin had run +// `agy models` for it every few minutes and opened an agy acp session with +// no prompt every hour). Its list and offer are kept in +// models.json across restarts and served as they are. agy is asked for +// them only at a sign-in, when the user refreshes the list, or when there +// is none; a turn's own session says what agy acp offers as it opens. +// // - cachedModelCatalog: the last `agy models` list (static until one). // - modelCatalogRefreshPromise: the listing running now. -// - wantOfferedProbe: a caller lists models (provider.models), so a listing -// that lands asks agy acp what it offers right away, not on the next -// models() call (#1064). // - acpOfferedModels, acpOfferedKey: `agy models` lists every model of the // account, while agy's ACP server offers a client only some of them. A // session's model option (and its models.availableModels) says which; // the catalog keeps to that. Before any session has said, only Gemini // models are served. -// - offeredStale: acpOfferedModels is what agy acp offered before (saved in -// models.json by an earlier run, or before `agy models` listed something -// else): served until agy acp is asked again, never believed for good. -// shenggxhz (X, 11-17) moved from Pro to Ultra and kept the Pro account's -// offer, which filtered Gemini 4 out of Ultra's listing. -// - offeredProbePromise, offeredProbeAt, offeredGen: the probe below. -// - offerRecheckAt: when a request last asked the offer again +// - acpTier: the tier agy acp's session/new names for the account +// (plugins#1602). +// - offeredStale: acpOfferedModels is in doubt (a session's update dropped +// models, `agy models` listed something else, or a request found it short +// of a model another account has): it is still served, but no request is +// turned away by it until a session says again. +// - offerAskPromise, offeredGen: askOffer below. +// - offerRecheckAt: when a request last put the offer in doubt // (recheckOffer). const modelStates = new Map() @@ -783,14 +809,11 @@ function ms() { state = { cachedModelCatalog: fallbackModelCatalog(), modelCatalogRefreshPromise: null, - wantOfferedProbe: false, acpOfferedModels: null, acpOfferedKey: "", acpTier: null, offeredStale: false, - offeredAt: 0, - offeredProbePromise: null, - offeredProbeAt: null, + offerAskPromise: null, offeredGen: 0, offerRecheckAt: null, } @@ -815,9 +838,13 @@ function offeredFamily(id) { } // update: the offer comes from a session's config_option_update, not from -// a session agy just opened. -function noteOfferedModels(configOptions, models, { update = false } = {}) { +// a session agy just opened. tier: the tier the opened session names +// (_meta.antigravity.tier.id), null when it names none; left out, the +// tier known stays (a resumed session, an update). +function noteOfferedModels(configOptions, models, { update = false, tier } = {}) { const offered = offeredModelsOf(configOptions, models) + const tierChanged = tier !== undefined && (tier || null) !== ms().acpTier + if (tierChanged) ms().acpTier = tier || null if (!offered.length) return const names = new Map(offered.map(model => [model.id, typeof model.name === "string" && model.name ? model.name : model.id])) const key = [...names.keys()].sort().join("\n") @@ -839,11 +866,16 @@ function noteOfferedModels(configOptions, models, { update = false } = {}) { } } ms().offeredStale = false - ms().offeredAt = Date.now() - if (key === ms().acpOfferedKey) return + // a session that names a tier and offers models serves the account, so + // an eligibility refusal `agy models` gave isn't the account's + // (plugins#1602) + if (ms().acpTier && isEligibilityRefusal(refusalOf())) noteRefusal("") + if (key === ms().acpOfferedKey && !tierChanged) return ms().acpOfferedModels = names ms().acpOfferedKey = key - if (ms().cachedModelCatalog?.agyPath) saveCatalog(ms().cachedModelCatalog.agyPath, { offered: [...names].map(([id, name]) => ({ id, name })) }) + if (ms().cachedModelCatalog?.agyPath) { + saveCatalog(ms().cachedModelCatalog.agyPath, { offered: [...names].map(([id, name]) => ({ id, name })), tier: ms().acpTier }) + } } // A model the session offers that `agy models` did not list is served as is. @@ -859,24 +891,23 @@ function offeredFilter(list) { (modelFamilyId(model) && ms().acpOfferedModels.has(modelFamilyId(model))))) } -// Before any request has opened a session, ask agy itself: a short `agy acp` -// that opens a session (no prompt) and reads what it offers, so the catalog -// lists Claude and GPT-OSS without a Gemini request first. Approach from -// yulong-ge's antigravity-official-acp (#854). +// What agy acp offers, asked with no turn: a short `agy acp` that opens a +// session (no prompt) and reads what it offers, so the catalog lists Claude +// and GPT-OSS before the first request. Approach from yulong-ge's +// antigravity-official-acp (#854). Asked only when the user acts: at a +// sign-in (probeSignedIn) and when the user refreshes the list. It runs +// agy as a turn does (the same flags and client name). const OFFERED_PROBE_TIMEOUT_MS = 30_000 -const OFFERED_PROBE_RETRY_MS = 60_000 -// Bumped when what was learnt about an agy no longer holds (another -// executable, a new sign-in): a probe still running for the old one is -// not believed. +// Bumped when what was learnt about an agy no longer holds (another +// executable, a new sign-in): an ask still running for the old one is not +// believed. function forgetOffered() { ms().acpOfferedModels = null ms().acpOfferedKey = "" ms().acpTier = null ms().offeredStale = false - ms().offeredAt = 0 - ms().offeredProbePromise = null - ms().offeredProbeAt = null + ms().offerAskPromise = null ms().offerRecheckAt = null ms().offeredGen++ } @@ -902,7 +933,7 @@ function killQuietly(child) { } } -async function probeOfferedModels(agyPath) { +async function askOffer(agyPath) { const state = ms() const home = currentHome() const gen = state.offeredGen @@ -914,8 +945,9 @@ async function probeOfferedModels(agyPath) { // on the folder a turn runs on, so it offers what a turn is served // (appGatewayOn: on ~/.gemini it would offer the app's gateway's) const own = await geminiDirArgs(agyPath) + const args = ["acp", ...await noDefaultCustomizationsArgs(agyPath), ...await telemetryArgs(agyPath), ...own.args] workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-models-")) - child = spawnAgy(agyPath, ["acp", ...own.args], { cwd: workspace, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }) + child = spawnAgy(agyPath, args, { cwd: workspace, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }) child.on("error", () => conn?.close(new Error("agy acp failed to start"))) child.on("close", () => conn?.close(new Error("agy acp exited"))) child.stdin?.on("error", () => {}) @@ -941,8 +973,7 @@ async function probeOfferedModels(agyPath) { inAccount(home, () => { // the tier agy acp says the account is served on (plugins#1602) const tier = session?._meta?.antigravity?.tier?.id - ms().acpTier = typeof tier === "string" && tier ? tier : null - noteOfferedModels(session?.configOptions, session?.models) + noteOfferedModels(session?.configOptions, session?.models, { tier: typeof tier === "string" && tier ? tier : null }) }) } const caps = init?.agentCapabilities ?? {} @@ -951,7 +982,8 @@ async function probeOfferedModels(agyPath) { } })()]) } catch { - // Unknown: keep serving Gemini only, and try again later. + // Unknown: what was known stays (Gemini only when nothing was), until + // a turn's session says or the user refreshes again. } finally { clearTimeout(timer) conn?.close(new Error("probe done")) @@ -960,35 +992,26 @@ async function probeOfferedModels(agyPath) { } } -function probeOfferedOnce(agyPath) { - // A learned offer is never believed for good: past the TTL it is stale, - // so the early return below no longer holds it back and agy acp is - // asked again. The 60s retry gate still bounds how often a probe starts. - if (ms().acpOfferedModels && ms().offeredAt && Date.now() - ms().offeredAt >= OFFERED_TTL_MS) ms().offeredStale = true - if ((ms().acpOfferedModels && !ms().offeredStale) || ms().offeredProbePromise) return ms().offeredProbePromise - const now = Date.now() - if (ms().offeredProbeAt !== null && now - ms().offeredProbeAt < OFFERED_PROBE_RETRY_MS) return null - ms().offeredProbeAt = now - const probe = probeOfferedModels(agyPath).finally(() => { - if (ms().offeredProbePromise === probe) ms().offeredProbePromise = null +// askOfferOnce asks once at a time for the account. +function askOfferOnce(agyPath) { + if (ms().offerAskPromise) return ms().offerAskPromise + const ask = askOffer(agyPath).finally(() => { + if (ms().offerAskPromise === ask) ms().offerAskPromise = null }) - ms().offeredProbePromise = probe - return probe + ms().offerAskPromise = ask + return ask } -// recheckOffer asks agy acp again what this account offers, for a request -// whose model the offer lacks while `agy models` lists it (plugins#1804). -// At most once in OFFER_RECHECK_MS for an account, past the probes' own -// retry gate; a probe that fails leaves the offer stale, which is unknown. -async function recheckOffer(agyPath) { +// recheckOffer puts the account's offer in doubt for a request whose model +// the offer lacks while `agy models` lists it (plugins#1804): the request +// goes on, and its own session says what agy acp offers now (a model it +// still doesn't offer is then turned away by #setModel: selection.offered). At most once in +// OFFER_RECHECK_MS for an account; agy acp isn't asked apart from the turn. +function recheckOffer() { const now = Date.now() if (ms().offerRecheckAt !== null && now - ms().offerRecheckAt < OFFER_RECHECK_MS) return ms().offerRecheckAt = now - if (!ms().offeredProbePromise) { - ms().offeredStale = true - ms().offeredProbeAt = null - } - await briefly(probeOfferedOnce(agyPath), OFFERED_PROBE_TIMEOUT_MS) + ms().offeredStale = true } // Web search, as agy itself searches (Kayphoon, magpie#7632): a session on @@ -1265,11 +1288,7 @@ function modelFamilyId(model) { // can't happen here and an Orchestrator turn is its planner alone, at a fixed // thinking level. It isn't listed, and a request naming it is told which // model it would really get. -function isOrchestrator(model) { - const id = typeof model === "string" ? model : model?.id ?? "" - const name = typeof model === "string" ? "" : model?.name ?? "" - return /^gemini-[a-z0-9.]*-?orchestrator/i.test(id) || /^Orchestrator\b/i.test(name) -} +// (isOrchestrator is model-ids.mjs's, which leaves it off usage windows too) function orchestratorPlanner(id) { return /argon|g1-pro/i.test(id) ? "gemini-4-argon" : "gemini-4-carbon" @@ -1346,11 +1365,36 @@ function fallbackModelCatalog(agyPath = null, { replace = false } = {}) { } // The last list `agy models` gave, kept beside sessions.json per agy -// executable (#1086): after a restart the host lists it at once, instead of -// the Gemini-only fallback until agy answers again. It is served as stale -// (fetchedAt 0), so the first models() call still asks agy. +// executable (#1086), with when it was listed (fetchedAt), what agy acp +// offered last and the tier it named: after a restart the account's list +// is served as it was, and agy isn't asked again until a sign-in, the +// user's refresh, or a turn's own session. Another account's entry counts +// for anotherAccountLists only while it is this young. const SAVED_CATALOG_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000 +// The last models.json read whole: a half-written or hand-edited file +// leaves it as it was, and saveCatalog writes over that, not over nothing +// (which would drop every other account's entry). +let lastGoodCatalogs = null + +function readCatalogs() { + const data = JSON.parse(fs.readFileSync(modelCatalogFile(), "utf8")) + if (data?.version !== 1 || !data.byAgy || typeof data.byAgy !== "object") throw new Error("not a models.json") + lastGoodCatalogs = { file: modelCatalogFile(), byAgy: data.byAgy } + return data.byAgy +} + +// catalogsOrLastGood is models.json's entries, or the last good read of the +// same file when it can't be read now (missing: none). +function catalogsOrLastGood() { + try { + return readCatalogs() + } catch (error) { + if (error?.code === "ENOENT") return {} + return lastGoodCatalogs?.file === modelCatalogFile() ? lastGoodCatalogs.byAgy : null + } +} + function modelCatalogFile() { return path.join(path.dirname(sessionStateFile()), "models.json") } @@ -1371,16 +1415,19 @@ function validModelRow(row) { function readSavedCatalog(agyPath) { if (!agyPath) return null try { - const data = JSON.parse(fs.readFileSync(modelCatalogFile(), "utf8")) - const entry = data?.version === 1 && data.byAgy && Object.hasOwn(data.byAgy, catalogKey(agyPath)) ? data.byAgy[catalogKey(agyPath)] : null - if (!entry || !Number.isFinite(entry.at) || Date.now() - entry.at > SAVED_CATALOG_MAX_AGE_MS) return null - // A half-written or hand-edited file means "unknown": the fallback serves. + const byAgy = catalogsOrLastGood() + const entry = byAgy && Object.hasOwn(byAgy, catalogKey(agyPath)) ? byAgy[catalogKey(agyPath)] : null + if (!entry || !Number.isFinite(entry.at)) return null + // A hand-edited entry means "unknown": the fallback serves. if (!Array.isArray(entry.list) || !entry.list.length || !entry.list.every(validModelRow)) return null const offered = Array.isArray(entry.offered) && entry.offered.length && entry.offered.every(row => validModelRow(row) && row.effort === undefined) ? entry.offered : null - return { list: entry.list.map(savedRow), offered: offered && offered.map(({ id, name }) => ({ id, name })) } + // a file written before fetchedAt was kept: listed when it was written + const fetchedAt = Number.isFinite(entry.fetchedAt) ? entry.fetchedAt : entry.at + const tier = typeof entry.tier === "string" && entry.tier ? entry.tier : null + return { list: entry.list.map(savedRow), offered: offered && offered.map(({ id, name }) => ({ id, name })), fetchedAt, tier } } catch { return null } @@ -1390,27 +1437,32 @@ function savedRow({ id, name, effort }) { return effort ? { id, name, effort } : { id, name } } -// saveCatalog merges what changed (the listing, or what agy acp offers) into -// the agy's entry. +// saveCatalog merges what changed (the listing, what agy acp offers, the +// tier it names) into the agy's entry, through a temp file renamed over it. function saveCatalog(agyPath, change) { if (!agyPath) return const file = modelCatalogFile() try { withStateLock(file, () => { - let byAgy = {} - try { - const data = JSON.parse(fs.readFileSync(file, "utf8")) - if (data?.version === 1 && data.byAgy && typeof data.byAgy === "object") byAgy = data.byAgy - } catch {} + const byAgy = { ...(catalogsOrLastGood() || {}) } const key = catalogKey(agyPath) - const entry = { ...(byAgy[key] || {}), at: Date.now() } - if (change.list) entry.list = change.list.map(savedRow) + const now = Date.now() + const entry = { ...(byAgy[key] || {}), at: now } + if (change.list) { + entry.list = change.list.map(savedRow) + entry.fetchedAt = now + } if (change.offered) entry.offered = change.offered + if (change.tier !== undefined) { + if (change.tier) entry.tier = change.tier + else delete entry.tier + } if (!Array.isArray(entry.list)) return byAgy[key] = entry const temp = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp` fs.writeFileSync(temp, JSON.stringify({ version: 1, byAgy }) + "\n", { mode: 0o600 }) fs.renameSync(temp, file) + lastGoodCatalogs = { file, byAgy } }) } catch {} } @@ -1425,10 +1477,10 @@ function anotherAccountLists(agyPath, model) { const base = model.replace(/-\d{8}$/, "") const bare = base.replace(/-(?:minimal|low|medium|high|xhigh|max)$/i, "") try { - const data = JSON.parse(fs.readFileSync(modelCatalogFile(), "utf8")) - if (data?.version !== 1 || !data.byAgy || typeof data.byAgy !== "object") return false + const byAgy = catalogsOrLastGood() + if (!byAgy) return false const mine = catalogKey(agyPath) - for (const [key, entry] of Object.entries(data.byAgy)) { + for (const [key, entry] of Object.entries(byAgy)) { if (key === mine || (key !== agyPath && !key.startsWith(agyPath + "#"))) continue // an account removed since leaves its entry behind, not its home const id = key === agyPath ? "" : key.slice(agyPath.length + 1) @@ -1452,14 +1504,19 @@ function anotherAccountLists(agyPath, model) { function startingModelCatalog(agyPath) { const saved = readSavedCatalog(agyPath) if (!saved) return fallbackModelCatalog(agyPath, { replace: true }) - // What agy acp offered last time, until a session of this run says. + // What agy acp offered last time, and the tier it named, until a session + // of this run says: believed as it was, as the list is. if (saved.offered && !ms().acpOfferedModels) { ms().acpOfferedModels = new Map(saved.offered.map(({ id, name }) => [id, name])) ms().acpOfferedKey = [...ms().acpOfferedModels.keys()].sort().join("\n") - ms().offeredStale = true + ms().offeredStale = false } + if (saved.tier && !ms().acpTier) ms().acpTier = saved.tier // The usage reader names ids on its windows from the catalog being served. storeCatalogRows(saved.list) + // fetchedAt stays 0 here: a list this run hasn't heard from agy doesn't + // fail a request fast (liveList), as the account may have changed plan + // since; the file keeps when it was listed. return { agyPath, list: saved.list, catalog: null, offeredKey: null, isFallback: false, fetchedAt: 0, lastAttemptAt: null } } @@ -1497,13 +1554,12 @@ function storeListedCatalog(agyPath, list, lastAttemptAt) { } // catalogWarming is the background work that can still change what models() -// lists (the listing, then the session probe it starts), or null when there -// is none. Hosts that read the list once (OpenCode 2.x's adapter) read it -// again when this ends. +// lists (a listing, or an ask of agy acp at a sign-in or refresh), or null +// when there is none. Hosts that read the list once (OpenCode 2.x's +// adapter) read it again when this ends. function catalogWarming() { // every account's: the host reading the list is in no account's scope - // A listing that lands starts the probe, so look again after each wait. - const pending = () => [...modelStates.values()].flatMap(state => [state.modelCatalogRefreshPromise, state.offeredProbePromise]).find(Boolean) + const pending = () => [...modelStates.values()].flatMap(state => [state.modelCatalogRefreshPromise, state.offerAskPromise]).find(Boolean) if (!pending()) return null return (async () => { for (let promise; (promise = pending());) await promise.catch(() => {}) @@ -1511,55 +1567,47 @@ function catalogWarming() { })() } -// Magpie gives models() about two seconds, while `agy models` can take longer. -// Serve the last catalog (static until the first success), refresh it in the -// background at most once at a time, and wait for that refresh only briefly. -// probeOffered: the caller is listing models (provider.models), not routing a -// request that is about to open a session of its own. -async function loadModelCatalog(agyPath, { probeOffered = false } = {}) { +// loadModelCatalog serves the account's last list as it is: it lists with +// agy only when there is none yet (the static fallback serves meanwhile, +// tried again at most every MODEL_CATALOG_RETRY_MS), or when the user asked +// for it (refresh), and then asks agy acp what it offers too. A list is +// never listed again for its age: an idle account sends Google nothing. +// Magpie gives models() a few seconds, while `agy models` can take longer, +// so the listing runs in the background and is waited for only briefly. +async function loadModelCatalog(agyPath, { refresh = false } = {}) { useAgyPath(agyPath) - if (probeOffered) ms().wantOfferedProbe = true const current = ms().cachedModelCatalog if (!agyPath) return catalogOf(current) const now = Date.now() - if (!current.isFallback && now - current.fetchedAt < MODEL_CATALOG_TTL_MS) { - // A signed-in agy whose offer is unknown yet is asked in the background. - if (probeOffered) probeOfferedOnce(agyPath) - return catalogOf(current) - } + if (!current.isFallback && !refresh) return catalogOf(current) + // an account Google turned away isn't asked again on its own: a sign-in + // or the user's refresh asks, and the list magpie had stays meanwhile + if (!refresh && refusalOf()) return catalogOf(current) if (!ms().modelCatalogRefreshPromise && - (current.lastAttemptAt === null || now - current.lastAttemptAt >= MODEL_CATALOG_RETRY_MS)) { + (refresh || current.lastAttemptAt === null || now - current.lastAttemptAt >= MODEL_CATALOG_RETRY_MS)) { current.lastAttemptAt = now - const refresh = listAgyModels(agyPath).then((list) => { + // A listing runs only on a refresh or with no list yet, so where + // `agy models` can't list for the account (the app's gateway, an + // eligibility refusal agy acp serves anyway) agy acp is asked in its + // place. The offer apart from that is asked on a refresh only. + const asked = {} + const listing = listAgyModels(agyPath, { ask: true, asked }).then(async (list) => { if (list?.length && ms().cachedModelCatalog === current) { storeListedCatalog(agyPath, list, current.lastAttemptAt) - // `agy models` answered, so agy is signed in: ask what agy acp - // offers now, while the host still waits for its first list. - if (ms().wantOfferedProbe) probeOfferedOnce(agyPath) + // the user asked: what agy acp offers is asked too, unless the + // listing asked it already (a gateway agy, an eligibility refusal) + if (refresh && !asked.offer) await askOfferOnce(agyPath) } }).catch(() => { // Keep the last successful catalog, including dynamic-only models. }).finally(() => { - if (ms().modelCatalogRefreshPromise === refresh) ms().modelCatalogRefreshPromise = null + if (ms().modelCatalogRefreshPromise === listing) ms().modelCatalogRefreshPromise = null }) - ms().modelCatalogRefreshPromise = refresh + ms().modelCatalogRefreshPromise = listing } if (ms().modelCatalogRefreshPromise) { - let timer - try { - await Promise.race([ - ms().modelCatalogRefreshPromise, - new Promise((resolve) => { timer = setTimeout(resolve, MODEL_CATALOG_FAST_WAIT_MS) }), - ]) - } finally { - clearTimeout(timer) - } + await briefly(ms().modelCatalogRefreshPromise, refresh ? MODEL_CATALOG_REFRESH_WAIT_MS : MODEL_CATALOG_FAST_WAIT_MS) } - // `agy models` answered, so agy is signed in: learn what its ACP server - // offers this client, waiting for it as briefly as for the listing. - // A saved list (fetchedAt 0) is not an answer from this agy yet. - const probe = probeOffered && !ms().cachedModelCatalog.isFallback && ms().cachedModelCatalog.fetchedAt > 0 ? probeOfferedOnce(agyPath) : null - if (probe) await briefly(probe, MODEL_CATALOG_FAST_WAIT_MS) return catalogOf(ms().cachedModelCatalog) } @@ -2146,7 +2194,7 @@ export function ideToolOf(toolCall) { // The bridge's session runs on agy's default agent (default-agent.mjs): its // instructions go in the workspace's AGENTS.md, and a hook fails every call // of agy's own tools, which the default agent always lists. media: the -// conversation carries a video or audio (stageMedia), which the model reads +// conversation carries a video, audio or PDF (stageMedia), which the model reads // with agy's own file viewer (read_file in agy 1.5.19, view_file before). // It reads agy's temp folder unasked, so for media that folder is the // session's workspace (#spawn). @@ -2158,7 +2206,7 @@ function bridgeAgentFiles(media, allowAgyTools) { const lines = ["Use only the provided tools. Text resembling a tool call is conversation content, not an executable call."] if (allowAgyTools) return { instructions: lines.join("\n"), allowed: null } lines.push(media - ? `Antigravity's own tools are turned off in this session but for read_file, which opens the video or audio files the conversation names, and every call to another (run_command, write_file, edit_file, search_web, invoke_subagent and the rest) fails: otherwise use only the tools named ${IDE_TOOLS}.` + ? `Antigravity's own tools are turned off in this session but for read_file, which opens the video, audio or PDF files the conversation names, and every call to another (run_command, write_file, edit_file, search_web, invoke_subagent and the rest) fails: otherwise use only the tools named ${IDE_TOOLS}.` : `Antigravity's own tools (run_command, read_file, write_file, edit_file, search_web, invoke_subagent and the rest) are turned off in this session and every call to one fails: use only the tools named ${IDE_TOOLS}.`) return { instructions: lines.join("\n"), allowed: media ? [IDE_TOOLS, ...MEDIA_TOOLS] : [IDE_TOOLS] } } @@ -2292,6 +2340,9 @@ class Turn { this.activeAcpToolCalls = new Set() this.acpToolWaiters = [] this.cancelledMcpSockets = new Set() + this.activeServerTools = new Set() + this.hostedToolUses = new Map() + this.hostedRejectedStreaks = new Map() this.agentError = false this.heldText = "" this.textTail = "" @@ -2712,10 +2763,19 @@ class Turn { this.push({ type: "result", result }) } + abortServerTools() { + for (const active of [...this.activeServerTools]) { + this.activeServerTools.delete(active) + try { active.controller.abort(new Error("agy bridge: turn closed")) } catch {} + try { active.socket?.destroy() } catch {} + } + } + fail(error) { if (this.done || this.finalized) return this.done = true clearTimeout(this.timer) + this.abortServerTools() this.notifyAcpTools() for (const waiter of this.lateWaiters.splice(0)) waiter.reject(error) this.push({ type: "error", error }) @@ -2892,6 +2952,9 @@ class Proc { this.unsentPrompt = null this.turn = null this.expectedMessages = null + // the histories of the conversations that opened as this one did and + // left their key to it (siblingsLeaving), as historyDigest has them + this.siblingHistories = [] this.toolsVersion = 1 this.listedVersion = 0 this.listWaiters = [] @@ -2912,6 +2975,8 @@ class Proc { this.model = opts.model this.selection = opts.selection this.tools = opts.tools ?? [] + this.hostedTools = opts.hostedTools instanceof Map ? opts.hostedTools : new Map() + this.hostedSearchActive = Boolean(opts.hostedSearchActive) this.toolsSignature = JSON.stringify(this.tools) this.instructions = opts.instructions || "" this.userId = opts.userId || "" @@ -2969,6 +3034,7 @@ class Proc { this.historyInvalid = false this.unsentPrompt = null this.expectedMessages = null + this.siblingHistories = [] this.omittedHistoryTokens = 0 this.lastCacheRatio = undefined this.pendingFlattenedTurn = undefined @@ -3197,7 +3263,12 @@ class Proc { // A resumed session reports the account default; always apply the selection. this.currentModel = session?.models?.currentModelId ?? null this.configOptions = Array.isArray(session?.configOptions) ? session.configOptions : [] - inAccount(this.home, () => noteOfferedModels(this.configOptions, session?.models)) + // what agy acp offers the account, and the tier it names, as the turn's + // own session says: kept for listings (models.json), so agy acp is + // never asked apart from a turn but at a sign-in or the user's refresh + const tier = session?._meta?.antigravity?.tier?.id + this.offeredHere = offeredModelsOf(this.configOptions, session?.models).map(model => model.id) + inAccount(this.home, () => noteOfferedModels(this.configOptions, session?.models, typeof tier === "string" && tier ? { tier } : {})) const configured = Date.now() if (this.model) await this.#setModel(this.model, this.selection, this.resumed) this.phases.set_model_ms = Date.now() - configured @@ -3221,6 +3292,14 @@ class Proc { try { let configured = false const target = this.configMethodUnsupported ? null : configModelSelection(this.configOptions, model, selection) + // a request let through while the offer was in doubt (recheckOffer, + // plugins#1804): this session says what agy acp offers now, and a + // model it still doesn't offer is turned away, as another signed-in + // account lists it + if (selection?.offered && this.offeredHere?.length && + !this.offeredHere.some(id => offeredFamily(id) === offeredFamily(model))) { + throw Object.assign(new Error("another signed-in agy account lists it"), { offerLacks: true }) + } if (target) { try { if (force || target.config.currentValue !== target.value) await this.#setConfig(target.config, target.value) @@ -3245,6 +3324,11 @@ class Proc { await this.conn.request("session/set_model", { sessionId: this.sessionId, modelId: model }, 30_000) } } catch (error) { + if (error.offerLacks) { + const wrapped = new Error(`agy bridge: model ${selection?.model || model} is unavailable to this agy account; ${error.message}`) + wrapped.statusCode = 400 + throw wrapped + } // Google turned the account away (#3501): agy's session offers no // model at all, so every model is "unknown". That is the account. const refused = await refusalNow(this.agyPath).catch(() => "") @@ -3320,7 +3404,9 @@ class Proc { } // Swap the client tool catalog in place; agy re-lists on tools/list_changed. - async updateTools(tools) { + async updateTools(tools, hostedTools = null, hostedSearchActive = null) { + if (hostedTools instanceof Map) this.hostedTools = hostedTools + if (typeof hostedSearchActive === "boolean") this.hostedSearchActive = hostedSearchActive const signature = JSON.stringify(tools) if (signature === this.toolsSignature) return this.tools = tools @@ -3479,6 +3565,12 @@ class Proc { if (this.historyInvalid) return false if (this.expectedMessages == null) return !this.turn && !this.hasSentFirstTurn if (sameHistory(this.expectedMessages, messages)) return true + // The history of a conversation that opened as this one did and left + // its key to it is that conversation's, not this one's masked another + // way: every tolerance below would take a reply that differs only by an + // id of a key's form (sess-abcdefgh, sess-qrstuvwx) for one key + // re-shaped, and go on in the other conversation's session (plugins#1757). + if (this.siblingHistories.length && this.siblingHistories.includes(historyDigest(messages))) return false // magpie's masking can mask a text the session already has differently // on a later request: the local model that missed it under load (the // rules masked it alone) reads it for a later one, and a value in an @@ -3515,6 +3607,10 @@ class Proc { // magpie's image-slim swaps an earlier image for its placeholder text; agy // has that image already, so the history it has is otherwise as it was. if (sameHistoryUpToImages(this.expectedMessages, messages)) return true + // Clients such as Kelivo store only the assistant's final text and omit + // server_tool_use / web_search_tool_result / web_fetch_tool_result blocks + // that this live session already produced; gated on the hosted_search switch. + if (this.hostedSearchActive && sameHistoryUpToServerTools(this.expectedMessages, messages)) return true // A client that compacts its own context (billion-context in DeepSeek // Harness) folds earlier messages into a summary the live session never // saw. agy still holds those messages whole, so the session holds as long @@ -3651,7 +3747,8 @@ class Proc { // here resumes at them (parkStep), never at the turn before if (!parkStep(this)) unpark(this.convKey) // agy hands Antigravity the prompt as a user's turn, where Codex's - // GPT-5 lines are turned away too (cloak.mjs, USER_TURNED_AWAY), and + // GPT-5 lines and WorkBuddy's first line are turned away too + // (cloak.mjs, USER_TURNED_AWAY), and // reads a command name anywhere in it as the user running that // command (cloak.mjs, defuseSlashCommands) promptParts = userTurnParts(promptParts, this.slashCommands) @@ -3768,9 +3865,11 @@ class Proc { // agy 1.5.10 leaves out the status agyRefusal reads the ban by if (core === DISABLED_CORE) return refusedError(ACCOUNT_DISABLED_REFUSED) if (core === VERIFY_CORE) { - // the link, when agy logged Google's error whole; the reply has none + // asked on this model call: the link when agy logged Google's error + // whole (the reply has none), and Google's words from its log const logged = await logTail(this.logPath, turn.logOffset) - return refusedError(verifyRefused(verifyLinkIn(`${turn.attemptDetail || ""}\n${logged}`))) + const google = agentErrorsIn(logged).at(-1) || turn.attemptDetail || "" + return refusedError(verifyRefused(verifyLinkIn(`${turn.attemptDetail || ""}\n${logged}`), { request: true, google })) } // A failed connection is in the reply's last attempt line, not the log's // executor error (#1136). @@ -3818,6 +3917,7 @@ class Proc { if (turn.cancelRequested || turn.done || turn.finalized) return false if (turn.hasPendingMcp() || this.dead) return false turn.cancelRequested = true + turn.abortServerTools() turn.detach() if (this.expectedMessages && partialContent.length) { this.expectedMessages.push({ role: "assistant", content: partialContent }) @@ -4008,11 +4108,20 @@ class Proc { args = restoreSlashCommands(args, this.slashCommands) const tool = this.tools.find((item) => item.name === name) if (!tool) throw new Error(`agy bridge: undeclared tool ${name}`) - const spilled = spilledOutput(this.agyDir, name, args) + const spilled = spilledOutput(this.agyDir, name, args, { + readTool: (this.tools.find((item) => /^(?:read|read_file|view|view_file)$/i.test(item.name)) ?? + this.tools.find((item) => /read|view/i.test(item.name)))?.name ?? "", + here: this.clientHere === true, + }) if (spilled) { socket.end(JSON.stringify({ result: spilled }) + "\n") return null } + const hosted = this.hostedTools?.get(name) + if (hosted) { + this.#runHostedToolCall(turn, hosted, args, socket) + return null + } // agy consumes its internal toolSummary instead of forwarding it to MCP, so // a call it makes reaches us without one. The client (an outer agy) declared // the field required on the tool, so put a value back before handing the @@ -4065,6 +4174,74 @@ class Proc { return call } + #runHostedToolCall(turn, hosted, args, socket) { + turn.flushText() + turn.saidSinceCall = turn.thoughtSinceCall = turn.invalidOutput = turn.deniedSinceCall = turn.emptyAsked = false + turn.arm() + const controller = new AbortController() + const active = { controller, socket } + turn.activeServerTools.add(active) + let responded = false + const finish = (payload) => { + if (responded) return + responded = true + turn.activeServerTools.delete(active) + if (socket.writable && !socket.destroyed) { + try { socket.end(JSON.stringify(payload) + "\n") } catch {} + } else { + try { socket.destroy() } catch {} + } + } + socket.once("close", () => { + if (!responded) { + turn.activeServerTools.delete(active) + try { controller.abort(new Error("agy bridge: MCP socket closed during hosted search")) } catch {} + } + }) + const usedCount = turn.hostedToolUses.get(hosted.name) || 0 + const rejectedStreak = turn.hostedRejectedStreaks.get(hosted.name) || 0 + const canReadSpilled = clientCanReadSpilledOutput(this.tools, this.hostedTools) + executeHostedTool(hosted, args, { + usedCount, + rejectedStreak, + canReadSpilled, + userAgent: `agy-cli/${CLIENT_INFO.version}`, + onReserve: (delta) => { + if (delta > 0) turn.hostedToolUses.set(hosted.name, (turn.hostedToolUses.get(hosted.name) || 0) + delta) + }, + signal: controller.signal, + emit: (event) => { + if (turn.done || turn.finalized || turn.cancelRequested || controller.signal.aborted) return + turn.arm() + turn.push(event) + }, + }).then(({ usedDelta, allMaxUsesRejected, mcpResult }) => { + if (allMaxUsesRejected) { + turn.hostedRejectedStreaks.set(hosted.name, (turn.hostedRejectedStreaks.get(hosted.name) || 0) + 1) + } else if (usedDelta > 0) { + turn.hostedRejectedStreaks.set(hosted.name, 0) + } + if (turn.done || turn.finalized || turn.cancelRequested || controller.signal.aborted) { + finish({ error: { code: -32603, message: "agy bridge: turn cancelled during hosted search" } }) + return + } + turn.arm() + finish({ result: mcpResult }) + }, (error) => { + if (turn.done || turn.finalized || turn.cancelRequested || controller.signal.aborted) { + finish({ error: { code: -32603, message: "agy bridge: turn cancelled during hosted search" } }) + return + } + turn.arm() + finish({ + result: { + content: [{ type: "text", text: `Hosted ${hosted.kind} failed: ${error?.message || String(error)}` }], + isError: true, + }, + }) + }) + } + // Answer agy before its MCP deadline; the real result follows on a repeat call. async #deferCall(turn, call) { if (call.mcpResponded || call.result || turn.done || turn.finalized) return @@ -4236,6 +4413,7 @@ class Proc { if (turn.finalized) return turn.finalized = true const keepStep = this.keepsParkedStep(turn) + turn.abortServerTools() turn.notifyAcpTools() for (const socket of turn.cancelledMcpSockets) { try { socket.destroy() } catch {} @@ -5450,6 +5628,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo let why = forceNew && opts.dropReason ? opts.dropReason : "no_live" let historyDiff let key = convKey + let siblings = null if (existing && !existing.dead && existing.turn && isFreshConversation && !forceNew && !opts.hasToolResults && !existing.turn.cancelRequested && existing.turn.model !== opts.model) { // A new conversation that opens as a running one did (one system prompt and @@ -5496,7 +5675,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo existing.openingText = openingTextOf(first) || existing.openingText existing.openingImages = openingImagesOf(first) } - await existing.updateTools(opts.tools) + await existing.updateTools(opts.tools, opts.hostedTools, opts.hostedSearchActive) // agy never listed the tools this request declares (an agy started // with none whose MCP server never connected): a new one may. if (existing.toolsListed()) return { proc: existing, history: matchedHistory } @@ -5524,11 +5703,12 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo if (!isFreshConversation && (why === "history" || (why === "forced" && opts.resumeStep)) && parkRebase(existing, null, opts.messages, opts.history, opts, convKey)) opts.rebase = true } + if (why === "fresh_after_first") siblings = siblingsLeaving(existing) if (!forceNew && launch && (statelessRequest(opts) ? statelessDonor(existing, launch, opts.userId || "", opts.sessionScope || "", opts.workDir) : why === "fresh_after_first" && sameOpeningDonor(existing, launch, opts))) { // the same stateless request again: its agy answers it in a new session - return await reuseStateless(existing, key, opts, why) + return await reuseStateless(existing, key, opts, why, siblings) } existing.retiring = true dropFromPool(existing) @@ -5570,6 +5750,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo throw error } pool.set(key, proc) + if (siblings) proc.siblingHistories = siblings // the next new conversation of this account and folder takes one ready warmSpare(agyPath, opts.workDir).catch(() => {}) // Why this request got a new agy session, so a cache that never hits can be @@ -5595,7 +5776,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo // boots its backend and takes seconds, a later one milliseconds. The // donor's conversation keeps no live session: a follow-up to it replays its // history, as after any lost session. -async function reuseStateless(donor, key, opts, why) { +async function reuseStateless(donor, key, opts, why, siblings = null) { const previousKey = donor.convKey dropFromPool(donor) // its session is closed, and resuming it elsewhere would share this agy's folder @@ -5608,6 +5789,7 @@ async function reuseStateless(donor, key, opts, why) { throw error } pool.set(key, donor) + if (siblings) donor.siblingHistories = siblings donor.sessionReason = why logSessionEvent(donor, why, { fresh: true, resumed: false, spare: false, parked: false, reused: true, @@ -5971,10 +6153,28 @@ function unwrapCallMcpArguments(args) { return args } +const parsedUserImages = new WeakMap() + function parseUserImage(block) { if (block?.type !== "image") return null - const mediaType = String(block.source?.media_type || "").toLowerCase() - return imageContent({ ...block, source: { ...block.source, media_type: mediaType === "image/jpg" ? "image/jpeg" : mediaType } }) + const source = block.source + const mediaType = String(source?.media_type || "").toLowerCase() + const data = source?.data + const previous = parsedUserImages.get(block) + if (previous && source?.type === "base64" && previous.data === data && previous.mediaType === mediaType) { + return { ...previous.image } + } + const image = imageContent({ ...block, source: { ...source, media_type: mediaType === "image/jpg" ? "image/jpeg" : mediaType } }) + parsedUserImages.set(block, { data, mediaType, image, sha256: null }) + return { ...image } +} + +function userImageDigest(block, data) { + const entry = parsedUserImages.get(block) + if (entry && entry.data === data) { + return (entry.sha256 ??= digest(data)) + } + return digest(data) } function parseUserDocumentText(block, inToolResult = false) { @@ -6302,6 +6502,103 @@ function sameToolUseIdentities(left, right) { return a != null && a === b } +const HOSTED_SERVER_BLOCK_TYPES = new Set([ + "server_tool_use", + "web_search_tool_result", + "web_fetch_tool_result", +]) + +function clientCanReadSpilledOutput(tools, hostedTools) { + if (!Array.isArray(tools)) return false + return tools.some((t) => { + if (!t || typeof t.name !== "string" || hostedTools?.has(t.name)) return false + const props = t.inputSchema?.properties + if (!props || typeof props !== "object") return false + if (/read|view/i.test(t.name)) { + return Object.entries(props).some(([k, p]) => /path|file/i.test(k) && p?.type === "string") + } + if (/bash|shell|command|exec|eval|python|terminal|powershell|repl|^sh$|^js$/i.test(t.name)) { + return Object.keys(props).some((k) => /^(?:command|commands|cmd|code|script|source)$/i.test(k)) + } + return false + }) +} + +function serverBlockIdentity(block) { + return `${block?.type || ""}:${renderServerAssistantBlock(block)}` +} + +// Accepts ONLY the case where the client dropped hosted server tool blocks that +// `expected` already produced. Any server block in `actual` that `expected` never +// saw at that message refuses the match so the bridge opens a fresh session and +// replays the history, search result included. +function alignHistoryWithDroppedServerTools(expected, actual) { + if (!Array.isArray(expected) || !Array.isArray(actual) || expected.length !== actual.length) { + return null + } + let droppedAny = false + const alignedExpected = [] + for (let i = 0; i < expected.length; i++) { + const expMsg = expected[i] + const actMsg = actual[i] + const expServer = expMsg?.role === "assistant" && Array.isArray(expMsg.content) + ? expMsg.content.filter((b) => HOSTED_SERVER_BLOCK_TYPES.has(b?.type)) + : [] + const actServer = actMsg?.role === "assistant" && Array.isArray(actMsg.content) + ? actMsg.content.filter((b) => HOSTED_SERVER_BLOCK_TYPES.has(b?.type)) + : [] + if (actServer.length > 0) { + let cursor = 0 + for (const ab of actServer) { + const sig = serverBlockIdentity(ab) + let found = -1 + for (let j = cursor; j < expServer.length; j++) { + if (serverBlockIdentity(expServer[j]) === sig) { + found = j + break + } + } + if (found < 0) return null + cursor = found + 1 + } + if (actServer.length === expServer.length) { + alignedExpected.push(expMsg) + continue + } + } + if (expServer.length === 0) { + alignedExpected.push(expMsg) + continue + } + droppedAny = true + if (actServer.length === 0) { + const kept = expMsg.content.filter((b) => !HOSTED_SERVER_BLOCK_TYPES.has(b?.type)) + alignedExpected.push({ ...expMsg, content: kept }) + } else { + const keptIds = actServer.map(serverBlockIdentity) + let k = 0 + const kept = expMsg.content.filter((b) => { + if (!HOSTED_SERVER_BLOCK_TYPES.has(b?.type)) return true + if (k < keptIds.length && serverBlockIdentity(b) === keptIds[k]) { + k++ + return true + } + return false + }) + alignedExpected.push({ ...expMsg, content: kept }) + } + } + return droppedAny ? alignedExpected : null +} + +function sameHistoryUpToServerTools(expected, actual) { + const alignedExpected = alignHistoryWithDroppedServerTools(expected, actual) + if (!alignedExpected) return false + if (sameHistory(alignedExpected, actual)) return true + if (sameHistoryUpToMasking(alignedExpected, actual)) return true + return sameHistoryUpToImages(alignedExpected, actual) +} + // Compare conversation content, not transport metadata or client-assigned IDs. // Keep argument values, result contents and internal whitespace significant. @@ -6368,8 +6665,9 @@ function instructionsIdentity(text) { // USER_CLOAK marks a session parked since its prompts went as cloakUser // says. One parked before keeps a user's turn with Codex's GPT-5 line as // written in agy's own copy, and every turn on it would be turned away, so -// it is not resumed: a new session gets the history as it goes now. -const USER_CLOAK = 1 +// it is not resumed: a new session gets the history as it goes now. 2 since +// WorkBuddy's first line goes reworded in a user's turn too (#1871). +const USER_CLOAK = 2 // A parked entry's instructionsInSession says where its instructions went. // A session agy opened with them appended keeps them in its own system // instruction, so every turn on it is turned away as before; it is resumed @@ -6451,7 +6749,7 @@ function openingImagesOf(message) { if (block?.type !== "image") continue try { const image = parseUserImage(block) - if (image) out.push(`${image.mimeType}:${digest(image.data)}`) + if (image) out.push(`${image.mimeType}:${userImageDigest(block, image.data)}`) } catch { const source = block.source || {} out.push(`invalid:${source.media_type || ""}:${digest(String(source.data || ""))}`) @@ -7073,15 +7371,15 @@ function historyBlock(block, ids) { let value if (typeof block === "string" || block.type === "text") { value = { type: "text", text: stripVolatileOpening(stripMagpiePlaceholderNotice(typeof block === "string" ? block : block.text || "")) } + } else if (isMedia(block)) { + value = { type: block.type, mediaType: block.source.media_type, sha256: digest(mediaData(block)) } } else if (block.type === "document") { value = { type: "text", text: parseUserDocumentText(block) } } else if (block.type === "search_result") { value = { type: "text", text: parseSearchResultText(block) } } else if (block.type === "image") { const image = parseUserImage(block) - value = { type: "image", mimeType: image.mimeType, sha256: digest(image.data) } - } else if (isMedia(block)) { - value = { type: block.type, mediaType: block.source.media_type, sha256: digest(mediaData(block)) } + value = { type: "image", mimeType: image.mimeType, sha256: userImageDigest(block, image.data) } } else if (block.type === "tool_use") { const ordinal = ids.size + 1 ids.set(block.id, ordinal) @@ -7169,6 +7467,17 @@ function historyKey(messages) { return stableJSON(historyRows(messages)) } +// The most histories of earlier same-opening conversations a session keeps. +const SIBLING_HISTORIES_MAX = 8 + +// What a new conversation that opens as `proc`'s did (fresh_after_first) +// keeps of it as it takes the key: the history it leaves, so that +// conversation's next turn is told apart from this one's (matchesHistory). +function siblingsLeaving(proc) { + const own = Array.isArray(proc?.expectedMessages) && proc.expectedMessages.length ? [historyDigest(proc.expectedMessages)] : [] + return [...own, ...(proc?.siblingHistories || [])].slice(0, SIBLING_HISTORIES_MAX) +} + // Assistant-prefill support: a trailing text-only assistant message is a // client-side prefill (chat/roleplay frontends, "continue"/"impersonate" // flows, bot frameworks). Keep the run in the tail so the session ledger @@ -7241,41 +7550,9 @@ function lastAssistantCalls(messages) { ? message.content.filter(block => block.type === "tool_use") : []) } -// agy cuts a tool result over its size short, saves the whole of it as -// <agy dir>/brain/<session>/.system_generated/steps/<step>/output.txt and -// has the model read that file. With magpie on a server (Docker) and the -// client on another machine, the client's Read of that path fails: the -// file is only where agy runs (Dani Ariyanto on Discord). So a read-type -// tool whose one path is such a file is answered here, from the file, and -// never reaches the client; null for any other call. Lines are numbered, -// from offset (a line number) for at most limit lines when the call says. -const SPILLED = /^brain[\\/][^\\/]+[\\/]\.system_generated[\\/]steps[\\/][^\\/]+[\\/]output\.txt$/ - -export function spilledOutput(agyDir, name, args) { - if (!agyDir || !/read|view/i.test(name) || !args || typeof args !== "object") return null - const paths = Object.values(args).filter((value) => typeof value === "string" && path.isAbsolute(value)) - if (paths.length !== 1 || !SPILLED.test(path.relative(agyDir, path.resolve(paths[0])))) return null - let text - try { - // a link out of agy's folder is not followed - const real = fs.realpathSync(paths[0]) - if (!SPILLED.test(path.relative(fs.realpathSync(agyDir), real))) return null - text = fs.readFileSync(real, "utf8") - } catch { - return null - } - const number = (key) => { - const value = Number(args[key]) - return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0 - } - const lines = text.split("\n") - if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop() - const from = Math.max(1, number("offset")) - const to = number("limit") ? Math.min(lines.length, from - 1 + number("limit")) : lines.length - const out = [] - for (let n = from; n <= to; n++) out.push(`${String(n).padStart(6)}\t${lines[n - 1]}`) - return { content: [{ type: "text", text: out.join("\n") }], isError: false } -} +// A read of a tool output agy cut short and saved in its own folder is +// answered from that file (spilled.mjs). +export { spilledOutput } // A bridge call's id, as #handleMcpCall makes it. const BRIDGE_CALL_ID = /^toolu_[0-9a-f]{24}$/ @@ -7693,14 +7970,25 @@ function sanitizeInputSchema(schema) { return out } -function normalizeTools(body) { - if (!Array.isArray(body.tools) || !body.tools.length) return [] +function normalizeToolCatalog(body, allowHosted = hostedSearchEnabled()) { + const hostedTools = new Map() + if (!Array.isArray(body.tools) || !body.tools.length) return { tools: [], hostedTools } const choice = body.tool_choice - if (choice === "none" || choice?.type === "none") return [] + if (choice === "none" || choice?.type === "none") return { tools: [], hostedTools } const selected = choice?.type === "tool" ? choice.name : null const seen = new Set() const tools = [] for (const tool of body.tools) { + const hosted = allowHosted ? buildHostedTool(tool) : null + if (hosted) { + const name = hosted.mcpTool.name + if (seen.has(name)) throw new UnsupportedContent(`duplicate tool ${name}`) + seen.add(name) + if (selected && name !== selected) continue + tools.push(hosted.mcpTool) + hostedTools.set(name, hosted.config) + continue + } if (!tool || typeof tool.name !== "string" || !tool.name) { throw new UnsupportedContent("a tool without a valid name") } @@ -7729,7 +8017,11 @@ function normalizeTools(body) { }) } if (selected && !tools.length) throw new UnsupportedContent(`tool_choice names undeclared tool ${selected}`) - return tools + return { tools, hostedTools } +} + +function normalizeTools(body) { + return normalizeToolCatalog(body).tools } function blockText(block) { @@ -7742,16 +8034,16 @@ function blockText(block) { if (block.type === "tool_reference" && typeof block.tool_name === "string") { return `Loaded tool: ${block.tool_name}` } + if (isMedia(block)) { + mediaData(block) + return `[${isPdf(block) ? "PDF" : block.type}]` + } if (block.type === "document") return parseUserDocumentText(block) if (block.type === "search_result") return parseSearchResultText(block) if (block.type === "image") { parseUserImage(block) return "[image]" } - if (isMedia(block)) { - mediaData(block) - return `[${block.type}]` - } if (block.type === "tool_result") { const inner = Array.isArray(block.content) ? block.content.map((part) => { @@ -7776,15 +8068,24 @@ function messageText(message) { // same shape. agy drops or refuses every way ACP has to attach one (an // audio block, a resource or resource_link, @path); only its own view_file // hands Gemini the media itself, so stageMedia leaves it in a file to read. +// A PDF the user attached (a base64 document) goes the same way: agy's +// file reader hands a PDF to the model as it is, as its own prompts say +// ("text and binary files (images, PDFs) alike"), where ACP carries only +// text and images (#1862). function isMedia(block) { - return block?.type === "video" || block?.type === "audio" + return block?.type === "video" || block?.type === "audio" || isPdf(block) +} + +function isPdf(block) { + return block?.type === "document" && block.source?.type === "base64" && + String(block.source.media_type || "").toLowerCase().split(";")[0].trim() === "application/pdf" } function hasMedia(message) { return Array.isArray(message.content) && message.content.some(isMedia) } -// of agy's models, only Gemini takes a video or audio +// of agy's models, only Gemini takes a video, audio or PDF function takesMedia(modelId) { return modelId.startsWith("gemini-") } @@ -7797,7 +8098,7 @@ function mediaData(block) { return source.data } -// stageMedia is the message with each video or audio written to +// stageMedia is the message with each video, audio or PDF written to // dir/attachments, named by its sha256 so a history that sends it every turn // writes it once, and a note to read it in its place. Synchronous: an await // before the turn starts would leave the process idle, to be evicted. @@ -7811,7 +8112,7 @@ function stagedMedia(block, dir) { const bytes = Buffer.from(mediaData(block), "base64") const type = String(block.source.media_type || "").toLowerCase().split(";")[0].trim() const sub = /^(?:video|audio)\/(?:x-)?([a-z0-9]{1,16})$/.exec(type)?.[1] - const ext = type === "audio/mpeg" ? "mp3" : sub === "quicktime" ? "mov" : sub || (block.type === "audio" ? "mp3" : "mp4") + const ext = block.type === "document" ? "pdf" : type === "audio/mpeg" ? "mp3" : sub === "quicktime" ? "mov" : sub || (block.type === "audio" ? "mp3" : "mp4") const file = path.join(dir, "attachments", `${digest(bytes)}.${ext}`) if (!fs.existsSync(file)) { // whole or not at all: one cut short by a failed write would pass for it @@ -7820,7 +8121,9 @@ function stagedMedia(block, dir) { fs.writeFileSync(part, bytes) fs.renameSync(part, file) } - return { type: "text", text: `[The user attached ${block.type === "video" ? "a video" : "an audio file"}: ${file}. Read it with your file reading tool before answering.]` } + const title = block.type === "document" && typeof block.title === "string" && block.title.trim() ? ` (${block.title.trim()})` : "" + const what = block.type === "video" ? "a video" : block.type === "audio" ? "an audio file" : "a PDF" + title + return { type: "text", text: `[The user attached ${what}: ${file}. Read it with your file reading tool before answering.]` } } function imageContent(block) { @@ -9224,6 +9527,7 @@ function validateBody(body) { if (block?.type === "tool_result") toolResult(block) else if (block?.type === "image") parseUserImage(block) else if (block?.type === "text" || typeof block === "string") continue + else if (isMedia(block)) mediaData(block) else if (block?.type === "document") parseUserDocumentText(block) else if (block?.type === "search_result") parseSearchResultText(block) else blockText(block) @@ -9787,7 +10091,7 @@ function responseOutputEstimate(content) { output += tokens } else if (block.type === "text") { output += estimateTextTokens(block.text) - } else if (block.type === "tool_use") { + } else if (block.type === "tool_use" || block.type === "server_tool_use") { output += estimateTextTokens(JSON.stringify(block)) } } @@ -10017,6 +10321,18 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist let pingTimer = null let finished = false let abortHandler = null + let serverSearchRequests = 0 + let serverFetchRequests = 0 + const withServerUsage = (usage) => { + if (!serverSearchRequests && !serverFetchRequests) return usage + return { + ...usage, + server_tool_use: { + ...(serverSearchRequests ? { web_search_requests: serverSearchRequests } : {}), + ...(serverFetchRequests ? { web_fetch_requests: serverFetchRequests } : {}), + }, + } + } // What this response has produced so far, for sizing a late prompt's input. const bindStep = (bound) => { currentStep = bound @@ -10154,6 +10470,41 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist if (forwardThinking) emitDelta("thinking", event.text) continue } + if (event.type === "server_tool_use") { + closeBlock() + const input = event.input ?? {} + send("content_block_start", { + type: "content_block_start", + index: blockIndex, + content_block: { type: "server_tool_use", id: event.id, name: event.name, input: {} }, + }) + send("content_block_delta", { + type: "content_block_delta", + index: blockIndex, + delta: { type: "input_json_delta", partial_json: JSON.stringify(input) }, + }) + send("content_block_stop", { type: "content_block_stop", index: blockIndex }) + blockIndex++ + responseContent.push({ type: "server_tool_use", id: event.id, name: event.name, input }) + continue + } + if (event.type === "server_tool_result") { + closeBlock() + const resultType = event.resultType || "web_search_tool_result" + send("content_block_start", { + type: "content_block_start", + index: blockIndex, + content_block: { type: resultType, tool_use_id: event.id, content: event.content }, + }) + send("content_block_stop", { type: "content_block_stop", index: blockIndex }) + blockIndex++ + responseContent.push({ type: resultType, tool_use_id: event.id, content: event.content }) + if (event.counted) { + if (event.kind === "web_fetch") serverFetchRequests++ + else serverSearchRequests++ + } + continue + } if (event.type === "tool") { emitToolUse(event.call) // Calls agy issued together leave in the same response. Separate MCP @@ -10181,7 +10532,7 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist } const usage = await settleUsage(currentProc, currentTurn, currentStep, responseContent) if (finished) return - stopMessage("tool_use", usage, false, currentStep.usageKind === "agy_model_call") + stopMessage("tool_use", withServerUsage(usage), false, currentStep.usageKind === "agy_model_call") currentProc.recordAssistantResponse(currentTurn, responseContent) if (currentToolResultStep && emittedCalls.length > 0 && currentProc.turn === currentTurn && !currentProc.dead && !currentProc.stopping && !currentProc.retiring && @@ -10206,7 +10557,7 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist currentTurn.rawUsage = event.result.usage ?? currentTurn.rawUsage const usage = await settleUsage(currentProc, currentTurn, currentStep, responseContent, event.result) if (finished) return - stopMessage(STOP_REASONS[event.result.stopReason] || "end_turn", usage, true, event.result.stopReason !== "cancelled") + stopMessage(STOP_REASONS[event.result.stopReason] || "end_turn", withServerUsage(usage), true, event.result.stopReason !== "cancelled") currentProc.recordAssistantResponse(currentTurn, responseContent) currentProc.finalizeTurn(currentTurn) detach() @@ -10386,7 +10737,7 @@ async function jsonResponseFromStream(stream, fallbackModel, fallbackId) { const current = blocks.get(payload.index) if (!current) return blocks.delete(payload.index) - if (current.type === "tool_use" && current._json) { + if ((current.type === "tool_use" || current.type === "server_tool_use") && current._json) { try { current.input = JSON.parse(current._json) } catch {} } delete current._json @@ -10515,6 +10866,27 @@ function bufferedAnthropicResponse(body, { msgId, model, content, stopReason, us }) send("content_block_stop", { type: "content_block_stop", index }) index++ + } else if (block.type === "server_tool_use") { + send("content_block_start", { + type: "content_block_start", + index, + content_block: { type: "server_tool_use", id: block.id, name: block.name, input: {} }, + }) + send("content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "input_json_delta", partial_json: JSON.stringify(block.input ?? {}) }, + }) + send("content_block_stop", { type: "content_block_stop", index }) + index++ + } else if (block.type === "web_search_tool_result" || block.type === "web_fetch_tool_result") { + send("content_block_start", { + type: "content_block_start", + index, + content_block: { type: block.type, tool_use_id: block.tool_use_id, content: block.content }, + }) + send("content_block_stop", { type: "content_block_stop", index }) + index++ } } send("message_delta", { @@ -10555,6 +10927,9 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a let flattened = proc.pendingFlattenedTurn proc.pendingFlattenedTurn = null const isFirstTurn = !proc.hasSentFirstTurn + // the client's folder is on this machine: it can open agy's saved outputs + // itself (spilledOutput) + proc.clientHere = !!(callerWorkDir && workDirectory(callerWorkDir)) proc.keepWorkspace() // the prompt names each video or audio by its file; the session is still // matched by body.messages @@ -10853,7 +11228,12 @@ const toldNotHeld = new Set() function readUsageOf(home, email = "", printOnly = false) { const key = home ?? "" let read = usageReaders.get(key) - if (!read) usageReaders.set(key, (read = createUsageReader(findAgy, { geminiDir: usageGeminiDir }))) + if (!read) { + // agy acp, when the reading starts one (usage.mjs's servedQuota), is + // run as a turn's is: the same flags and client name + const acpArgs = async (agy) => [...await noDefaultCustomizationsArgs(agy), ...await telemetryArgs(agy)] + usageReaders.set(key, (read = createUsageReader(findAgy, { geminiDir: usageGeminiDir, acpArgs, clientInfo: CLIENT_INFO }))) + } return inAccount(home, async () => { if (email) { let stored = null @@ -10887,8 +11267,23 @@ function readUsageOf(home, email = "", printOnly = false) { }) } -export const AntigravityBridgePlugin = async () => { +export const AntigravityBridgePlugin = async (input = {}, pluginOptions = {}) => { keepAgyCurrent(findAgy) + const magpie = input?.magpie + // `config` runs once when Magpie loads the plugin (`searches: true` passes + // client hosted search tools through without making agy-cli Magpie's own + // searcher). Latch that load-time decision so `config` and request handling + // stay in lockstep until Magpie reloads; `AGY_BRIDGE_HOSTED_SEARCH=0` still + // forces it off. + let latchedHostedSearch = null + const computeHostedSearch = () => hostedSearchEnabled(process.env, { + magpieOption: magpie?.option?.(PROVIDER_ID, HOSTED_SEARCH_OPTION), + pluginOptions, + }) + const hostedSearchForRequest = () => { + if (hostedSearchForcedOff(process.env)) return false + return latchedHostedSearch !== null ? latchedHostedSearch : computeHostedSearch() + } return { // magpie's web search (Settings › Models › Web search), as the signed-in // account, through agy's own search_web; OpenCode ignores it @@ -10897,6 +11292,28 @@ export const AntigravityBridgePlugin = async () => { }, auth: { provider: PROVIDER_ID, + // Magpie's own switches in Providers › agy-cli and `magpie plugin options` + // (OpenCode ignores auth.options). + options: [ + { + key: HOSTED_SEARCH_OPTION, + label: "Batched web search", + description: "Let the model submit up to 10 search queries or 3 page fetches in one step (running at most 2 at a time), using Magpie's configured search service. Off: Magpie runs searches one by one. Restart Magpie after changing.", + default: false, + labels: { + zh: "批量联网搜索", + "zh-TW": "批次聯網搜尋", + ja: "一括Web検索", + de: "Gebündelte Websuche", + }, + descriptions: { + zh: "让模型一步内提交最多 10 个搜索词或 3 个网页抓取请求(每次最多同时执行 2 个),仍使用你在 Magpie 里配置的搜索服务。关闭时由 Magpie 逐条搜索。修改后需重启 Magpie。", + "zh-TW": "讓模型一步內提交最多 10 個搜尋詞或 3 個網頁擷取請求(每次最多同時執行 2 個),仍使用你在 Magpie 裡設定的搜尋服務。關閉時由 Magpie 逐條搜尋。修改後需重啟 Magpie。", + ja: "1ステップで最大10件の検索または最大3件のページ取得をまとめて送れます(同時実行は最大2件)。Magpieに設定済みの検索サービスを使い、オフ時は1件ずつ検索します。変更後はMagpieを再起動してください。", + de: "Lässt das Modell in einem Schritt bis zu 10 Suchanfragen oder 3 Seitenabrufe einreichen (maximal 2 gleichzeitig) über Magpies eingerichteten Suchdienst. Aus: Magpie sucht einzeln. Nach dem Ändern Magpie neu starten.", + }, + }, + ], // Magpie's hook for the CLI a plugin runs through: a sign-in on a // machine without agy (magpie in Docker) installs it first, into the // plugin's own folder (install.mjs). OpenCode ignores it. @@ -11092,14 +11509,15 @@ export const AntigravityBridgePlugin = async () => { const missing = () => aliased || offerLacks() || (!(ms().acpOfferedModels && !ms().offeredStale) && liveList && !catalogHasModel(listed.routing ?? listed, requestedModel)) let missingHere = missing() + let rechecked = false // what agy acp offered may be short of what it offers now // (plugins#1804): a model `agy models` lists for this account - // has its offer asked again before the request is turned away. - // An offer that couldn't be read is unknown, and the request - // goes on by the listing. + // puts the offer in doubt, and the request goes on by the + // listing; its own session says what agy acp offers now. if (missingHere && !aliased && offerLacks() && catalogHasModel(routing, requestedModel) && anotherAccountLists(agy, requestedModel)) { - await recheckOffer(agy) + recheckOffer() + rechecked = true listed = catalogOf(ms().cachedModelCatalog) model = resolveAgyModel(listed, requestedModel, body, saidEffort) missingHere = missing() @@ -11110,9 +11528,9 @@ export const AntigravityBridgePlugin = async () => { // agy runs the requested model when its session offers it (configModelSelection), else the resolved one const media = body.messages.some(hasMedia) if (media && !(takesMedia(requestedModel) && takesMedia(model))) { - return jsonError(400, `agy bridge: video or audio input to ${requestedModel} is not supported. Choose a Gemini model`, undefined, { noRetry: true }) + return jsonError(400, `agy bridge: video, audio or PDF input to ${requestedModel} is not supported. Choose a Gemini model`, undefined, { noRetry: true }) } - const selection = { model: requestedModel, effort: requestedEffort(body, saidEffort) } + const selection = { model: requestedModel, effort: requestedEffort(body, saidEffort), ...(rechecked ? { offered: true } : {}) } // Claude Code's AgentSummary in short notes (opt-in, plugins#1701): // answered by a one-shot, tool-free agy on the resolved model, // before anything reads the worker's history or tool results @@ -11152,7 +11570,21 @@ export const AntigravityBridgePlugin = async () => { const instructions = sessionInstructions(body, callerWorkDir) try { - const tools = normalizeTools(body) + const hostedSearchActive = hostedSearchForRequest() + // When hosted_search is on and a user manually selects agy-cli/<model> + // as Magpie's searcher, Magpie rewrites User-Agent to magpie/<ver> + // (gateway.go userAgentFor) and forwards x-magpie-caller-agent: agy-cli + // on the loopback MCP hop; refuse immediately before recursing. + const callerAgent = (requestHeader(fetchInput, init, "x-magpie-caller-agent") || "").trim().toLowerCase() + if (hostedSearchActive && callerAgent === PROVIDER_ID) { + return jsonError( + 400, + "agy-cli cannot act as magpie's model searcher while hosted_search is enabled; select another searcher or a search API in Settings › Models › Web search", + undefined, + { noRetry: true }, + ) + } + const { tools, hostedTools } = normalizeToolCatalog(body, hostedSearchActive) for (const message of body.messages) { if (message.role !== "assistant" || !Array.isArray(message.content)) continue for (const block of message.content) { @@ -11171,7 +11603,7 @@ export const AntigravityBridgePlugin = async () => { logBridgeEvent(null, null, "layout_flip", "layout_canonicalized", { reqId, convKey, layout, nonstream: body.stream === false }) } - const acquireOpts = { model, selection, tools, workDir, instructions, history: trailing.history, + const acquireOpts = { model, selection, tools, hostedTools, hostedSearchActive, workDir, instructions, history: trailing.history, messages: body.messages, layout, nonstream: body.stream === false, reqId, convKey, legacyConvKey: legacyConvKey !== convKey ? legacyConvKey : "", hasToolResults: resultBlocks.length > 0, userId: body.metadata?.user_id || "", sessionScope, @@ -11364,7 +11796,7 @@ export const AntigravityBridgePlugin = async () => { if (!proc.dead && !turn.done) { // A tool catalog that lost or changed tools applies to the // rest of this turn; a model change applies from the next prompt. - await proc.updateTools(tools) + await proc.updateTools(tools, hostedTools) const delivered = proc.continueWith(results) if (delivered > 0) { proc.recordToolResults(turn, body.messages) @@ -11462,7 +11894,14 @@ export const AntigravityBridgePlugin = async () => { config: async (cfg) => { cfg.provider ??= {} const was = cfg.provider[PROVIDER_ID] ?? {} - cfg.provider[PROVIDER_ID] = { npm: NPM_ANTHROPIC, ...was, name: was.name || PROVIDER_NAME } + const searches = computeHostedSearch() + latchedHostedSearch = searches + cfg.provider[PROVIDER_ID] = { + npm: NPM_ANTHROPIC, + ...(searches ? { searches: true } : {}), + ...was, + name: was.name || PROVIDER_NAME, + } }, provider: { id: PROVIDER_ID, @@ -11477,8 +11916,9 @@ export const AntigravityBridgePlugin = async () => { if (own.refuse) throw new Error(own.refuse) return inAccount(own.home, async () => { const agy = findAgy() - // Never force a refresh here: Magpie times models() out after about two seconds. - const catalog = await loadModelCatalog(agy, { probeOffered: true }) + // The account's last list, as it is: agy is asked only when there + // is none, or when the user refreshes the list (ctx.refresh). + const catalog = await loadModelCatalog(agy, { refresh: ctx?.refresh === true }) // Google turned the account away (#3501): agy lists nothing, and a // fallback list would read as models this account has. magpie // keeps the list it had and shows why. @@ -11490,12 +11930,10 @@ export const AntigravityBridgePlugin = async () => { // asked what it offers. magpie keeps the list it had and the // user's picks with it; a cold host's short list dropped every // other pick (Archivemylife on X: the picks didn't stick). - // So is an offer from before (saved by an earlier run, past its - // hour, or put in doubt by a session's update) while agy acp is - // asked again: a host restarted froze a short saved offer into - // magpie's list though the probe had the full one seconds later - // (plugins#1804). - if (ms().cachedModelCatalog.isFallback || ((!ms().acpOfferedModels || ms().offeredStale) && (ms().modelCatalogRefreshPromise || ms().offeredProbePromise))) { + // So is an offer in doubt while agy acp is being asked (a refresh + // still running): a short offer frozen into magpie's list hid the + // full one agy acp gave seconds later (plugins#1804). + if (ms().cachedModelCatalog.isFallback || ((!ms().acpOfferedModels || ms().offeredStale) && (ms().modelCatalogRefreshPromise || ms().offerAskPromise))) { out[Symbol.for("magpie.fellBack")] = true } for (const model of catalog.models) { @@ -11508,7 +11946,7 @@ export const AntigravityBridgePlugin = async () => { limit: modelLimits(model.id), api: { id: model.id, url: "agy://local", npm: NPM_ANTHROPIC }, capabilities: { - ...(imageModel ? { attachment: true, input: { text: true, image: true, ...(mediaModel ? { video: true, audio: true } : {}) }, output: { text: true } } : {}), + ...(imageModel ? { attachment: true, input: { text: true, image: true, ...(mediaModel ? { video: true, audio: true, pdf: true } : {}) }, output: { text: true } } : {}), ...(model.variants ? { reasoning: true } : {}), }, ...(model.variants ? { @@ -11560,7 +11998,7 @@ function classifyAgyFailure(detail) { return { status: 403, message: ACCOUNT_DISABLED_REFUSED, noRetry: true } } if (hasCore(VERIFY_CORE) || /\bverification required\b/i.test(text)) { - return { status: 403, message: verifyRefused(verifyLinkIn(text)), noRetry: true } + return { status: 403, message: verifyRefused(verifyLinkIn(text), { request: !verifyAskedAtSignIn(text) }), noRetry: true } } const refused = agyRefusal(text) if (refused) { diff --git a/model-ids.mjs b/model-ids.mjs index 2976fc3..01ca371 100644 --- a/model-ids.mjs +++ b/model-ids.mjs @@ -15,9 +15,21 @@ import { currentHome } from "./account.mjs" const states = new Map() +// Orchestrator is a planner the bridge doesn't serve (index.mjs's +// orchestratorRefusal): agy lists it, and its usage group names it beside +// the Gemini models, but no window is made for it. A window of a model the +// provider never lists is one magpie can't tell the account's picks from +// (#1891: with the pools' models unpicked, Orchestrator (Argon) was the one +// window left of the card, and the menu bar showed it alone). +export function isOrchestrator(model) { + const id = typeof model === "string" ? model : model?.id ?? "" + const name = typeof model === "string" ? "" : model?.name ?? "" + return /^gemini-[a-z0-9.]*-?orchestrator/i.test(id) || /^Orchestrator\b/i.test(name) +} + export function storeCatalogRows(list) { const key = currentHome() ?? "" - const rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id) : null + const rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id && !isOrchestrator(model)) : null if (!rows) { states.delete(key) return diff --git a/package.json b/package.json index ae76255..ca152be 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.186", + "version": "0.1.199", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", @@ -18,6 +18,7 @@ "gateway-free.mjs", "image.mjs", "documents.mjs", + "spilled.mjs", "opencode.mjs", "opencode2.mjs", "platform.mjs", @@ -37,7 +38,8 @@ "NOTICE.md", "re2-pattern.mjs", "array-items.mjs", - "cloak.mjs" + "cloak.mjs", + "hosted-search.mjs" ], "keywords": [ "magpie", diff --git a/spilled.mjs b/spilled.mjs new file mode 100644 index 0000000..998a32e --- /dev/null +++ b/spilled.mjs @@ -0,0 +1,437 @@ +// agy cuts a tool result over its size short, saves the whole of it as +// <agy dir>/brain/<session>/.system_generated/steps/<step>/output.txt and +// has the model read that file. With magpie on a server (Docker, or a Linux +// box with the client on a Mac) the file is only where agy runs, so a +// client tool that opens it fails with not found (Dani Ariyanto on +// Discord, plugins#1848). spilledOutput answers such a call here, from the +// file, in every form a client reads with: +// - a read tool's path, with offset and limit (Claude Code), view_range +// (the text editor tool's view), or a selector after the path, as Oh My +// Pi's read takes it: output.txt:1-100, :raw:1-100, :-60, :5+10, :40-, +// :1-12,-15, :L5..L9; +// - a shell command that only reads it: cat, head, tail or sed -n on it, +// each alone or piped into head, tail or sed -n (bash, Codex's command +// array), Get-Content or type (PowerShell, cmd); +// - code that only reads it: Python's Path(...).read_text() or +// open(...).read(), JavaScript's readFileSync(...) or Bun.file(...).text() +// (Oh My Pi's eval). +// Any other call that names the file (grep on it, a script that works on +// it) can't be answered here: unless the client is known to be on this +// machine, where it can open the file itself, it is told where the file +// is and the forms above. null leaves the call to the client. +import fs from "node:fs" +import path from "node:path" + +const SPILLED = /^brain[\\/][^\\/]+[\\/]\.system_generated[\\/]steps[\\/][^\\/]+[\\/]output\.txt$/ +// what follows the folder in a spilled file's path, as a command spells it +const SPILLED_TAIL = /^[\\/]brain[\\/][^\\/\s'"`;|&<>()]+[\\/]\.system_generated[\\/]steps[\\/][^\\/\s'"`;|&<>()]+[\\/]output\.txt/ +// a string that is a shell command or code to run, by its key +const COMMAND_KEY = /^(?:command|commands|cmd|code|script|source)$/i +const READ_TOOL = /read|view/i + +// The real path of a spilled output that file names, null for any other +// file and for a link out of agy's folder. +function spilledFile(agyDir, file) { + if (typeof file !== "string" || !file) return null + if (/^file:\/\//i.test(file)) { + try { file = decodeURIComponent(new URL(file).pathname) } catch { return null } + if (/^\/[A-Za-z]:[\\/]/.test(file)) file = file.slice(1) + } + if (!path.isAbsolute(file) || !SPILLED.test(path.relative(agyDir, path.resolve(file)))) return null + try { + const real = fs.realpathSync(file) + if (!SPILLED.test(path.relative(fs.realpathSync(agyDir), real))) return null + if (!fs.statSync(real).isFile()) return null + return real + } catch { + return null + } +} + +function fileLines(real) { + const text = fs.readFileSync(real, "utf8") + const lines = text.split("\n") + if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop() + return lines.map((line) => line.endsWith("\r") ? line.slice(0, -1) : line) +} + +// A path with Oh My Pi's selector after it: the path and the selector +// ("" for none); null when what follows output.txt isn't a selector. +function splitSelector(value) { + const at = value.lastIndexOf("output.txt") + if (at < 0) return null + const end = at + "output.txt".length + const rest = value.slice(end) + if (!rest) return { file: value, selector: "" } + if (!rest.startsWith(":")) return null + return { file: value.slice(0, end), selector: rest.slice(1) } +} + +const RANGE_CHUNK = /^L?(\d+)(?:(\.\.|[-+])L?(\d+)?)?$/i + +// Oh My Pi's selector (read-selector.ts, line-ranges.ts) as the lines it +// picks: { raw, pick(count) => [[from, to], ...] }; null when it isn't one. +function parseSelector(selector) { + if (!selector) return { raw: false, pick: (count) => [[1, count]] } + let raw = false + const lists = [] + for (const chunk of selector.split(":")) { + if (/^raw$/i.test(chunk)) raw = true + else lists.push(chunk) + } + if (lists.length > 1) return null + if (!lists.length) return raw ? { raw, pick: (count) => [[1, count]] } : null + const ranges = [] + let tail = 0 + for (const part of lists[0].split(",")) { + const back = /^-(\d+)$/.exec(part) + if (back) { + if (Number(back[1]) < 1) return null + tail = Math.max(tail, Number(back[1])) + continue + } + const m = RANGE_CHUNK.exec(part) + if (!m) return null + const from = Number(m[1]) + if (from < 1) return null + const sep = m[2] === ".." ? "-" : m[2] + const rhs = m[3] === undefined ? undefined : Number(m[3]) + if (sep === "+") { + if (!(rhs >= 1)) return null + ranges.push([from, from + rhs - 1]) + } else if (sep === "-") { + if (rhs !== undefined && rhs < from) return null + ranges.push([from, rhs ?? Infinity]) + } else { + ranges.push([from, from]) + } + } + return { + raw, + pick(count) { + const all = tail ? [...ranges, [Math.max(1, count - tail + 1), count]] : ranges + return mergeRanges(all.map(([from, to]) => [from, Math.min(to, count)])) + }, + } +} + +function mergeRanges(ranges) { + const sorted = ranges.filter(([from, to]) => from <= to).sort((a, b) => a[0] - b[0]) + const out = [] + for (const [from, to] of sorted) { + const last = out.at(-1) + if (last && from <= last[1] + 1) last[1] = Math.max(last[1], to) + else out.push([from, to]) + } + return out +} + +function positive(value) { + const n = Number(value) + return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0 +} + +// The lines a read tool's arguments ask for, beside the path's own selector. +function argumentRange(args, count) { + if (Array.isArray(args.view_range) && args.view_range.length === 2) { + const from = Math.max(1, positive(args.view_range[0]) || 1) + const end = Number(args.view_range[1]) + return [[from, end === -1 || !Number.isFinite(end) ? count : Math.min(count, Math.floor(end))]] + } + const from = Math.max(1, positive(args.offset)) + const limit = positive(args.limit) + return [[from, limit ? Math.min(count, from - 1 + limit) : count]] +} + +function numbered(lines, ranges) { + const out = [] + for (const [from, to] of ranges) for (let n = from; n <= to; n++) out.push(`${String(n).padStart(6)}\t${lines[n - 1]}`) + return out.join("\n") +} + +function plain(lines, ranges) { + const out = [] + for (const [from, to] of ranges) for (let n = from; n <= to; n++) out.push(lines[n - 1]) + return out.join("\n") +} + +function answer(text, lines) { + if (!text && lines.length && !(lines.length === 1 && lines[0] === "")) text = `(nothing in that range: the file has ${lines.length} lines)` + return { content: [{ type: "text", text }], isError: false } +} + +// Every string in args with the key it sits under (an array's items under +// the array's key), however deep. +function strings(value, key = "", out = []) { + if (typeof value === "string") out.push({ key, value }) + else if (Array.isArray(value)) for (const item of value) strings(item, key, out) + else if (value && typeof value === "object") for (const [k, v] of Object.entries(value)) strings(v, k, out) + return out +} + +// The spilled outputs a command or code names, by the folder's path in it. +function namedIn(agyDir, text) { + const roots = new Set([agyDir]) + try { roots.add(fs.realpathSync(agyDir)) } catch {} + for (const root of [...roots]) { + roots.add(root.replace(/\\/g, "/")) + roots.add(root.replace(/\//g, "\\")) + } + const found = new Set() + for (const root of roots) { + for (let at = text.indexOf(root); at >= 0; at = text.indexOf(root, at + 1)) { + const m = SPILLED_TAIL.exec(text.slice(at + root.length)) + if (m) found.add(text.slice(at, at + root.length + m[0].length)) + } + } + return [...found] +} + +// --- shell ----------------------------------------------------------- + +// Words of a command of one pipeline, quotes taken off; null for anything +// more (;, &&, redirection to a file, substitution, a variable). +function shellStages(command) { + let text = command.trim().replace(/\s+(?:2>\s*\/dev\/null|2>&1|2>\$null)\s*$/i, "") + const stages = [[]] + let word = null + const push = () => { if (word !== null) stages.at(-1).push(word); word = null } + for (let i = 0; i < text.length; i++) { + const c = text[i] + if (c === "'") { + const end = text.indexOf("'", i + 1) + if (end < 0) return null + word = (word ?? "") + text.slice(i + 1, end) + i = end + } else if (c === '"') { + let j = i + 1 + let s = "" + for (; j < text.length && text[j] !== '"'; j++) { + if (text[j] === "\\" && j + 1 < text.length && /["\\$`]/.test(text[j + 1])) s += text[++j] + else if (/[$`]/.test(text[j])) return null + else s += text[j] + } + if (j >= text.length) return null + word = (word ?? "") + s + i = j + } else if (c === "|") { + if (text[i + 1] === "|") return null + push() + stages.push([]) + } else if (/\s/.test(c)) { + push() + } else if (/[;&<>`$(){}*?]/.test(c)) { + return null + } else if (c === "\\" && i + 1 < text.length && !/[A-Za-z0-9_.-]/.test(text[i + 1])) { + word = (word ?? "") + text[++i] + } else { + word = (word ?? "") + c + } + } + push() + return stages.every((stage) => stage.length) ? stages : null +} + +// A count after -n, as head and tail take it: "5", "+5" (tail: from line 5). +function countArg(words, i) { + const w = words[i] + let m = /^-n(.*)$/.exec(w) || /^--lines=(.*)$/.exec(w) + if (m) return m[1] ? { value: m[1], used: 1 } : words[i + 1] !== undefined ? { value: words[i + 1], used: 2 } : null + m = /^-(\d+)$/.exec(w) + if (m) return { value: m[1], used: 1 } + return null +} + +// One stage as what it does to the lines: (lines) => lines, and the file it +// reads, if it names one; null for a stage that isn't a plain read. +function shellStage(words) { + const [cmd, ...rest] = words + const name = cmd.toLowerCase() + const files = [] + if (name === "cat" || name === "type" || name === "get-content" || name === "gc") { + let number = false + let first = 0 + let last = 0 + for (let i = 0; i < rest.length; i++) { + const w = rest[i] + if (name === "cat" && w === "-n") number = true + else if (/^-(?:path|literalpath|lp)$/i.test(w) && rest[i + 1] !== undefined) files.push(rest[++i]) + else if (/^-(?:totalcount|head|first)$/i.test(w) && positive(rest[i + 1])) first = positive(rest[++i]) + else if (/^-(?:tail|last)$/i.test(w) && positive(rest[i + 1])) last = positive(rest[++i]) + else if (/^-(?:raw|encoding)$/i.test(w)) { if (/^-encoding$/i.test(w)) i++ } + else if (w.startsWith("-") && w !== "-") return null + else files.push(w) + } + return { + files, + run(lines) { + let out = lines + if (first) out = out.slice(0, first) + if (last) out = out.slice(-last) + return number ? out.map((line, i) => `${String(i + 1).padStart(6)}\t${line}`) : out + }, + } + } + if (name === "head" || name === "tail") { + let count = "10" + for (let i = 0; i < rest.length; i++) { + const n = countArg(rest, i) + if (n) { count = n.value; i += n.used - 1; continue } + if (rest[i].startsWith("-")) return null + files.push(rest[i]) + } + const m = /^(\+)?(\d+)$/.exec(count) + if (!m) return null + const n = Number(m[2]) + if (name === "head") return m[1] ? null : { files, run: (lines) => lines.slice(0, n) } + return { files, run: (lines) => m[1] ? lines.slice(Math.max(0, n - 1)) : n ? lines.slice(-n) : [] } + } + if (name === "sed") { + let quiet = false + let script = null + for (const w of rest) { + if (w === "-n") quiet = true + else if (script === null && !w.startsWith("-")) script = w + else if (w.startsWith("-")) return null + else files.push(w) + } + const m = script && /^(\d+)(?:,(\d+|\$))?p$/.exec(script.trim()) + if (!quiet || !m) return null + const from = Number(m[1]) + const to = m[2] === undefined ? from : m[2] === "$" ? Infinity : Number(m[2]) + return { files, run: (lines) => lines.slice(Math.max(0, from - 1), to) } + } + if (name === "select-object" || name === "select") { + let first = 0 + let last = 0 + let skip = 0 + for (let i = 0; i < rest.length; i++) { + const w = rest[i] + const n = positive(rest[i + 1]) + if (/^-first$/i.test(w) && n) { first = n; i++ } + else if (/^-last$/i.test(w) && n) { last = n; i++ } + else if (/^-skip$/i.test(w) && n) { skip = n; i++ } + else return null + } + return { + files, + run(lines) { + let out = lines.slice(skip) + if (first) out = out.slice(0, first) + if (last) out = out.slice(-last) + return out + }, + } + } + return null +} + +// What a shell command that only reads file prints, null for any other. +function shellRead(agyDir, command, real) { + const stages = shellStages(command) + if (!stages) return null + let lines = null + for (const [index, words] of stages.entries()) { + const stage = shellStage(words) + if (!stage) return null + if (index === 0) { + if (stage.files.length !== 1 || spilledFile(agyDir, stage.files[0]) !== real) return null + lines = stage.run(fileLines(real)) + } else { + if (stage.files.length) return null + lines = stage.run(lines) + } + } + return lines.join("\n") +} + +// --- code ------------------------------------------------------------ + +const PY_STRING = String.raw`[rR]?(?:"([^"\\\n]*)"|'([^'\\\n]*)')` +const PY_TEXT_ARGS = String.raw`(?:\s*(?:encoding\s*=\s*)?["'][\w-]+["'])?(?:\s*,\s*errors\s*=\s*["'][\w-]+["'])?` +const PY_OPEN_ARGS = String.raw`(?:\s*,\s*(?:mode\s*=\s*)?["']rt?["'])?(?:\s*,\s*encoding\s*=\s*["'][\w-]+["'])?(?:\s*,\s*errors\s*=\s*["'][\w-]+["'])?` +const PY_READ = new RegExp(String.raw`^(?:print\s*\(\s*)?(?:(?:pathlib\s*\.\s*)?Path\s*\(\s*${PY_STRING}\s*\)\s*\.\s*read_text\s*\(${PY_TEXT_ARGS}\s*\)|open\s*\(\s*${PY_STRING}${PY_OPEN_ARGS}\s*\)\s*\.\s*read\s*\(\s*\))\s*(?:\)\s*)?;?$`) +const JS_STRING = String.raw`(?:"([^"\\\n]*)"|'([^'\\\n]*)'|\x60([^\x60\\$\n]*)\x60)` +const JS_READ = new RegExp(String.raw`^(?:console\s*\.\s*log\s*\(\s*|return\s+)?(?:await\s+)?(?:(?:(?:fs|require\s*\(\s*["'](?:node:)?fs["']\s*\))\s*\.\s*)?readFileSync\s*\(\s*${JS_STRING}\s*,\s*(?:["']utf-?8["']|\{\s*encoding\s*:\s*["']utf-?8["']\s*\})\s*\)|(?:fs\s*\.\s*promises\s*\.\s*|fsp\s*\.\s*)?readFile\s*\(\s*${JS_STRING}\s*,\s*["']utf-?8["']\s*\)|Bun\s*\.\s*file\s*\(\s*${JS_STRING}\s*\)\s*\.\s*text\s*\(\s*\))\s*(?:\)\s*)?;?$`) +// lines code may have beside its one read: imports +const CODE_PREAMBLE = /^\s*(?:import\s+[\w.]+(?:\s+as\s+\w+)?|from\s+[\w.]+\s+import\s+[\w, ]+|import\s+(?:\*\s+as\s+)?\w+\s+from\s+["'][\w:/-]+["'];?|import\s+\{[\w\s,]+\}\s+from\s+["'][\w:/-]+["'];?|(?:const|let|var)\s+(?:\w+|\{[\w\s,]+\})\s*=\s*(?:await\s+import|require)\s*\(\s*["'][\w:/-]+["']\s*\);?)\s*$/ + +// What code that only reads file gives, null for any other code. +function codeRead(agyDir, code, real) { + const body = code.split("\n").filter((line) => line.trim() && !line.trim().startsWith("#") && !CODE_PREAMBLE.test(line)) + if (body.length !== 1) return null + const statement = body[0].trim() + const m = PY_READ.exec(statement) || JS_READ.exec(statement) + if (!m) return null + // a wrapper's ( has its ) + const opened = (statement.match(/\(/g) || []).length + const closed = (statement.match(/\)/g) || []).length + if (opened !== closed) return null + const named = m.slice(1).find((group) => group !== undefined) + if (spilledFile(agyDir, named) !== real) return null + return fs.readFileSync(real, "utf8") +} + +// --- the call -------------------------------------------------------- + +// spilledOutput answers a client tool call that reads a file agy spilled, +// from that file: { content, isError }, or null to leave the call to the +// client. readTool: the client's read tool, named when telling the model +// how to read the file; here: the client is known to be on this machine. +export function spilledOutput(agyDir, name, args, { readTool = "", here = false } = {}) { + if (!agyDir || typeof name !== "string" || !args || typeof args !== "object") return null + const found = strings(args) + // a read tool's one path, a selector maybe after it + if (READ_TOOL.test(name) || args.command === "view") { + const paths = found.filter(({ value }) => /^(?:file:\/\/|[\\/]|[A-Za-z]:[\\/])/.test(value.trim())) + if (paths.length === 1) { + const split = splitSelector(paths[0].value.trim()) + const real = split && spilledFile(agyDir, split.file) + if (real) { + const selector = parseSelector(split.selector) + if (!selector) { + return { + content: [{ type: "text", text: `Invalid selector ':${split.selector}'. Use :N, :N-M, :N+K, :N- (open-ended), :-N (last N lines), a comma-separated list of ranges, :raw, or a range with raw (e.g. :raw:50-100).` }], + isError: true, + } + } + let lines + try { lines = fileLines(real) } catch { return null } + const ranges = split.selector ? selector.pick(lines.length) : argumentRange(args, lines.length) + return answer(selector.raw ? plain(lines, ranges) : numbered(lines, ranges), lines) + } + } + } + // a command or code that names one + const named = [] + for (const { key, value } of found) { + const whole = spilledFile(agyDir, value.trim()) + const inText = COMMAND_KEY.test(key) || /bash|shell|command|exec|eval|python|terminal|powershell|repl|^sh$|^js$/i.test(name) + ? namedIn(agyDir, value) : [] + if (whole) named.push({ value, real: whole, whole: true }) + for (const file of inText) { + const real = spilledFile(agyDir, file) + if (real) named.push({ value, real, whole: false }) + } + } + if (!named.length) return null + const files = [...new Set(named.map((n) => n.real))] + if (files.length === 1) { + for (const { value, real, whole } of named) { + if (whole) continue + let text = null + try { text = shellRead(agyDir, value, real) ?? codeRead(agyDir, value, real) } catch { text = null } + if (text !== null) return { content: [{ type: "text", text }], isError: false } + } + } + if (here) return null + const shown = named.find((n) => n.whole)?.value.trim() || namedIn(agyDir, named[0].value)[0] || files[0] + const how = readTool ? `with ${readTool} on that path (a line range as ${readTool} takes it), or ` : "" + return { + content: [{ + type: "text", + text: `${shown} is where this session saves tool outputs, which may not be the machine ${name} runs on, so this call isn't run. Read it ${how}with a command that only reads it: cat, head -n N, tail -n N or sed -n 'A,Bp' on that path alone.`, + }], + isError: true, + } +} diff --git a/test/catalog.mjs b/test/catalog.mjs index 727f578..1835422 100644 --- a/test/catalog.mjs +++ b/test/catalog.mjs @@ -14,7 +14,7 @@ import fs from "node:fs" import os from "node:os" import path from "node:path" import { - BASE_MODEL_ROWS, CATALOG_TTL_MS, OFFERED_TTL_MS, MESSAGES_URL, baseBody, createBridgeKit, modelsOutput, readSse, sleep, tick, + BASE_MODEL_ROWS, CATALOG_TTL_MS, MESSAGES_URL, baseBody, createBridgeKit, modelsOutput, readSse, sleep, tick, } from "./testkit.mjs" const FAST_BUDGET_MS = 750 // 计划给的调度容差;补丁内部等待预算是 500ms,远低于 Magpie 的 2s。 @@ -622,14 +622,36 @@ test("首次快速成功时直接拿到动态目录", async () => { }) }) -test("会话开放的型号才列出:不等请求,探测会话就列出 Claude、GPT-OSS 和 agy models 没列的型号", async () => { - await withKit({ modelsBehavior: DYNAMIC_OK, offeredModels: [ +const ACP_FLAGS_HELP = "Usage of acp:\n --include-default-customizations\n \tload the default customizations (default true)\n --disable-telemetry\n \tdisable telemetry (default false)\n" + +// An idle account sends Google nothing of its own (Discord, 12-03: an +// Antigravity account was banned with no agent using it): a listing never +// starts agy acp, and the list is never listed again for its age. The user +// refreshing the list asks agy acp once, run as a turn runs it. +test("会话开放的型号:列目录从不起 agy acp,也不按时间重列;用户刷新时问一次,参数和请求的一样", async () => { + await withKit({ modelsBehavior: DYNAMIC_OK, acpHelp: ACP_FLAGS_HELP, offeredModels: [ ["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["gemini-4-argon-low", "Gemini 4 Argon (Low)"], ["claude-opus-5-5-high", "Claude Opus 5.5 (High)"], ["claude-opus-5-5-low", "Claude Opus 5.5 (Low)"], ["gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"], ["offered-only", "Offered Only"], ] }, async (kit) => { await kit.models() - await settle(kit) + await warmed(kit) + const listed = await kit.models() + assert.equal(kit.acpSpawns.length, 0, "列目录起了 agy acp") + assert.equal(kit.modelsSpawns.length, 1) + assert.equal(listed["claude-opus-5-5"], undefined, "没有会话说过就列出了 Claude") + // 一个月过去,没人用:一个子进程都不起。 + kit.clock.advance(30 * 24 * 60 * 60 * 1000) + await kit.models() + await warmed(kit) + assert.equal(kit.modelsSpawns.length, 1, "列表按时间重列了") + assert.equal(kit.acpSpawns.length, 0, "开放型号按时间重问了") + // 用户刷新:agy models 和 agy acp 各问一次。 + const refreshed = await kit.refresh() + await warmed(kit) + assert.equal(kit.modelsSpawns.length, 2) + assert.equal(kit.acpSpawns.length, 1) + assert.ok(refreshed["claude-opus-5-5"], "刷新等到了 agy acp 的回答") const after = await kit.models() assert.deepEqual(Object.keys(after["claude-opus-5-5"]?.variants ?? {}).sort(), ["high", "low"]) assert.deepEqual(JSON.parse(JSON.stringify(after["claude-opus-5-5"].limit)), { context: 1000000, output: 64000 }) @@ -639,47 +661,64 @@ test("会话开放的型号才列出:不等请求,探测会话就列出 Clau assert.equal(after["gemini-3.8-flash"], undefined, "会话没开放的 Gemini 也不应列出") assert.equal(after["mystery-model"], undefined) assert.ok(after["gemini-4-argon"]) - // 探测只开会话、不发 prompt,用插件自己的名字,进程跑完就关。 - assert.equal(kit.acpLog.filter(entry => entry.method === "session/prompt").length, 0, "探测不应发 prompt") + // 只开会话、不发 prompt,用插件自己的名字,和请求一样关掉遥测和默认定制,跑完就关。 + assert.equal(kit.acpLog.filter(entry => entry.method === "session/prompt").length, 0, "不应发 prompt") assert.equal(kit.acpLog.filter(entry => entry.method === "session/new").length, 1) assert.equal(kit.acpLog.find(entry => entry.method === "initialize")?.params?.clientInfo?.name, "opencode-agy-cli-auth") - assert.deepEqual(kit.acpSpawns.map(spawn => spawn.args), [["acp"]]) - assert.equal(kit.children.size, 0, "探测的 agy acp 应已退出") - // TTL 之内,目录 5 分钟一刷也不再探测:每次探测都要起一个 agy acp。 - kit.clock.advance(CATALOG_TTL_MS) + const args = kit.acpSpawns[0].args + assert.equal(args[0], "acp") + assert.ok(args.includes("--disable-telemetry"), args.join(" ")) + assert.ok(args.includes("--include-default-customizations=false"), args.join(" ")) + assert.equal(kit.children.size, 0, "agy acp 应已退出") + // 之后的列目录不再起任何子进程。 + kit.clock.advance(2 * 60 * 60 * 1000) await kit.models() - await settle(kit) - assert.equal(kit.acpSpawns.length, 1, "开放型号的 TTL 之内不该再探测") - // 到了开放型号的 TTL 就再探测一次:学到的开放型号不能永远当真, - // Google 在服务端换了开放的型号,目录要跟上(2026-11-27)。 - kit.clock.advance(OFFERED_TTL_MS - CATALOG_TTL_MS) - await kit.models() - await settle(kit) - assert.equal(kit.acpSpawns.length, 2, "到了开放型号的 TTL 应当再探测一次") - const relearned = await kit.models() - assert.ok(relearned["claude-opus-5-5"], "重探测后仍应列出会话开放的型号") - assert.equal(relearned["claude-sonnet-5-5"], undefined, "重探测后仍不应列出会话没开放的型号") - assert.equal(relearned["gemini-3.8-flash"], undefined, "重探测后仍不应列出会话没开放的 Gemini") + await warmed(kit) + assert.equal(kit.modelsSpawns.length, 2) + assert.equal(kit.acpSpawns.length, 1) + }) +}) + +test("一个请求的 agy acp 和用户刷新时问的一样:同样的参数和客户端名", async () => { + await withKit({ modelsBehavior: DYNAMIC_OK, acpHelp: ACP_FLAGS_HELP, offeredModels: OFFERED_ALL }, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.text("ok") + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } } + } + const parsed = await readSse(await kit.request(baseBody({ model: "agy-cli/gemini-4-argon", tools: [], messages: [{ role: "user", content: "hi" }] }))) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + const started = performance.now() + await kit.refresh() + assert.ok(performance.now() - started < 5_000, `刷新等了 ${Math.round(performance.now() - started)}ms`) + await warmed(kit) + assert.equal(kit.acpSpawns.length, 2) + // 请求自己的 --ide-mcp-port、--log-file 只属于那一轮;遥测和默认定制必须一样。 + const flags = (args) => args.filter(arg => /^--(?:disable-telemetry|include-default-customizations)/.test(arg)).sort() + assert.deepEqual(flags(kit.acpSpawns[0].args), ["--disable-telemetry", "--include-default-customizations=false"]) + assert.deepEqual(flags(kit.acpSpawns[1].args), flags(kit.acpSpawns[0].args)) + const names = kit.acpLog.filter(entry => entry.method === "initialize").map(entry => entry.params?.clientInfo?.name) + assert.deepEqual(names, ["opencode-agy-cli-auth", "opencode-agy-cli-auth"]) }) }) -test("探测会话失败(agy 要求登录)时只列 Gemini,限流后再试,成功即列出", async () => { +test("刷新时 agy acp 失败(agy 要求登录)只列 Gemini;不自己再试,下次刷新成功即列出", async () => { await withKit({ modelsBehavior: DYNAMIC_OK, sessionNewError: { code: -32000, message: "Authentication required" }, offeredModels: [ ["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["claude-opus-5-5-high", "Claude Opus 5.5 (High)"], ["claude-opus-5-5-low", "Claude Opus 5.5 (Low)"], ] }, async (kit) => { - await kit.models() - await settle(kit) + await kit.refresh() + await warmed(kit) const failed = await kit.models() assert.equal(failed["claude-opus-5-5"], undefined) assert.ok(failed["gemini-4-argon"]) - assert.equal(kit.children.size, 0, "失败的探测也应关掉 agy acp") - assert.equal(kit.acpSpawns.length, 1, "一分钟内不再探测") + assert.equal(kit.children.size, 0, "失败的 agy acp 也应关掉") + assert.equal(kit.acpSpawns.length, 1) kit.sessionNewError = null - kit.clock.advance(60_000) + kit.clock.advance(60 * 60 * 1000) await kit.models() - // 新鲜目录不等探测:等它起来并跑完。 - for (let i = 0; i < 200 && kit.acpSpawns.length < 2; i++) await sleep(5) - await settle(kit) + await warmed(kit) + assert.equal(kit.acpSpawns.length, 1, "没人刷新就又问了 agy acp") + await kit.refresh() + await warmed(kit) assert.equal(kit.acpSpawns.length, 2) const listed = await kit.models() assert.deepEqual(Object.keys(listed["claude-opus-5-5"]?.variants ?? {}).sort(), ["high", "low"]) @@ -721,9 +760,9 @@ test("图片模型不进聊天目录:buildModelCatalog 排除 gemini-3.1-flash // 2026-11-27:Google 在服务端换了 agy acp 开放的型号(新来的 claude-4-6 / // gemini-3.1-flash-image,旧的 gemini-4-neon/carbon/argon 与 claude-5-5 不再 -// 开放),网关却一直列着旧的开放型号:学到的开放型号没有 TTL,列表没变 -// 就不重新探测。到了 TTL 就再探测,目录跟上新开放的型号;图片模型不进 -// 聊天目录(只走图片路径)。 +// 开放),网关却一直列着旧的开放型号。目录跟上的是下一个请求自己的会话 +// (或用户刷新),不是后台按时探测:空闲的账号什么都不发(12-03)。 +// 图片模型不进聊天目录(只走图片路径)。 const INCIDENT_ROWS = [ ...BASE_MODEL_ROWS, ["gemini-4-neon-high", "Gemini 4 Neon (High)"], ["gemini-4-neon-low", "Gemini 4 Neon (Low)"], @@ -748,10 +787,10 @@ const INCIDENT_OFFERED_OLD = [ ["gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"], ] -test("服务端换了开放的型号,目录在一个 TTL 内跟上;图片模型不进聊天目录", async () => { +test("服务端换了开放的型号,下一个请求的会话一说目录就跟上;图片模型不进聊天目录", async () => { await withKit({ modelsBehavior: { stdout: modelsOutput(INCIDENT_ROWS) }, offeredModels: INCIDENT_OFFERED_NEW }, async (kit) => { - await kit.models() - await settle(kit) + await kit.refresh() + await warmed(kit) const listed = await kit.models() assert.ok(listed["claude-sonnet-4-6"], "新开放的型号应列出") assert.ok(listed["claude-opus-4-6-thinking"], "新开放的型号应列出") @@ -766,24 +805,30 @@ test("服务端换了开放的型号,目录在一个 TTL 内跟上;图片模 assert.equal(image.capabilities?.output?.text, false, "图片模型不应有文本输出") assert.equal(image.capabilities?.output?.image, true, "图片模型应有图像输出") assert.deepEqual(image.variants ?? {}, {}, "图片模型不应有聊天档位") - // 服务端换回旧的开放型号:到了 TTL 再探测,目录跟上。 + // 服务端换回旧的开放型号:列目录不去问,请求自己的会话说了就跟上。 const probes = kit.acpSpawns.length kit.offeredModels = INCIDENT_OFFERED_OLD - kit.clock.advance(OFFERED_TTL_MS) + kit.clock.advance(24 * 60 * 60 * 1000) await kit.models() - await settle(kit) - assert.ok(kit.acpSpawns.length > probes, "到了 TTL 应当再探测开放型号") + await warmed(kit) + assert.equal(kit.acpSpawns.length, probes, "没人用时不该问 agy acp") + kit.defaultPrompt = async (agent) => { + await agent.text("ok") + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } } + } + const parsed = await readSse(await kit.request(baseBody({ model: "agy-cli/gemini-4-hydrogen", tools: [], messages: [{ role: "user", content: "hi" }] }))) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) const after = await kit.models() - for (const id of ["gemini-4-neon", "gemini-4-carbon", "gemini-4-argon", "claude-opus-5-5", "claude-sonnet-5-5"]) assert.ok(after[id], `重探测后应列出 ${id}`) - assert.equal(after["claude-sonnet-4-6"], undefined, "重探测后不应再列出已不开放的型号") - assert.equal(after["claude-opus-4-6-thinking"], undefined, "重探测后不应再列出已不开放的型号") - assert.equal(after["gemini-3.1-flash-image"]?.capabilities?.output?.text, false, "重探测后图片模型仍不应是聊天型号") + for (const id of ["gemini-4-neon", "gemini-4-carbon", "gemini-4-argon", "claude-opus-5-5", "claude-sonnet-5-5"]) assert.ok(after[id], `会话说了以后应列出 ${id}`) + assert.equal(after["claude-sonnet-4-6"], undefined, "不应再列出已不开放的型号") + assert.equal(after["claude-opus-4-6-thinking"], undefined, "不应再列出已不开放的型号") + assert.equal(after["gemini-3.1-flash-image"]?.capabilities?.output?.text, false, "图片模型仍不应是聊天型号") }) }) // #1064(hiee3):真实登录的 agy 上 `agy models` 约 4.4s、agy acp 开会话约 3s,都远过 500ms 的快速等待。 -// 这里各模拟 1.5s:第一次 models() 只能给静态目录,但列表一到就该起探测, -// 后台跑完后的第一次 models() 就要有 Claude 和 GPT-OSS,不该要第三次。 +// 这里各模拟 1.5s。agy acp 只在登录和用户刷新时问(12-03):登录后的第一次 +// models() 就有 Claude 和 GPT-OSS,刷新等得到两个回答。 const SLOW_MS = 1_500 const OFFERED_CLAUDE = [ ["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["gemini-4-argon-low", "Gemini 4 Argon (Low)"], @@ -805,48 +850,63 @@ function assertClaudeListed(models, label) { for (const id of ["claude-opus-5-5", "claude-sonnet-5-5", "gpt-oss-120b"]) assert.ok(models[id], `${label}:没有 ${id},只有 ${ids(models).join(", ")}`) } -test("#1064 慢 agy:第一次 models() 给静态目录,后台热身后的第一次就列出 Claude 和 GPT-OSS", async () => { +test("#1064 慢 agy:第一次 models() 给静态目录,后台列完只列 Gemini、不起 agy acp;刷新等到 Claude 和 GPT-OSS", async () => { await withKit(SLOW_AGY, async (kit) => { const { value: first, ms } = await timed(() => kit.models()) assert.ok(ms < FAST_BUDGET_MS, `首次目录耗时 ${Math.round(ms)}ms`) assertFallbackPresent(first) await warmed(kit) - assert.equal(kit.acpSpawns.length, 1, "列表一到就该起一次探测会话") + assert.equal(kit.acpSpawns.length, 0, "列目录起了 agy acp") const { value: after, ms: warmMs } = await timed(() => kit.models()) assert.ok(warmMs < 100, `热身后的目录耗时 ${Math.round(warmMs)}ms`) - assertClaudeListed(after, "热身后的第一次 models()") + assert.ok(after["gemini-4-argon"]) + assert.equal(after["claude-opus-5-5"], undefined) assert.equal(kit.modelsSpawns.length, 1) - assert.equal(kit.acpSpawns.length, 1) assert.equal(kit.plugin.provider.warming(), null, "热身完了不该还说在热身") + const { value: refreshed } = await timed(() => kit.refresh()) + assertClaudeListed(refreshed, "刷新") + assert.equal(kit.modelsSpawns.length, 2) + assert.equal(kit.acpSpawns.length, 1) }) }) -// #1086(yinbing-666):重启后在 agy 再次回答前,也该列出上次的完整目录,而不是只有 Gemini。 -// 重启后 agy 回答了也要再探测一次保存的开放型号(shenggxhz),多一次 1.5s 的慢会话,所以给 15s。 -test("#1086 重启后第一次 models() 就给上次 agy 列出并开放的目录,坏文件和别的 agy 仍给静态目录", { timeout: 15_000 }, async () => { +// #1086(yinbing-666):重启后就列出上次的完整目录,而不是只有 Gemini; +// 12-03 起重启也不再问 agy:保存的列表、开放型号和档位照旧用。慢会话 1.5s,给 15s。 +test("#1086 重启后第一次 models() 就给上次 agy 列出并开放的目录,一个子进程都不起;坏文件和别的 agy 仍给静态目录", { timeout: 15_000 }, async () => { const shared = fs.mkdtempSync(path.join(os.tmpdir(), "agy-catalog-saved-")) try { const agy = path.join(shared, process.platform === "win32" ? "agy.exe" : "agy") fs.writeFileSync(agy, "#!/bin/sh\nexit 99\n", { mode: 0o755 }) const env = { XDG_STATE_HOME: path.join(shared, "state") } - await withKit({ ...SLOW_AGY, agyPath: agy, env }, async (kit) => { + let listedAt + await withKit({ ...SLOW_AGY, agyPath: agy, env, sessionTier: { id: "g1-pro-tier", name: "Google AI Pro" } }, async (kit) => { assertFallbackPresent(await kit.models()) await warmed(kit) - assertClaudeListed(await kit.models(), "第一次运行") + listedAt = kit.clock.now() + kit.clock.advance(60_000) + assertClaudeListed(await kit.refresh(), "第一次运行的刷新") + await warmed(kit) }) const file = path.join(shared, "state", "magpie-agy-bridge", "models.json") const saved = fs.readFileSync(file, "utf8") assert.match(saved, /claude-sonnet-5-5-high/) + const entry = Object.values(JSON.parse(saved).byAgy)[0] + assert.ok(entry.fetchedAt > listedAt, "fetchedAt 是刷新时列出的时间") + assert.equal(entry.tier, "g1-pro-tier") + assert.ok(entry.offered.some(row => row.id === "claude-sonnet-5-5-high")) - // 重启:agy 还是慢,第一次 models() 就该有 Claude;探测等 agy models 回答后才起。 + // 重启:第一次 models() 就有 Claude;不问 agy models,也不起 agy acp。 await withKit({ ...SLOW_AGY, agyPath: agy, env }, async (kit) => { const { value: first, ms } = await timed(() => kit.models()) assert.ok(ms < FAST_BUDGET_MS, `重启后首次目录耗时 ${Math.round(ms)}ms`) assertClaudeListed(first, "重启后第一次") - assert.equal(kit.acpSpawns.length, 0, "agy models 回答前不该起探测会话") - assert.equal(kit.modelsSpawns.length, 1, "保存的目录也要再问一次 agy") await warmed(kit) - assert.equal(kit.acpSpawns.length, 1, "agy 回答后,保存的开放型号也要再探测一次") + kit.clock.advance(7 * 24 * 60 * 60 * 1000) + assertClaudeListed(await kit.models(), "重启一周后") + await warmed(kit) + assert.equal(kit.modelsSpawns.length, 0, "重启后又问了 agy models") + assert.equal(kit.acpSpawns.length, 0, "重启后起了 agy acp") + assert.equal(kit.plugin.provider.warming(), null) }) // 另一个 agy 可执行文件不用这份目录。 @@ -866,6 +926,42 @@ test("#1086 重启后第一次 models() 就给上次 agy 列出并开放的目 } }) +test("models.json 之后被写坏:内存里的目录照旧,下次保存不丢别的账号的条目", async () => { + const shared = fs.mkdtempSync(path.join(os.tmpdir(), "agy-catalog-torn-")) + try { + const agy = path.join(shared, process.platform === "win32" ? "agy.exe" : "agy") + fs.writeFileSync(agy, "#!/bin/sh\nexit 99\n", { mode: 0o755 }) + const env = { XDG_STATE_HOME: path.join(shared, "state") } + const file = path.join(shared, "state", "magpie-agy-bridge", "models.json") + fs.mkdirSync(path.dirname(file), { recursive: true }) + const other = { at: Date.UTC(2026, 10, 4, 11, 0, 0), list: [{ id: "gemini-4-argon-high", name: "Gemini 4 Argon (High)", effort: "high" }] } + fs.writeFileSync(file, JSON.stringify({ version: 1, byAgy: { [`${agy}#someone-else`]: other } })) + await withKit({ modelsBehavior: DYNAMIC_OK, agyPath: agy, env, offeredModels: OFFERED_CLAUDE }, async (kit) => { + await kit.models() + await warmed(kit) + assert.ok((await kit.models())["gemini-9-test"]) + // 另一个进程写了一半 + const whole = fs.readFileSync(file, "utf8") + fs.writeFileSync(file, whole.slice(0, 20)) + assert.ok((await kit.models())["gemini-9-test"], "坏文件冲掉了内存里的目录") + // 一个请求的会话说了开放的型号:保存时用上次读好的内容 + kit.defaultPrompt = async (agent) => { + await agent.text("ok") + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } } + } + const parsed = await readSse(await kit.request(baseBody({ model: "agy-cli/gemini-4-argon", tools: [], messages: [{ role: "user", content: "hi" }] }))) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + const byAgy = JSON.parse(fs.readFileSync(file, "utf8")).byAgy + assert.deepEqual(byAgy[`${agy}#someone-else`], other, "别的账号的条目丢了") + assert.ok(byAgy[agy]?.offered?.some(row => row.id === "claude-opus-5-5-high"), "会话说的开放型号没存下") + assert.equal(kit.acpSpawns.length, 1, "只有请求自己的 agy acp") + assert.equal(kit.modelsSpawns.length, 1) + }) + } finally { + fs.rmSync(shared, { recursive: true, force: true }) + } +}) + test("#1064 慢 agy:已登录时 authorize 读到的列表和探测就是目录,紧接着的 models() 不再是静态目录", async () => { await withKit(SLOW_AGY, async (kit) => { const { value: started, ms } = await timed(() => kit.plugin.auth.methods[0].authorize()) @@ -896,9 +992,9 @@ test("#1064 登录检查不为探测等太久:会话一直不答时最多多 }) }) -test("#1064 agyPath 变了,旧 agy 开放的型号不再列出,新 agy 重新探测", async () => { +test("#1064 agyPath 变了,旧 agy 开放的型号不再列出,刷新时问的是新 agy", async () => { await withKit({ modelsBehavior: DYNAMIC_OK, offeredModels: OFFERED_CLAUDE }, async (kit) => { - await kit.models() + await kit.refresh() await warmed(kit) assertClaudeListed(await kit.models(), "agy-a") kit.env.AGY_PATH = kit.makeFakeAgy("agy-b") @@ -906,7 +1002,10 @@ test("#1064 agyPath 变了,旧 agy 开放的型号不再列出,新 agy 重 const switched = await kit.models() assert.deepEqual(ids(switched).filter(id => /^(?:claude|gpt)-/.test(id)), [], "换了 agy 还在列旧 agy 开放的型号") await warmed(kit) - assert.equal(kit.acpSpawns.length, 2, "新 agy 应重新探测") + assert.equal(kit.acpSpawns.length, 1, "没人刷新就问了新 agy 的 agy acp") + await kit.refresh() + await warmed(kit) + assert.equal(kit.acpSpawns.length, 2) assert.equal(kit.acpSpawns.at(-1).file, kit.env.AGY_PATH) const after = await kit.models() assert.equal(after["claude-opus-5-5"], undefined) @@ -939,20 +1038,23 @@ test("新鲜缓存不再等待也不再 spawn", async () => { }) }) -test("TTL 边界:差 1ms 不刷新,到点后台刷新且过期期间仍 750ms 内返回旧动态目录", async () => { +test("列过的目录不按时间重列:一年后也不起 agy models;用户刷新时后台重列,卡住期间 750ms 内仍给旧动态目录", async () => { await withKit({ modelsBehavior: DYNAMIC_OK }, async (kit) => { await kit.models() await settle(kit) assert.equal(kit.modelsSpawns.length, 1) kit.modelsBehavior = { hang: true } - kit.clock.advance(CATALOG_TTL_MS - 1) + kit.clock.advance(365 * 24 * 60 * 60 * 1000) await kit.models() - assert.equal(kit.modelsSpawns.length, 1, "TTL 未到就重新 spawn 了") - kit.clock.advance(1) - const { value, ms } = await timed(() => kit.models()) - assert.equal(kit.modelsSpawns.length, 2, "TTL 到点没有刷新") - assert.ok(ms < FAST_BUDGET_MS, `过期目录耗时 ${Math.round(ms)}ms`) - assert.ok(value["gemini-9-test"], "过期刷新卡住时丢了上次的动态目录") + assert.equal(kit.modelsSpawns.length, 1, "按时间重列了") + // 刷新等 agy 最多十几秒(host 的 listWait 约 15s),等不到就给上次的 + const value = await kit.refresh() + assert.equal(kit.modelsSpawns.length, 2, "刷新没有重列") + assert.ok(value["gemini-9-test"], "刷新卡住时丢了上次的动态目录") + const { value: during, ms: duringMs } = await timed(() => kit.models()) + assert.ok(duringMs < FAST_BUDGET_MS, `刷新期间目录耗时 ${Math.round(duringMs)}ms`) + assert.ok(during["gemini-9-test"]) + await kit.finishChildren() }) }) @@ -967,14 +1069,13 @@ test("50 个并发 models() 只 spawn 一次且结果一致", async () => { }) }) -test("失败、超时、空输出、不可解析输出都保留动态独有型号,成功后恢复更新", async () => { +test("刷新失败、超时、空输出、不可解析输出都保留动态独有型号,成功后恢复更新", async () => { await withKit({ modelsBehavior: DYNAMIC_OK }, async (kit) => { assert.ok((await kit.models())["gemini-9-test"]) await settle(kit) const failures = [ ["退出码非零", { code: 1, stdout: "" }], ["被超时杀掉", { killed: true }], - ["卡死", { hang: true }], ["spawn error 事件", { error: true }], ["spawn 同步抛错", { throwSync: true }], ["空输出", { code: 0, stdout: "" }], @@ -982,18 +1083,15 @@ test("失败、超时、空输出、不可解析输出都保留动态独有型 ] for (const [label, behavior] of failures) { kit.modelsBehavior = behavior - kit.clock.advance(CATALOG_TTL_MS) const before = kit.modelsSpawns.length - const { value, ms } = await timed(() => kit.models()) + const value = await kit.refresh() assert.equal(kit.modelsSpawns.length, before + 1, `${label}:没有发起刷新`) - assert.ok(ms < FAST_BUDGET_MS, `${label}:耗时 ${Math.round(ms)}ms`) assert.ok(value["gemini-9-test"], `${label}:动态独有型号被静态表冲掉`) await kit.finishChildren() await settle(kit) } kit.modelsBehavior = { stdout: modelsOutput([...BASE_MODEL_ROWS, ["gemini-10-new-high", "G10 (High)"], ["gemini-10-new-low", "G10 (Low)"]]) } - kit.clock.advance(CATALOG_TTL_MS) - const recovered = await kit.models() + const recovered = await kit.refresh() assert.ok(recovered["gemini-10-new"], "恢复成功后没有换成新目录") assert.equal(recovered["gemini-9-test"], undefined, "成功刷新应整体替换为新目录") }) @@ -1056,7 +1154,7 @@ const ORCH_ROWS = [ test("Orchestrator 不列出,点名它的请求得 400 并指向它实际会跑的型号;Hydrogen 等有 limit", async () => { await withKit({ modelsBehavior: { stdout: modelsOutput(ORCH_ROWS) }, offeredModels: ORCH_ROWS }, async (kit) => { - await kit.models() + await kit.refresh() await settle(kit) const models = await kit.models() for (const id of ["gemini-pro-orchestrator", "gemini-pro-orchestrator-g1-pro"]) assert.equal(models[id], undefined, `列出了 ${id}`) @@ -1231,36 +1329,38 @@ test("a session's update that loses models doesn't overwrite the account's offer { const own = await ask(kit, "gemini-4-hydrogen"); assert.equal(own.status, 200, own.text) } const saved = JSON.parse(fs.readFileSync(file, "utf8")).byAgy[own].offered.map(m => m.id) assert.ok(saved.some(id => id.startsWith("gemini-4-carbon")) && saved.some(id => id.startsWith("gemini-4-neon")), saved.join(",")) - // asked again: the next listing probes agy acp before the hour is up - // (the request's own agy stays open, so this waits on the plugin's - // warming, not on every child) + // in doubt, and not asked apart from a turn (12-03): the listing starts + // no agy acp, keeps Carbon, and Carbon's own session says update = null const probes = kit.acpSpawns.filter(spawn => spawn.args.length === 1).length - kit.clock.advance(60_000) - await kit.models() - await kit.plugin.provider.warming?.() - await settle(kit) - assert.equal(kit.acpSpawns.filter(spawn => spawn.args.length === 1).length, probes + 1, "the offer in doubt wasn't asked again") + kit.clock.advance(60 * 60_000) assert.ok((await kit.models())["gemini-4-carbon"]) + await kit.plugin.provider.warming?.() + assert.equal(kit.acpSpawns.filter(spawn => spawn.args.length === 1).length, probes, "a listing asked agy acp") const carbon = await ask(kit, "gemini-4-carbon") assert.equal(carbon.status, 200, carbon.text) + assert.ok((await kit.models())["gemini-4-carbon"]) }) }) -test("a model the offer lacks but agy models lists has the offer asked again before it is turned away (plugins#1804)", async () => { +test("a model the offer lacks but agy models lists goes on to its own session before it is turned away (plugins#1804)", async () => { let offer = PRO_1804_SHORT await withKit({ modelsBehavior: { stdout: modelsOutput(PRO_1804) }, offeredModels: () => offer }, async (kit) => { - await kit.models() + await kit.refresh() await warmed(kit) await kit.models() seedProPeer(kit) const probes = () => kit.acpSpawns.filter(spawn => spawn.args.length === 1).length - // the offer was short; agy acp offers Carbon again now + // the offer was short; agy acp offers Carbon again now: the request + // goes on and its own session says so, with no agy acp of its own offer = PRO_1804 let before = probes() + let turns = kit.acpSpawns.length const carbon = await ask(kit, "gemini-4-carbon") assert.equal(carbon.status, 200, carbon.text) - assert.equal(probes(), before + 1, "asked agy acp once") + assert.equal(probes(), before, "asked agy acp apart from the turn") + assert.equal(kit.acpSpawns.length, turns + 1) + assert.ok((await kit.models())["gemini-4-carbon"]) // short again (a session opened on the account says so): within five // minutes it isn't asked again, and the request is turned away @@ -1272,26 +1372,35 @@ test("a model the offer lacks but agy models lists has the offer asked again bef assert.match(JSON.parse(soon.text).error.message, /unavailable to this agy account; another signed-in agy account lists it/) assert.equal(probes(), before, "asked again within five minutes") - // after five minutes it is asked again, and still short: turned away + // after five minutes it goes on again, and its session, still short, + // turns it away kit.clock.advance(5 * 60_000) before = probes() + turns = kit.acpSpawns.length const later = await ask(kit, "gemini-4-neon") assert.equal(later.status, 400, later.text) - assert.equal(probes(), before + 1) + assert.match(JSON.parse(later.text).error.message, /gemini-4-neon is unavailable to this agy account; another signed-in agy account lists it/) + assert.equal(probes(), before) + assert.equal(kit.acpSpawns.length, turns + 1) }) }) -test("a saved offer in doubt is marked fell back while agy acp is asked again (plugins#1804)", async () => { +test("an offer in doubt is marked fell back while a refresh asks agy acp again (plugins#1804)", async () => { await withKit({ modelsBehavior: { stdout: modelsOutput(PRO_1804) }, offeredModels: PRO_1804 }, async (kit) => { - await kit.models() + await kit.refresh() await warmed(kit) assert.equal((await kit.models())[FELL_BACK], undefined) - // the offer's hour is up and the probe takes its time + // agy models lists something else now: the offer is in doubt while the + // refresh's agy acp takes its time + kit.modelsBehavior = { stdout: modelsOutput(PRO_1804_SHORT) } kit.sessionNewDelayMs = 1_500 - kit.clock.advance(OFFERED_TTL_MS) + const spawns = kit.acpSpawns.length + const refreshing = kit.refresh() + for (let i = 0; i < 200 && kit.acpSpawns.length === spawns; i++) await sleep(10) + assert.equal(kit.acpSpawns.length, spawns + 1, "the refresh didn't ask agy acp") const stale = await kit.models() - assert.ok(kit.children.size > 0, "no probe running") - assert.equal(stale[FELL_BACK], true, "an offer past its hour, served while agy acp is asked, wasn't marked fell back") + assert.equal(stale[FELL_BACK], true, "an offer in doubt, served while agy acp is asked, wasn't marked fell back") + await refreshing await warmed(kit) assert.equal((await kit.models())[FELL_BACK], undefined) }) @@ -1485,20 +1594,26 @@ test("静态目录与探测前只有 Gemini 的目录都标为 fell back,账 assertFallbackPresent(first) assert.equal(first[FELL_BACK], true, "冷启动的静态目录没标 fell back") await warmed(kit) - const listed = await kit.models() - assertClaudeListed(listed, "热身后的 models()") + // agy models 列出的(还没有会话说开放哪些)就是账号的目录:没有在问的,不标 + assert.equal((await kit.models())[FELL_BACK], undefined, "账号自己的目录标成了 fell back") + const listed = await kit.refresh() + assertClaudeListed(listed, "刷新后的 models()") assert.equal(listed[FELL_BACK], undefined, "账号自己的目录标成了 fell back") }) }) -test("agy models 答了、探测还没答时只有 Gemini 的目录标 fell back", async () => { +test("刷新时 agy models 答了、agy acp 还没答,只有 Gemini 的目录标 fell back", async () => { await withKit({ modelsBehavior: DYNAMIC_OK, sessionNewDelayMs: SLOW_MS, offeredModels: OFFERED_CLAUDE }, async (kit) => { + const refreshing = kit.refresh() + for (let i = 0; i < 300 && kit.acpSpawns.length === 0; i++) await sleep(10) + assert.equal(kit.acpSpawns.length, 1, "刷新没问 agy acp") const first = await kit.models() assert.ok(!Object.keys(first).some(id => id.startsWith("claude-")), Object.keys(first).join(",")) - assert.equal(first[FELL_BACK], true, "探测前只有 Gemini 的目录没标 fell back") + assert.equal(first[FELL_BACK], true, "问 agy acp 时只有 Gemini 的目录没标 fell back") + await refreshing await warmed(kit) const listed = await kit.models() - assertClaudeListed(listed, "探测后的 models()") + assertClaudeListed(listed, "问过以后的 models()") assert.equal(listed[FELL_BACK], undefined) }) }) @@ -1533,11 +1648,17 @@ test("#3501 Google 拒了账号:models() 说出原因,不给静态目录冒 assert.match(error.message, /valid license/) assert.match(error.message, /\/logout.*\/login/) assert.match(error.message, /AGY_ADC_AUTH/) - // agy 又能列出了(重新登录、换了地区):恢复正常目录 - kit.modelsBehavior = DYNAMIC_OK - kit.clock.advance(CATALOG_TTL_MS) + // 被拒的账号不自己再问(12-03):一天后列目录也不起 agy + const spawned = kit.modelsSpawns.length + kit.clock.advance(24 * 60 * 60 * 1000) await kit.models().catch(() => {}) await warmed(kit) + assert.equal(kit.modelsSpawns.length, spawned, "被拒的账号又问了 agy models") + assert.equal(kit.acpSpawns.length, 0) + // agy 又能列出了(重新登录、换了地区),用户刷新:恢复正常目录 + kit.modelsBehavior = DYNAMIC_OK + await kit.refresh().catch(() => {}) + await warmed(kit) assert.ok((await kit.models())["gemini-9-test"], "agy 能列出后仍报拒绝") }) }) @@ -1681,12 +1802,12 @@ test("#1229 每个账号列自己开放的型号,互不覆盖", async () => { const token = path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "accounts", "otheracct1", ".gemini", "antigravity-cli", "antigravity-oauth-token") fs.mkdirSync(path.dirname(token), { recursive: true }) fs.writeFileSync(token, JSON.stringify({ token: { access_token: "test-access", refresh_token: "test-refresh", expiry: "0001-01-01T00:00:00Z" } })) - const own = () => kit.plugin.provider.models() - const other = () => kit.plugin.provider.models(undefined, { auth: otherAuth }) - await own() + const own = (ctx) => kit.plugin.provider.models(undefined, ctx) + const other = (ctx) => kit.plugin.provider.models(undefined, { ...ctx, auth: otherAuth }) + await own({ refresh: true }) await warmed(kit) assertClaudeListed(await own(), "默认账号") - await other() + await other({ refresh: true }) await warmed(kit) const otherList = await other() assert.ok(otherList["gemini-4-argon"]) @@ -1711,51 +1832,68 @@ const PRO_OFFERED = [["gemini-3.8-flash", "Gemini 3.8 Flash"], ["claude-sonnet-4 const ULTRA_ROWS = [["gemini-4-carbon-high", "Gemini 4 Carbon (High)"], ["gemini-4-carbon-low", "Gemini 4 Carbon (Low)"], ...PRO_ROWS] const ULTRA_OFFERED = [["gemini-4-carbon-high", "Gemini 4 Carbon (High)"], ["gemini-4-carbon-low", "Gemini 4 Carbon (Low)"], ...PRO_OFFERED] -test("shenggxhz 换到 Ultra 账号后重启:保存的旧开放型号不挡住 Gemini 4,agy 回答后重新探测", async () => { +test("shenggxhz 换到 Ultra 账号后重启:保存的旧目录照旧用、不问 agy;刷新或一个请求的会话就列出 Gemini 4", async () => { const shared = fs.mkdtempSync(path.join(os.tmpdir(), "agy-catalog-ultra-")) try { const agy = path.join(shared, process.platform === "win32" ? "agy.exe" : "agy") fs.writeFileSync(agy, "#!/bin/sh\nexit 99\n", { mode: 0o755 }) const env = { XDG_STATE_HOME: path.join(shared, "state") } await withKit({ agyPath: agy, env, modelsBehavior: { stdout: modelsOutput(PRO_ROWS) }, offeredModels: PRO_OFFERED }, async (kit) => { - await kit.models() + await kit.refresh() await warmed(kit) const pro = await kit.models() assert.ok(pro["claude-sonnet-4-6"]) assert.equal(pro["gemini-4-carbon"], undefined) }) - await withKit({ agyPath: agy, env, modelsBehavior: { stdout: modelsOutput(ULTRA_ROWS) }, offeredModels: ULTRA_OFFERED }, async (kit) => { - await kit.models() + const saved = fs.readFileSync(path.join(shared, "state", "magpie-agy-bridge", "models.json"), "utf8") + const ultraKit = { agyPath: agy, env, modelsBehavior: { stdout: modelsOutput(ULTRA_ROWS) }, offeredModels: ULTRA_OFFERED } + await withKit(ultraKit, async (kit) => { + assert.ok((await kit.models())["claude-sonnet-4-6"]) await warmed(kit) - const ultra = await kit.models() - assert.ok(ultra["gemini-4-carbon"], `Ultra 的 Gemini 4 Carbon 没列出:${ids(ultra).join(", ")}`) - assert.equal(kit.acpSpawns.length, 1, "保存的开放型号要在这次运行里再问一次 agy acp") + assert.equal(kit.acpSpawns.length + kit.modelsSpawns.length, 0, "重启后问了 agy") + const ultra = await kit.refresh() + assert.ok(ultra["gemini-4-carbon"], `刷新后 Ultra 的 Gemini 4 Carbon 没列出:${ids(ultra).join(", ")}`) + assert.equal(kit.acpSpawns.length, 1) + }) + // 不刷新:保存的 Pro 开放型号不挡住 Carbon 的请求,它的会话说了就列出 + fs.writeFileSync(path.join(shared, "state", "magpie-agy-bridge", "models.json"), saved) + await withKit(ultraKit, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.text("ok") + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } } + } + const parsed = await readSse(await kit.request(baseBody({ model: "agy-cli/gemini-4-carbon", tools: [], messages: [{ role: "user", content: "hi" }] }))) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + // agy models 还没列过它,所以按会话给的档位名列出,刷新后归成一个型号 + const after = await kit.models() + assert.ok(after["gemini-4-carbon"] || after["gemini-4-carbon-high"], `会话说了以后 Carbon 没列出:${ids(after).join(", ")}`) + assert.equal(kit.modelsSpawns.length, 0) + assert.equal(kit.acpSpawns.length, 1, "只有请求自己的 agy acp") }) } finally { fs.rmSync(shared, { recursive: true, force: true }) } }) -test("shenggxhz 运行中换了账号:agy models 列表变了就重新探测开放型号", async () => { +test("shenggxhz 运行中换了账号:刷新时 agy models 列表变了,开放型号也重新问;之后不按时间重问", async () => { await withKit({ modelsBehavior: { stdout: modelsOutput(PRO_ROWS) }, offeredModels: PRO_OFFERED }, async (kit) => { - await kit.models() + await kit.refresh() await warmed(kit) assert.equal((await kit.models())["gemini-4-carbon"], undefined) assert.equal(kit.acpSpawns.length, 1) kit.modelsBehavior = { stdout: modelsOutput(ULTRA_ROWS) } kit.offeredModels = ULTRA_OFFERED - kit.clock.advance(CATALOG_TTL_MS) - await kit.models() + await kit.refresh() await warmed(kit) const after = await kit.models() assert.ok(after["gemini-4-carbon"], `换账号后 Gemini 4 Carbon 没列出:${ids(after).join(", ")}`) - assert.equal(kit.acpSpawns.length, 2, "列表变了该再探测一次") - // 列表没变,但开放型号到了 TTL:再探测一次,确认开放的还是同一批。 - kit.clock.advance(OFFERED_TTL_MS) + assert.equal(kit.acpSpawns.length, 2, "刷新该再问一次") + kit.clock.advance(7 * 24 * 60 * 60 * 1000) await kit.models() await warmed(kit) - assert.equal(kit.acpSpawns.length, 3, "到了开放型号的 TTL 应当再探测一次") - assert.ok((await kit.models())["gemini-4-carbon"], "重探测后仍应列出 Gemini 4 Carbon") + assert.equal(kit.acpSpawns.length, 2, "按时间又问了 agy acp") + assert.equal(kit.modelsSpawns.length, 2, "按时间又问了 agy models") + assert.ok((await kit.models())["gemini-4-carbon"]) }) }) @@ -1887,9 +2025,17 @@ test("config names the provider, keeping the user's own name", async () => { const row = registry.plugins.find((p) => p.providers?.includes("agy-cli")) assert.equal(cfg.provider["agy-cli"].name, row.name) assert.equal(cfg.provider["agy-cli"].npm, kit.plugin.provider.npm) + assert.equal(cfg.provider["agy-cli"].searches, undefined) const own = { provider: { "agy-cli": { name: "My agy", npm: "x", options: { x: 1 } } } } await kit.plugin.config(own) assert.deepEqual(own.provider["agy-cli"], { name: "My agy", npm: "x", options: { x: 1 } }) + const toggle = kit.plugin.auth.options?.find((o) => o.key === "hosted_search") + assert.ok(toggle, "auth.options declares hosted_search switch") + assert.equal(toggle.default, false) + assert.ok(toggle.label.length <= 60) + assert.ok(toggle.description.length <= 300) + for (const v of Object.values(toggle.labels || {})) assert.ok(v.length <= 60) + for (const v of Object.values(toggle.descriptions || {})) assert.ok(v.length <= 300) }) }) diff --git a/test/conversation-key.mjs b/test/conversation-key.mjs index cdd1538..e358d3e 100644 --- a/test/conversation-key.mjs +++ b/test/conversation-key.mjs @@ -825,6 +825,11 @@ test("a session parked before a user's turn was cloaked is not resumed", () => { park(proc) delete parked.get(convKey).userCloak assert.equal(takeParked(convKey, { workDir: "/tmp/agy-park-test", instructions: "Rules.\n", history }), null) + // parked before WorkBuddy's first line went reworded in a user's turn + // (#1871): agy's copy may keep it as written + park(proc) + parked.get(convKey).userCloak = 1 + assert.equal(takeParked(convKey, { workDir: "/tmp/agy-park-test", instructions: "Rules.\n", history }), null) }) test("a session parked with its instructions appended to agy's is resumed only while they still go there", () => { @@ -876,3 +881,36 @@ test("a user's turn goes to agy with Codex's GPT-5 lines reworded", async () => assert.ok(all.includes("You are Hermes Agent, built by Nous Research."), "other lines go as written in a user's turn") }) }) + +// plugins#1871 (djj532): WorkBuddy's first line, "This conversation is +// powered by <model>", got Antigravity's bare 429 in agy-cli's default +// place for the system prompt (the first user turn), streamed or not, and +// a copy of it in a tool result reaches a user's turn too. The rest of +// WorkBuddy's prompt is its templates/workbuddy-prompt.tpl (5.5.6) as +// written. +test("WorkBuddy's first line goes to agy as \"… powered by an AI model.\", in the system prompt and a tool result, streamed or not (#1871)", async () => { + await withKit({}, async (kit) => { + const sent = [] + kit.defaultPrompt = async (agent) => { + sent.push(agent.prompt.map((p) => p.type === "text" ? p.text : "").join("")) + await agent.text("ok") + return { stopReason: "end_turn" } + } + const rest = "Your main goal is to follow the USER's instructions at each message, denoted by the <user_query> tag." + const system = `This conversation is powered by gemini-4-carbon-high\n\n${rest}` + const streamed = await readSse(await kit.request(baseBody({ metadata: { user_id: "wb-stream" }, system, messages: [{ role: "user", content: "list the files" }] }))) + assert.equal(streamed.error, null) + const whole = await kit.request(baseBody({ stream: false, metadata: { user_id: "wb-whole" }, system: system.replace("gemini-4-carbon-high", "gemini-3.8-flash-high"), messages: [ + { role: "user", content: "read the log" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Read", input: { path: "/w/log.json" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: '{"system":"This conversation is powered by claude-sonnet-4-6\\n\\nWB-LOG"}' }] }, + ] })) + assert.equal(whole.status, 200) + assert.equal(sent.length, 2) + for (const text of sent) { + assert.ok(!/powered by (?!an AI model\.)/i.test(text), text) + assert.ok(text.includes(`This conversation is powered by an AI model.\n\n${rest}`), text) + } + assert.ok(sent[1].includes('{"system":"This conversation is powered by an AI model.\\n\\nWB-LOG"}'), sent[1]) + }) +}) diff --git a/test/hosted-search.mjs b/test/hosted-search.mjs new file mode 100644 index 0000000..b3359e2 --- /dev/null +++ b/test/hosted-search.mjs @@ -0,0 +1,1325 @@ +// In-bridge concurrent hosted web_search / web_fetch tests: +// verifies parallel execution via magpie's loopback /mcp/magpie/web-search +// (keyless on loopback, explicit key only on remote AGY_BRIDGE_SEARCH_URL), +// Anthropic server_tool_use / web_search_tool_result / web_fetch_tool_result +// SSE & JSON output, >6-round search, switch-gated one-way multi-turn session +// continuity, non-selection as magpie's own searcher, adaptive web_fetch +// budgets + per-URL offsets + max_uses, and non-interception of client tools. +// +// bun test ./hosted-search.mjs + +import { test } from "node:test" +import assert from "node:assert/strict" +import fs from "node:fs" +import http from "node:http" +import os from "node:os" +import path from "node:path" +import { + HOSTED_SEARCH_OPTION, + buildHostedTool, + domainAllowed, + executeHostedWebFetch, + executeHostedWebSearch, + extractFetchTasksInfo, + extractSearchQueries, + fitMagpieFetchOutput, + formatSearchOutcomesForModel, + hostedSearchEnabled, + isSiteOnlyQuery, + magpieConfigDirs, + matchesDomain, + parseMagpieSearchText, + resolveSearchApiKey, + resolveSearchEndpoint, +} from "../hosted-search.mjs" +import { + READ_TOOL, + baseBody, + continueWithToolResults, + createBridgeKit, + readJson, + readSse, +} from "./testkit.mjs" + +const HOSTED_WEB_SEARCH = { type: "web_search_20250305", name: "web_search" } +const HOSTED_WEB_FETCH = { type: "web_fetch_20250910", name: "web_fetch" } + +async function startMockMcpServer(handler) { + let inFlight = 0 + let maxInFlight = 0 + const calls = [] + const server = http.createServer(async (req, res) => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) + const toolName = body?.params?.name + const toolArgs = body?.params?.arguments ?? {} + inFlight++ + if (inFlight > maxInFlight) maxInFlight = inFlight + calls.push({ + auth: req.headers.authorization || "", + userAgent: req.headers["user-agent"] || "", + toolName, + toolArgs, + at: Date.now(), + }) + try { + const outcome = await handler({ toolName, toolArgs, req, body }) + if (outcome?.httpStatus && outcome.httpStatus !== 200) { + res.writeHead(outcome.httpStatus, { "Content-Type": "application/json" }) + res.end(JSON.stringify({ error: { message: outcome.message || "mock error" } })) + return + } + res.writeHead(200, { "Content-Type": "application/json" }) + res.end(JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + result: { + content: [{ type: "text", text: outcome?.text ?? "" }], + isError: Boolean(outcome?.isError), + }, + })) + } finally { + inFlight-- + } + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + const { port } = server.address() + return { + url: `http://127.0.0.1:${port}/mcp/magpie/web-search`, + calls, + get maxInFlight() { return maxInFlight }, + close: () => new Promise((resolve) => server.close(resolve)), + } +} + +async function withKit(options, fn) { + const { defaultOff = false, ...rest } = options || {} + const env = defaultOff + ? { ...(rest.env || {}) } + : { AGY_BRIDGE_HOSTED_SEARCH: "1", ...(rest.env || {}) } + const kit = await createBridgeKit({ ...rest, env }) + try { return await fn(kit) } finally { await kit.dispose() } +} + +// ---------------------------------------------------------------- Pure unit tests + +test("parseMagpieSearchText parses em-dash titles, bare URLs and multiline snippets", () => { + const sample = [ + "1. What’s New In Python 3.13 — Python 3.15.2 documentation — https://docs.python.org/3/whatsnew/3.13.html", + "Python 3.13 was released on October 7, 2024.", + "Second line of snippet.", + "", + "2. https://example.org/plain", + "Bare URL snippet.", + ].join("\r\n") + const hits = parseMagpieSearchText(sample) + assert.equal(hits.length, 2) + assert.equal(hits[0].title, "What’s New In Python 3.13 — Python 3.15.2 documentation") + assert.equal(hits[0].url, "https://docs.python.org/3/whatsnew/3.13.html") + assert.match(hits[0].snippet, /October 7, 2024[\s\S]*Second line/) + assert.equal(hits[1].title, "example.org") + assert.equal(hits[1].url, "https://example.org/plain") + assert.equal(hits[1].snippet, "Bare URL snippet.") + assert.deepEqual(parseMagpieSearchText("No results found."), []) +}) + +test("extractSearchQueries and extractFetchTasksInfo deduplicate, trim, and enforce hard batch caps (10 and 3) ignoring env overrides", () => { + assert.deepEqual( + extractSearchQueries({ queries: [" Alpha ", "beta", "ALPHA", ""], query: "gamma" }), + ["Alpha", "beta", "gamma"], + ) + const prevSearchBatch = process.env.AGY_BRIDGE_SEARCH_MAX_BATCH + const prevFetchBatch = process.env.AGY_BRIDGE_FETCH_MAX_BATCH + process.env.AGY_BRIDGE_SEARCH_MAX_BATCH = "50" + process.env.AGY_BRIDGE_FETCH_MAX_BATCH = "20" + try { + const fifteen = Array.from({ length: 15 }, (_, i) => `q-${i + 1}`) + assert.equal(extractSearchQueries({ queries: fifteen }).length, 10) + const sixUrls = Array.from({ length: 6 }, (_, i) => `https://example.com/${i + 1}`) + assert.equal(extractFetchTasksInfo({ urls: sixUrls }).items.length, 3) + } finally { + if (prevSearchBatch === undefined) delete process.env.AGY_BRIDGE_SEARCH_MAX_BATCH + else process.env.AGY_BRIDGE_SEARCH_MAX_BATCH = prevSearchBatch + if (prevFetchBatch === undefined) delete process.env.AGY_BRIDGE_FETCH_MAX_BATCH + else process.env.AGY_BRIDGE_FETCH_MAX_BATCH = prevFetchBatch + } + assert.deepEqual(extractSearchQueries({}), []) +}) + +test("matchesDomain & domainAllowed handle subdomains, paths and blocked domains", () => { + assert.equal(matchesDomain("https://docs.python.org/3/library/os.html", "python.org"), true) + assert.equal(matchesDomain("https://docs.python.org/3/library/os.html", "docs.python.org/3/"), true) + assert.equal(matchesDomain("https://docs.python.org/2/library/os.html", "docs.python.org/3/"), false) + assert.equal(domainAllowed("https://docs.python.org/3/a", ["python.org"], ["bad.python.org"]), true) + assert.equal(domainAllowed("https://bad.python.org/x", ["python.org"], ["bad.python.org"]), false) +}) + +test("buildHostedTool matches hosted web_search/web_fetch only when input_schema is absent", () => { + const ws = buildHostedTool(HOSTED_WEB_SEARCH) + assert.equal(ws?.config.kind, "web_search") + assert.equal(ws?.mcpTool.name, "web_search") + assert.ok(ws?.mcpTool.inputSchema.properties.queries) + assert.ok(ws?.mcpTool.inputSchema.properties.query) + + const wf = buildHostedTool(HOSTED_WEB_FETCH) + assert.equal(wf?.config.kind, "web_fetch") + assert.equal(wf?.mcpTool.name, "web_fetch") + + // Client custom tool named web_search with input_schema MUST NOT be intercepted + assert.equal(buildHostedTool({ + type: "web_search_20250305", + name: "web_search", + input_schema: { type: "object", properties: { q: { type: "string" } } }, + }), null) + assert.equal(buildHostedTool(READ_TOOL), null) +}) + +test("hostedSearchEnabled defaults off and respects env > magpie option > pluginOptions", () => { + assert.equal(hostedSearchEnabled({}), false) + assert.equal(hostedSearchEnabled({}, { magpieOption: true }), true) + assert.equal(hostedSearchEnabled({}, { magpieOption: false, pluginOptions: { hosted_search: true } }), false) + assert.equal(hostedSearchEnabled({}, { pluginOptions: { hosted_search: true } }), true) + assert.equal(hostedSearchEnabled({}, { pluginOptions: { hostedSearch: true } }), true) + assert.equal(hostedSearchEnabled({ AGY_BRIDGE_HOSTED_SEARCH: "1" }, { magpieOption: false }), true) + assert.equal(hostedSearchEnabled({ AGY_BRIDGE_HOSTED_SEARCH: "0" }, { magpieOption: true }), false) +}) + +test("resolveSearchEndpoint and resolveSearchApiKey send no key on loopback, ignore caller-keys.json, and follow ~/.config/magpie", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-hosted-cfg-")) + try { + const magpieDir = path.join(dir, "magpie") + fs.mkdirSync(magpieDir, { recursive: true }) + fs.writeFileSync(path.join(magpieDir, "gateway.json"), JSON.stringify({ addr: "[::]:4567" })) + // Even if caller-keys.json has shared/restricted keys, the plugin MUST NEVER read or send them. + fs.writeFileSync(path.join(magpieDir, "caller-keys.json"), JSON.stringify([ + { id: "1", name: "Alice's laptop (shared)", secret: "sk-alice", mcp: ["none"] }, + { id: "2", name: "mine", secret: "sk-mine" }, + ])) + assert.equal(resolveSearchEndpoint({ XDG_CONFIG_HOME: dir }), "http://127.0.0.1:4567/mcp/magpie/web-search") + // Loopback NEVER sends any key, even if env keys or caller-keys.json exist + assert.equal(resolveSearchApiKey({ + XDG_CONFIG_HOME: dir, + AGY_BRIDGE_SEARCH_KEY: "sk-explicit", + MAGPIE_API_KEY: "sk-api", + MAGPIE_GATEWAY_KEY: "sk-gw", + }), "") + + // Remote AGY_BRIDGE_SEARCH_URL sends ONLY explicit AGY_BRIDGE_SEARCH_KEY (never caller-keys.json or MAGPIE_API_KEY) + assert.equal(resolveSearchApiKey({ + XDG_CONFIG_HOME: dir, + AGY_BRIDGE_SEARCH_URL: "https://remote.example.com/mcp", + MAGPIE_API_KEY: "sk-api", + MAGPIE_GATEWAY_KEY: "sk-gw", + }), "") + assert.equal(resolveSearchApiKey({ + XDG_CONFIG_HOME: dir, + AGY_BRIDGE_SEARCH_URL: "https://remote.example.com/mcp", + AGY_BRIDGE_SEARCH_KEY: "sk-remote-explicit", + }), "sk-remote-explicit") + + // MAGPIE_PUBLIC_URL and non-loopback auto-discovered hosts are rejected + assert.equal( + resolveSearchEndpoint({ MAGPIE_PUBLIC_URL: "https://public.example.com/", XDG_CONFIG_HOME: dir }), + "http://127.0.0.1:4567/mcp/magpie/web-search", + ) + assert.equal( + resolveSearchEndpoint({ MAGPIE_ADDR: "0.0.0.0:3425", XDG_CONFIG_HOME: dir }), + "http://127.0.0.1:3425/mcp/magpie/web-search", + ) + assert.equal( + resolveSearchEndpoint({ MAGPIE_ADDR: "public.example.com:3425", XDG_CONFIG_HOME: dir }), + "http://127.0.0.1:4567/mcp/magpie/web-search", + ) + const remoteCfg = path.join(dir, "remote-cfg") + fs.mkdirSync(remoteCfg, { recursive: true }) + fs.writeFileSync(path.join(remoteCfg, "gateway.json"), JSON.stringify({ addr: "https://evil.example.com" })) + fs.writeFileSync(path.join(remoteCfg, "settings.json"), JSON.stringify({ listen: "192.168.1.50:8080" })) + assert.equal( + resolveSearchEndpoint({ MAGPIE_CONFIG_DIR: remoteCfg }), + "http://127.0.0.1:3425/mcp/magpie/web-search", + ) + + // Magpie keeps installed config in ~/.config/magpie across platforms (stale Application Support / APPDATA must not shadow it) + const fakeHome = path.join(dir, "home") + const dotConfigMagpie = path.join(fakeHome, ".config", "magpie") + const staleMac = path.join(fakeHome, "Library", "Application Support", "magpie") + const staleWin = path.join(fakeHome, "AppData", "Roaming", "magpie") + fs.mkdirSync(dotConfigMagpie, { recursive: true }) + fs.mkdirSync(staleMac, { recursive: true }) + fs.mkdirSync(staleWin, { recursive: true }) + fs.writeFileSync(path.join(dotConfigMagpie, "settings.json"), JSON.stringify({ port: 18086 })) + fs.writeFileSync(path.join(staleMac, "settings.json"), JSON.stringify({ port: 19999 })) + fs.writeFileSync(path.join(staleWin, "settings.json"), JSON.stringify({ port: 29999 })) + const cfgDirs = magpieConfigDirs({ HOME: fakeHome, APPDATA: path.join(fakeHome, "AppData", "Roaming") }) + assert.ok(cfgDirs.includes(dotConfigMagpie)) + assert.ok(!cfgDirs.includes(staleMac)) + assert.ok(!cfgDirs.includes(staleWin)) + assert.equal( + resolveSearchEndpoint({ HOME: fakeHome, APPDATA: path.join(fakeHome, "AppData", "Roaming") }), + "http://127.0.0.1:18086/mcp/magpie/web-search", + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test("formatSearchOutcomesForModel compacts large 8-query batches under agy spill limit while keeping every query", () => { + const bigSnippet = "Detailed release notes and changelog information. ".repeat(40) + const outcomes = Array.from({ length: 8 }, (_, i) => { + const q = `topic-${i + 1}` + const hits = Array.from({ length: 4 }, (_, h) => ({ + title: `Doc ${i + 1}-${h + 1}`, + url: `https://example.com/${q}/${h + 1}`, + snippet: bigSnippet, + })) + return { query: q, ok: true, text: bigSnippet.repeat(4), hits } + }) + const formatted = formatSearchOutcomesForModel(outcomes, 7500) + assert.ok(Buffer.byteLength(formatted, "utf8") <= 7500) + for (let i = 1; i <= 8; i++) { + assert.match(formatted, new RegExp(`=== Search query ${i}: topic-${i} ===`)) + assert.match(formatted, new RegExp(`https://example\\.com/topic-${i}/1`)) + } +}) + +test("fitMagpieFetchOutput computes exact Unicode code-point (Go rune) offsets across 4-byte emojis and CJK", () => { + // 1500 pairs of "🚀中" = 3000 Go runes (4500 UTF-16 code units, 10500 UTF-8 bytes > 7500) + const fullRunes = Array.from("🚀中".repeat(1500)) + const chunk1Body = fullRunes.slice(0, 2000).join("") + const raw1 = `URL: https://emoji.example/doc\nTitle: Emoji Doc\n\n${chunk1Body}\n\n[1000 more characters: call web_fetch with offset=2000 to read on]` + const fitted1 = fitMagpieFetchOutput(raw1, "https://emoji.example/doc", 100, 3500, "web_fetch") + assert.ok(Buffer.byteLength(fitted1, "utf8") <= 3500) + const m = /\[(\d+) more characters: call web_fetch with url="https:\/\/emoji\.example\/doc" and offset=(\d+) to read on\]$/.exec(fitted1) + assert.ok(m, `expected continuation footer in: ${fitted1.slice(-160)}`) + const reportedRemaining = Number(m[1]) + const nextOffset = Number(m[2]) + const keptRunes = nextOffset - 100 + assert.ok(keptRunes > 0 && keptRunes < 2000) + assert.equal(reportedRemaining, 3000 - keptRunes) + // Verify exact character alignment: kept body ends right before fullRunes[keptRunes] + const bodyOnly = fitted1 + .replace(/^URL: [^\n]*\nTitle: [^\n]*\n\n/, "") + .replace(/\n\n\[\d+ more characters:[^\]]+\]$/, "") + assert.equal(Array.from(bodyOnly).length, keptRunes) + assert.equal(bodyOnly + fullRunes.slice(keptRunes).join(""), fullRunes.join("")) +}) + +// ---------------------------------------------------------------- End-to-end bridge tests + +test("10-query batch web_search runs at most 2 MCP calls in flight at once and sends no key on loopback", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => { + await new Promise((r) => setTimeout(r, 35)) + const q = toolArgs.query + return { text: `1. Result for ${q} — https://example.com/${encodeURIComponent(q)}\nSnippet about ${q}.` } + }) + const cfgDir = fs.mkdtempSync(path.join(os.tmpdir(), "agy-hosted-key-")) + fs.mkdirSync(path.join(cfgDir, "magpie"), { recursive: true }) + fs.writeFileSync(path.join(cfgDir, "magpie", "caller-keys.json"), JSON.stringify([ + { id: "1", name: "Alice's laptop (shared)", secret: "sk-alice", mcp: ["none"] }, + ])) + try { + await withKit({ + env: { AGY_BRIDGE_SEARCH_URL: mock.url, XDG_CONFIG_HOME: cfgDir, MAGPIE_API_KEY: "sk-env" }, + }, async (kit) => { + const queries = Array.from({ length: 10 }, (_, i) => `topic-${i + 1}`) + let mcpReply = null + kit.defaultPrompt = async (agent) => { + await agent.thought("Let me search all 10 topics in one batch.") + const [reply] = await agent.tools([["web_search", { queries, count: 3 }]]) + mcpReply = reply + await agent.text("All 10 topics summarized.") + return { stopReason: "end_turn", usage: { inputTokens: 100, outputTokens: 50, totalTokens: 150 } } + } + + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1) + assert.equal(mock.calls.length, 10) + assert.equal(mock.maxInFlight, 2, `expected at most 2 in-flight MCP calls on a 10-query batch, got maxInFlight=${mock.maxInFlight}`) + // Loopback MUST NOT send any Authorization header + assert.ok(mock.calls.every((c) => c.auth === ""), "loopback MCP calls must send no Authorization header") + assert.ok(mock.calls.every((c) => c.toolArgs.count === 3)) + assert.equal(mcpReply?.result?.isError, false) + assert.match(mcpReply?.result?.content?.[0]?.text || "", /=== Search query 10: topic-10 ===/) + assert.deepEqual(parsed.usage.server_tool_use, { web_search_requests: 10 }) + }) + } finally { + await mock.close() + fs.rmSync(cfgDir, { recursive: true, force: true }) + } +}) + +test("more than 6 sequential web_search rounds run in 1 live agy session without cutoff", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Hit ${toolArgs.query} — https://news.example/${toolArgs.query}\nDetails.`, + })) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.defaultPrompt = async (agent) => { + for (let i = 1; i <= 8; i++) { + const [reply] = await agent.tools([["web_search", { query: `round-${i}` }]]) + assert.equal(reply?.result?.isError, false) + } + await agent.text("Completed all 8 rounds.") + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(parsed.content.filter((b) => b.type === "server_tool_use").length, 8) + assert.equal(parsed.content.filter((b) => b.type === "web_search_tool_result").length, 8) + assert.deepEqual(parsed.usage.server_tool_use, { web_search_requests: 8 }) + assert.equal(kit.acpSpawns.length, 1) + }) + } finally { + await mock.close() + } +}) + +test("multi-turn conversation keeps live agy session when client strips server blocks the live session already has, and never when switch is off or blocks are unseen", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Docs — https://docs.example/${toolArgs.query}\nInfo.`, + })) + try { + // 1a. Switch ON (Kelivo-style client that strips server blocks across turns): reuses 1 live session + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.prompts = [ + async (agent) => { + await agent.tools([["web_search", { query: "q1" }]]) + await agent.text("First answer.") + return { stopReason: "end_turn" } + }, + async (agent) => { + await agent.tools([["web_search", { query: "q2" }]]) + await agent.text("Second answer.") + return { stopReason: "end_turn" } + }, + async (agent) => { + await agent.text("Third answer.") + return { stopReason: "end_turn" } + }, + ] + const body1 = baseBody({ tools: [HOSTED_WEB_SEARCH], messages: [{ role: "user", content: "q1?" }] }) + await readSse(await kit.request(body1)) + assert.equal(kit.acpSpawns.length, 1) + + const body2 = { + ...body1, + messages: [ + ...body1.messages, + { role: "assistant", content: "First answer." }, + { role: "user", content: "follow up?" }, + ], + } + const p2 = await readSse(await kit.request(body2)) + assert.equal(p2.content.find((b) => b.type === "text")?.text, "Second answer.") + assert.equal(kit.acpSpawns.length, 1, "stripped history on turn 2 must reuse live agy session") + + const body3 = { + ...body1, + messages: [ + ...body2.messages, + { role: "assistant", content: "Second answer." }, + { role: "user", content: "one more?" }, + ], + } + const p3 = await readSse(await kit.request(body3)) + assert.equal(p3.content.find((b) => b.type === "text")?.text, "Third answer.") + assert.equal(kit.acpSpawns.length, 1, "stripped history on turn 3 must also reuse live agy session") + }) + + // 1b. Switch ON (client that echoes full server_tool_use + web_search_tool_result blocks): reuses 1 live session + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.prompts = [ + async (agent) => { + await agent.tools([["web_search", { query: "full-1" }]]) + await agent.text("Full first.") + return { stopReason: "end_turn" } + }, + async (agent) => { + await agent.text("Full second.") + return { stopReason: "end_turn" } + }, + ] + const body1 = baseBody({ tools: [HOSTED_WEB_SEARCH], messages: [{ role: "user", content: "full?" }] }) + const p1 = await readSse(await kit.request(body1)) + assert.equal(kit.acpSpawns.length, 1) + const p2 = await readSse(await kit.request({ + ...body1, + messages: [ + ...body1.messages, + { role: "assistant", content: p1.content }, + { role: "user", content: "next?" }, + ], + })) + assert.equal(p2.content.find((b) => b.type === "text")?.text, "Full second.") + assert.equal(kit.acpSpawns.length, 1, "full echoed server blocks must reuse live agy session") + }) + + // 2. Switch OFF (yetone's blocker #3): turn 1 plain answer; turn 2 history adds external + // server_tool_use + web_search_tool_result -> MUST open a new session and replay the search result! + await withKit({ defaultOff: true }, async (kit) => { + const seenPrompts = [] + kit.defaultPrompt = async (agent) => { + seenPrompts.push(agent.prompt.map((p) => p.text || "").join("\n")) + await agent.text(seenPrompts.length === 1 ? "Plain reply." : "Answered with replayed search.") + return { stopReason: "end_turn" } + } + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content: "hi" }] }))) + assert.equal(kit.acpSpawns.length, 1) + + const turn2 = await readSse(await kit.request(baseBody({ + messages: [ + { role: "user", content: "hi" }, + { + role: "assistant", + content: [ + { type: "server_tool_use", id: "srvtoolu_ext1", name: "web_search", input: { query: "ext" } }, + { + type: "web_search_tool_result", + tool_use_id: "srvtoolu_ext1", + content: [{ type: "web_search_result", url: "https://e.x/", title: "EX", encrypted_content: "" }], + }, + { type: "text", text: "Plain reply." }, + ], + }, + { role: "user", content: "next" }, + ], + }))) + assert.equal(turn2.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 2, "switch-off path must open a new session and replay unseen search blocks") + assert.ok(seenPrompts.slice(1).some((p) => p.includes("https://e.x/")), "replayed prompt must include https://e.x/") + }) + + // 2b. Switch OFF: even if expectedMessages held replayed server blocks, dropping them on the next + // turn MUST NOT match via sameHistoryUpToServerTools while the switch is off (matches main). + await withKit({ defaultOff: true }, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.text("Switch-off reply.") + return { stopReason: "end_turn" } + } + const prevAssistant = [ + { type: "server_tool_use", id: "srvtoolu_prev", name: "web_search", input: { query: "prev" } }, + { + type: "web_search_tool_result", + tool_use_id: "srvtoolu_prev", + content: [{ type: "web_search_result", url: "https://prev.example/", title: "Prev", encrypted_content: "" }], + }, + { type: "text", text: "Earlier answer." }, + ] + await readSse(await kit.request(baseBody({ + messages: [ + { role: "user", content: "q0" }, + { role: "assistant", content: prevAssistant }, + { role: "user", content: "q1" }, + ], + }))) + assert.equal(kit.acpSpawns.length, 1) + + await readSse(await kit.request(baseBody({ + messages: [ + { role: "user", content: "q0" }, + { role: "assistant", content: "Earlier answer." }, + { role: "user", content: "q1" }, + { role: "assistant", content: "Switch-off reply." }, + { role: "user", content: "q2" }, + ], + }))) + assert.equal(kit.acpSpawns.length, 2, "switch-off path must never apply sameHistoryUpToServerTools") + }) + + // 3. Switch ON with unseen server blocks in client history: MUST ALSO open a new session and replay! + await withKit({ env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + const seenPrompts = [] + kit.defaultPrompt = async (agent) => { + seenPrompts.push(agent.prompt.map((p) => p.text || "").join("\n")) + await agent.text(seenPrompts.length === 1 ? "No search on turn 1." : "Saw replayed search.") + return { stopReason: "end_turn" } + } + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [{ role: "user", content: "hello" }], + }))) + assert.equal(kit.acpSpawns.length, 1) + + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [ + { role: "user", content: "hello" }, + { + role: "assistant", + content: [ + { type: "server_tool_use", id: "srvtoolu_unseen", name: "web_search", input: { query: "unseen" } }, + { + type: "web_search_tool_result", + tool_use_id: "srvtoolu_unseen", + content: [{ type: "web_search_result", url: "https://e.x/unseen", title: "Unseen", encrypted_content: "" }], + }, + { type: "text", text: "No search on turn 1." }, + ], + }, + { role: "user", content: "next" }, + ], + }))) + assert.equal(kit.acpSpawns.length, 2, "even with switch on, unseen server blocks in client history must trigger replay") + assert.ok(seenPrompts.slice(1).some((p) => p.includes("https://e.x/unseen"))) + }) + + // 4. Switch ON with MIXED messages (one assistant message dropped blocks the session saw, + // while another assistant message carries unseen server blocks): MUST ALSO open a new session! + await withKit({ env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + let turnNo = 0 + const seenPrompts = [] + kit.defaultPrompt = async (agent) => { + turnNo++ + seenPrompts.push(agent.prompt.map((p) => p.text || "").join("\n")) + if (turnNo === 1) { + await agent.text("Plain reply 1.") + } else if (turnNo === 2) { + await agent.tools([["web_search", { query: "mixed-turn2" }]]) + await agent.text("Searched reply 2.") + } else { + await agent.text("Replayed reply 3.") + } + return { stopReason: "end_turn" } + } + // Turn 1: no search + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [{ role: "user", content: "q1" }], + }))) + // Turn 2: reuses session, executes hosted search + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [ + { role: "user", content: "q1" }, + { role: "assistant", content: [{ type: "text", text: "Plain reply 1." }] }, + { role: "user", content: "q2" }, + ], + }))) + assert.equal(kit.acpSpawns.length, 1) + + // Turn 3: assistant #1 injects unseen server blocks while assistant #2 drops Turn 2's server blocks + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [ + { role: "user", content: "q1" }, + { + role: "assistant", + content: [ + { type: "server_tool_use", id: "srvtoolu_mixed_unseen", name: "web_search", input: { query: "unseen-mixed" } }, + { + type: "web_search_tool_result", + tool_use_id: "srvtoolu_mixed_unseen", + content: [{ type: "web_search_result", url: "https://e.x/mixed-unseen", title: "Mixed Unseen", encrypted_content: "" }], + }, + { type: "text", text: "Plain reply 1." }, + ], + }, + { role: "user", content: "q2" }, + { role: "assistant", content: [{ type: "text", text: "Searched reply 2." }] }, + { role: "user", content: "q3" }, + ], + }))) + assert.equal(kit.acpSpawns.length, 2, "mixed dropped + unseen server blocks must refuse session reuse and replay") + assert.ok(seenPrompts.slice(2).some((p) => p.includes("https://e.x/mixed-unseen"))) + }) + } finally { + await mock.close() + } +}) + +test("stream:false JSON response reconstructs server_tool_use.input and usage.server_tool_use", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Page ${toolArgs.query} — https://site.test/${toolArgs.query}\nBody.`, + })) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.tools([["web_search", { queries: ["alpha", "beta"] }]]) + await agent.text("Done.") + return { stopReason: "end_turn" } + } + const res = await kit.request(baseBody({ stream: false, tools: [HOSTED_WEB_SEARCH] })) + const parsed = await readJson(res) + const uses = parsed.content.filter((b) => b.type === "server_tool_use") + assert.deepEqual(uses.map((u) => u.input), [{ query: "alpha" }, { query: "beta" }]) + assert.equal(parsed.content.filter((b) => b.type === "web_search_tool_result").length, 2) + assert.deepEqual(parsed.usage.server_tool_use, { web_search_requests: 2 }) + }) + } finally { + await mock.close() + } +}) + +test("max_uses, domain filters, and partial MCP errors emit proper Anthropic error blocks", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => { + if (toolArgs.query === "fail-me") return { httpStatus: 429, message: "rate limited" } + return { + text: [ + "1. Allowed — https://docs.python.org/3/ok\nGood doc.", + "2. Disallowed — https://spam.example.com/bad\nNoise.", + ].join("\n\n"), + } + }) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.defaultPrompt = async (agent) => { + const [reply] = await agent.tools([["web_search", { queries: ["ok-q", "fail-me", "over-limit"] }]]) + assert.equal(reply?.result?.isError, false) + assert.match(reply?.result?.content?.[0]?.text || "", /docs\.python\.org/) + assert.doesNotMatch(reply?.result?.content?.[0]?.text || "", /spam\.example\.com/) + await agent.text("Handled partial errors.") + return { stopReason: "end_turn" } + } + const tool = { ...HOSTED_WEB_SEARCH, max_uses: 2, allowed_domains: ["docs.python.org"] } + const parsed = await readSse(await kit.request(baseBody({ tools: [tool] }))) + const results = parsed.content.filter((b) => b.type === "web_search_tool_result") + assert.equal(results.length, 3) + + const okRes = results.find((r) => Array.isArray(r.content)) + assert.equal(okRes.content.length, 1) + assert.equal(okRes.content[0].url, "https://docs.python.org/3/ok") + + const errCodes = results.filter((r) => !Array.isArray(r.content)).map((r) => r.content.error_code).sort() + assert.deepEqual(errCodes, ["max_uses_exceeded", "too_many_requests"]) + // Only successful searches are billed; both max_uses_exceeded and failed + // searches (e.g. 429/timeout/5xx) must NOT increment web_search_requests. + assert.deepEqual(parsed.usage.server_tool_use, { web_search_requests: 1 }) + }) + } finally { + await mock.close() + } +}) + +test("custom client web_search tool with input_schema is NOT intercepted by hosted search", async () => { + const customSearch = { + name: "web_search", + description: "Client custom search", + input_schema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] }, + } + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + const [reply] = await agent.tools([["web_search", { query: "client-owned" }]]) + await agent.text("Got: " + reply.result.content[0].text) + return { stopReason: "end_turn" } + } + const body1 = baseBody({ tools: [customSearch] }) + const p1 = await readSse(await kit.request(body1)) + assert.equal(p1.stopReason, "tool_use") + assert.equal(p1.content.filter((b) => b.type === "tool_use").length, 1) + assert.equal(p1.content.filter((b) => b.type === "server_tool_use").length, 0) + + const body2 = continueWithToolResults(body1, p1, () => "client result") + const p2 = await readSse(await kit.request(body2)) + assert.equal(p2.stopReason, "end_turn") + assert.equal(p2.content.find((b) => b.type === "text")?.text, "Got: client result") + }) +}) + +test("mixed hosted web_search + client Read tool in one turn completes cleanly in 1 session", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Spec — https://spec.test/${toolArgs.query}\nSpec body.`, + })) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.defaultPrompt = async (agent) => { + const [searchReply] = await agent.tools([["web_search", { query: "api-spec" }]]) + assert.equal(searchReply?.result?.isError, false) + const [readReply] = await agent.tools([["Read", { path: "README.md" }]]) + await agent.text("Combined: " + readReply.result.content[0].text) + return { stopReason: "end_turn" } + } + const body1 = baseBody({ tools: [HOSTED_WEB_SEARCH, READ_TOOL] }) + const p1 = await readSse(await kit.request(body1)) + assert.equal(p1.stopReason, "tool_use") + assert.equal(p1.content.filter((b) => b.type === "server_tool_use").length, 1) + assert.equal(p1.content.filter((b) => b.type === "web_search_tool_result").length, 1) + assert.equal(p1.content.filter((b) => b.type === "tool_use").length, 1) + assert.deepEqual(p1.usage.server_tool_use, { web_search_requests: 1 }) + + // Client sends back Read tool_result (even stripping server blocks!) + const toolUse = p1.content.find((b) => b.type === "tool_use") + const body2 = { + ...body1, + messages: [ + ...body1.messages, + { role: "assistant", content: [toolUse] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: toolUse.id, content: "readme contents" }] }, + ], + } + const p2 = await readSse(await kit.request(body2)) + assert.equal(p2.stopReason, "end_turn") + assert.equal(p2.content.find((b) => b.type === "text")?.text, "Combined: readme contents") + assert.equal(kit.acpSpawns.length, 1) + }) + } finally { + await mock.close() + } +}) + +test("hosted web_fetch_20250910 executes parallel fetches and emits web_fetch_tool_result", async () => { + const mock = await startMockMcpServer(async ({ toolName, toolArgs }) => { + assert.equal(toolName, "web_fetch") + return { text: `Markdown content of ${toolArgs.url}` } + }) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.defaultPrompt = async (agent) => { + const [reply] = await agent.tools([["web_fetch", { urls: ["https://a.example", "https://b.example"] }]]) + assert.equal(reply?.result?.isError, false) + await agent.text("Fetched both.") + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_FETCH] }))) + assert.equal(parsed.stopReason, "end_turn") + const uses = parsed.content.filter((b) => b.type === "server_tool_use") + const results = parsed.content.filter((b) => b.type === "web_fetch_tool_result") + assert.equal(uses.length, 2) + assert.equal(results.length, 2) + assert.equal(results[0].content.type, "web_fetch_result") + assert.deepEqual(parsed.usage.server_tool_use, { web_fetch_requests: 2 }) + }) + } finally { + await mock.close() + } +}) + +test("isSiteOnlyQuery catches boolean/quoted/uppercase site:-only forms while preserving valid site: queries", () => { + for (const bad of [ + "site:reuters.com", + "SITE:reuters.com", + "(site:a.com OR site:b.com)", + "\"site:a.com\"", + "site:\"a.com\"", + "-site:spam.com AND site:docs.org", + "site:a.com | site:b.com", + "NOT site:example.com", + " ( site:a.com ) ", + ]) { + assert.equal(isSiteOnlyQuery(bad), true, `expected site-only rejection for: ${bad}`) + } + for (const good of [ + "site:docs.python.org 3.13", + "site:reuters.com 黄金价格", + "(site:a.com OR site:b.com) inflation", + "python or rust", + "site:sec.gov 10-K", + ]) { + assert.equal(isSiteOnlyQuery(good), false, `expected valid query for: ${good}`) + } +}) + +test("site:-only queries are rejected before max_uses and Tavily; valid site: queries pass verbatim", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Official — https://docs.python.org/3/whatsnew/3.13.html\nReleased Oct 2024.`, + })) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + kit.defaultPrompt = async (agent) => { + const [reply] = await agent.tools([[ + "web_search", + { queries: ["(site:a.com OR site:b.com)", "\"SITE:c.com\"", "site:docs.python.org 3.13"] }, + ]]) + assert.equal(reply?.result?.isError, false) + assert.match(reply?.result?.content?.[0]?.text || "", /only site: filter/) + await agent.text("Done with valid site search.") + return { stopReason: "end_turn" } + } + const tool = { ...HOSTED_WEB_SEARCH, max_uses: 1 } + const parsed = await readSse(await kit.request(baseBody({ tools: [tool] }))) + assert.equal(mock.calls.length, 1, "site-only queries must never reach MCP/Tavily") + assert.equal(mock.calls[0].toolArgs.query, "site:docs.python.org 3.13", "valid site: query must be forwarded verbatim") + assert.match(mock.calls[0].userAgent, /^agy-cli\//) + assert.doesNotMatch(mock.calls[0].userAgent, /^magpie-/i) + + const results = parsed.content.filter((b) => b.type === "web_search_tool_result") + assert.equal(results.length, 3) + const errors = results.filter((r) => !Array.isArray(r.content)).map((r) => r.content.error_code) + assert.deepEqual(errors, ["invalid_tool_input", "invalid_tool_input"]) + assert.deepEqual(parsed.usage.server_tool_use, { web_search_requests: 1 }) + }) + } finally { + await mock.close() + } +}) + +test("default maxBatch=10 and default max_uses=20 cap oversized batches, show budget hints, and escalate on 2nd rejection", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Hit ${toolArgs.query} — https://example.com/${toolArgs.query}\nSummary.`, + })) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + const replies = [] + kit.defaultPrompt = async (agent) => { + const [r1] = await agent.tools([["web_search", { queries: Array.from({ length: 15 }, (_, i) => `q${i + 1}`) }]]) + replies.push(r1.result.content[0].text) + const [r2] = await agent.tools([["web_search", { queries: Array.from({ length: 7 }, (_, i) => `b${i + 1}`) }]]) + replies.push(r2.result.content[0].text) + const [r3] = await agent.tools([["web_search", { queries: Array.from({ length: 5 }, (_, i) => `c${i + 1}`) }]]) + replies.push(r3.result.content[0].text) + const [r4] = await agent.tools([["web_search", { query: "extra-1" }]]) + replies.push(r4.result.content[0].text) + const [r5] = await agent.tools([["web_search", { query: "extra-2" }]]) + replies.push(r5.result.content[0].text) + await agent.text("Final answer after hitting default 20 cap.") + return { stopReason: "end_turn" } + } + + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(mock.calls.length, 20) + assert.deepEqual(parsed.usage.server_tool_use, { web_search_requests: 20 }) + assert.match(replies[0], /capped at 10 queries per call \(5 omitted\)/) + assert.match(replies[1], /\[Search budget: 3 searches remaining for this turn\.\]/) + assert.match(replies[2], /\[Search budget: 0 searches remaining for this turn\./) + assert.match(replies[3], /max_uses_exceeded/) + assert.match(replies[4], /^STOP calling web_search\./) + }) + } finally { + await mock.close() + } +}) + +test("hosted web_search clears deniedSinceCall so an empty ending uses normal retry, not tool-off prompt", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Hit — https://example.com/${toolArgs.query}\nBody.`, + })) + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + const seenPrompts = [] + kit.prompts = [ + async (agent) => { + seenPrompts.push(agent.prompt[0]?.text || "") + await agent.requestPermission({ toolCallId: "native-1", title: "run_command" }) + await agent.tools([["web_search", { query: "status" }]]) + await agent.thought("thinking without final text") + return { stopReason: "end_turn" } + }, + async (agent) => { + seenPrompts.push(agent.prompt[0]?.text || "") + await agent.text("Recovered answer.") + return { stopReason: "end_turn" } + }, + ] + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(parsed.content.find((b) => b.type === "text")?.text, "Recovered answer.") + assert.equal(seenPrompts.length, 2) + assert.doesNotMatch(seenPrompts[1], /built-in tool|turned off/i) + }) + } finally { + await mock.close() + } +}) + +test("web_fetch enforces max_uses, rejects shared offset across multiple URLs, and supports per-URL offsets", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `URL: ${toolArgs.url}\n\nSlice from ${toolArgs.offset} (max=${toolArgs.max_chars})`, + })) + try { + assert.equal(extractFetchTasksInfo({ urls: ["https://a.test", "https://b.test"], offset: 1100 }).multiUrlOffsetError, true) + assert.equal( + extractFetchTasksInfo({ + requests: [{ url: "https://x.test", offset: 0 }], + urls: ["https://a.test", "https://b.test"], + offset: 1100, + }).multiUrlOffsetError, + true, + ) + + await withKit({ env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + const replies = [] + kit.defaultPrompt = async (agent) => { + // 1. Shared non-zero offset with multiple URLs is rejected without spending max_uses + const [bad] = await agent.tools([["web_fetch", { urls: ["https://a.test", "https://b.test"], offset: 1100 }]]) + assert.equal(bad.result.isError, true) + replies.push(bad.result.content[0].text) + + // 2. Per-URL `requests` runs 2 independent offsets, plus a 3rd URL rejected by max_uses: 2 + const [batch] = await agent.tools([["web_fetch", { + requests: [ + { url: "https://a.test", offset: 1100 }, + { url: "https://b.test", offset: 0 }, + { url: "https://c.test", offset: 0 }, + ], + }]]) + assert.equal(batch.result.isError, false) + replies.push(batch.result.content[0].text) + + // 3. Subsequent calls after max_uses is spent get max_uses_exceeded, then firmer STOP + const [over1] = await agent.tools([["web_fetch", { url: "https://d.test" }]]) + replies.push(over1.result.content[0].text) + const [over2] = await agent.tools([["web_fetch", { url: "https://e.test" }]]) + replies.push(over2.result.content[0].text) + + await agent.text("Done.") + return { stopReason: "end_turn" } + } + + const tool = { ...HOSTED_WEB_FETCH, max_uses: 2 } + const parsed = await readSse(await kit.request(baseBody({ tools: [tool] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(mock.calls.length, 2, "only 2 fetches may reach MCP when max_uses is 2") + assert.deepEqual(mock.calls.map((c) => [c.toolArgs.url, c.toolArgs.offset]), [ + ["https://a.test", 1100], + ["https://b.test", 0], + ]) + assert.match(replies[0], /single URL only/) + assert.match(replies[1], /max_uses_exceeded/) + assert.match(replies[2], /max_uses_exceeded/) + assert.match(replies[3], /^STOP calling web_fetch\./) + + const fetchResults = parsed.content.filter((b) => b.type === "web_fetch_tool_result") + const errCodes = fetchResults.filter((r) => r.content.type === "web_fetch_tool_result_error").map((r) => r.content.error_code) + assert.deepEqual(errCodes, ["invalid_input", "max_uses_exceeded", "max_uses_exceeded", "max_uses_exceeded"]) + assert.deepEqual(parsed.usage.server_tool_use, { web_fetch_requests: 2 }) + }) + } finally { + await mock.close() + } +}) + +test("web_fetch gives 20,000-char budget when client has Read tool, and 7500-byte exact-offset slices when Read is absent", async () => { + const englishPage = "A".repeat(25_000) + const emojiCjkRunes = Array.from("🚀中".repeat(2_000)) // 4000 runes + const mock = await startMockMcpServer(async ({ toolArgs }) => { + const src = toolArgs.url.includes("emoji") ? emojiCjkRunes : Array.from(englishPage) + const start = toolArgs.offset || 0 + const end = Math.min(start + toolArgs.max_chars, src.length) + const slice = src.slice(start, end).join("") + const rem = src.length - end + const tail = rem > 0 ? `\n\n[${rem} more characters: call web_fetch with offset=${end} to read on]` : "" + return { text: `URL: ${toolArgs.url}\nTitle: Long Page\n\n${slice}${tail}` } + }) + try { + // 1. Client WITH Read tool (Claude Code / OpenCode): full 20,000-char budget, 3-URL batch gets 6666 each + await withKit({ env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + const replies = [] + kit.defaultPrompt = async (agent) => { + const [r1] = await agent.tools([["web_fetch", { url: "https://long.test/doc", max_chars: 20000 }]]) + replies.push(r1.result.content[0].text) + const [r2] = await agent.tools([["web_fetch", { urls: ["https://u1.test", "https://u2.test", "https://u3.test"] }]]) + replies.push(r2.result.content[0].text) + const [r3] = await agent.tools([["web_fetch", { + requests: [ + { url: "https://m1.test", max_chars: 100000 }, + { url: "https://m2.test", max_chars: 100000 }, + { url: "https://m3.test", max_chars: 100000 }, + ], + }]]) + replies.push(r3.result.content[0].text) + await agent.text("Read full long page.") + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_FETCH, READ_TOOL] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(mock.calls[0].toolArgs.max_chars, 20000) + assert.deepEqual(mock.calls.slice(1, 4).map((c) => c.toolArgs.max_chars), [6666, 6666, 6666]) + assert.deepEqual(mock.calls.slice(4, 7).map((c) => c.toolArgs.max_chars), [33333, 33333, 33333], "one web_fetch call must cap total max_chars across URLs at <= 100,000") + assert.ok(replies[0].length > 20000, "full 20,000-char slice returned unclipped when Read tool is present") + assert.match(replies[0], /\[5000 more characters: call web_fetch with offset=20000 to read on\]/) + assert.deepEqual(parsed.usage.server_tool_use, { web_fetch_requests: 7 }) + }) + + // 2. Client WITHOUT Read tool (Kelivo): ~7200 ASCII chars or ~2100 emoji+CJK runes in 1 MCP call (<= 7500 bytes), exact offset + const beforeInline = mock.calls.length + await withKit({ env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + let asciiText = "" + let part1 = "" + let part2 = "" + kit.defaultPrompt = async (agent) => { + const [ra] = await agent.tools([["web_fetch", { url: "https://long.test/ascii" }]]) + asciiText = ra.result.content[0].text + const [re1] = await agent.tools([["web_fetch", { url: "https://emoji.test/cjk", offset: 0 }]]) + part1 = re1.result.content[0].text + const m = /offset=(\d+) to read on\]$/.exec(part1) + assert.ok(m, "expected exact continuation offset") + const [re2] = await agent.tools([["web_fetch", { url: "https://emoji.test/cjk", offset: Number(m[1]) }]]) + part2 = re2.result.content[0].text + await agent.text("Continued cleanly.") + return { stopReason: "end_turn" } + } + const readUrlTool = { + name: "read_url", + description: "Fetch URL metadata without local filesystem access.", + input_schema: { type: "object", properties: { url: { type: "string" } }, required: ["url"] }, + } + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_FETCH, readUrlTool] }))) + assert.equal(parsed.stopReason, "end_turn") + // Exactly 3 upstream calls (1 per tool invocation, zero retries!) + assert.equal(mock.calls.length - beforeInline, 3) + assert.ok(Buffer.byteLength(asciiText, "utf8") <= 7500) + assert.ok(asciiText.length > 7000, `expected >7000 ASCII chars inline, got ${asciiText.length}`) + assert.ok(Buffer.byteLength(part1, "utf8") <= 7500) + assert.ok(Buffer.byteLength(part2, "utf8") <= 7500) + + const stripWrap = (s) => s + .replace(/^URL: [^\n]*\nTitle: [^\n]*\n\n/, "") + .replace(/\n\n\[\d+ more characters:[^\]]+\]$/, "") + const joined = stripWrap(part1) + stripWrap(part2) + assert.equal(joined, emojiCjkRunes.slice(0, Array.from(joined).length).join(""), "continuation must have zero skipped or duplicated characters") + assert.deepEqual(parsed.usage.server_tool_use, { web_fetch_requests: 3 }) + }) + } finally { + await mock.close() + } +}) + +test("agy-cli never marks models as Magpie searchers (no searchTool/searches), latches config switch, and refuses x-magpie-caller-agent: agy-cli loop", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Toggle Hit — https://example.com/${encodeURIComponent(toolArgs.query)}\nResult.`, + })) + try { + let enabled = true + const pluginInput = { + magpie: { + option: (provider, key) => (provider === "agy-cli" && key === HOSTED_SEARCH_OPTION ? enabled : undefined), + }, + } + await withKit({ defaultOff: true, pluginInput, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + const cfg = { provider: {} } + await kit.plugin.config(cfg) + assert.equal(cfg.provider["agy-cli"].searches, true) + + // Models MUST NEVER carry searchTool or searches (which would make Magpie pick agy-cli as its own searcher and recurse) + const models = await kit.models() + assert.ok(Object.keys(models).length > 0) + for (const m of Object.values(models)) { + assert.equal(m.searchTool, undefined, `model ${m.id} must not set searchTool`) + assert.equal(m.searches, undefined, `model ${m.id} must not set searches`) + } + + // Refuses recursive loopback hop where Magpie sets user-agent: magpie/<ver> and x-magpie-caller-agent: agy-cli + const spawnsAfterModels = kit.acpSpawns.length + const loopRes = await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }), { + headers: { + "user-agent": "magpie/0.1.5392", + "x-magpie-caller-agent": "agy-cli", + }, + }) + assert.equal(loopRes.status, 400) + const loopErr = await loopRes.json() + assert.doesNotMatch(loopErr?.error?.message || "", /agy-cli:agy/) + assert.equal(kit.acpSpawns.length, spawnsAfterModels) + + // Flipping UI switch off mid-run keeps the load-time latched `true` until restart so active pass-through never breaks + enabled = false + kit.defaultPrompt = async (agent) => { + const [reply] = await agent.tools([["web_search", { query: "latched-on" }]]) + assert.equal(reply.result.isError, false) + await agent.text("Answered while latched.") + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }))) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(mock.calls.length, 1) + + // Explicit AGY_BRIDGE_HOSTED_SEARCH=0 still forces off even when latched ON + kit.env.AGY_BRIDGE_HOSTED_SEARCH = "0" + kit.defaultPrompt = async (agent) => { + await agent.tools([["web_search", { query: "forced-off" }]]) + return { stopReason: "end_turn" } + } + const forcedOff = await readSse(await kit.request(baseBody({ tools: [HOSTED_WEB_SEARCH] }))) + assert.equal(forcedOff.stopReason, "tool_use") + assert.equal(mock.calls.length, 1) + }) + } finally { + await mock.close() + } +}) + +test("multi-turn session stays live when both image-slim placeholder and stripped server_tool blocks occur together", async () => { + const mock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Result — https://example.com/${encodeURIComponent(toolArgs.query)}\nSnippet.`, + })) + const TINY_PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aRX0AAAAASUVORK5CYII=" + try { + await withKit({ promptImages: true, env: { AGY_BRIDGE_SEARCH_URL: mock.url } }, async (kit) => { + let promptIdx = 0 + kit.defaultPrompt = async (agent) => { + promptIdx++ + if (promptIdx === 1) { + await agent.text("Ready for your screenshot.") + return { stopReason: "end_turn" } + } + if (promptIdx === 2) { + await agent.tools([["web_search", { query: "screenshot-topic" }]]) + await agent.text("Turn 2 answer with image and search.") + return { stopReason: "end_turn" } + } + await agent.text("Turn 3 reused live session.") + return { stopReason: "end_turn" } + } + + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [{ role: "user", content: "Start investigation" }], + }))) + assert.equal(kit.acpSpawns.length, 1) + + await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [ + { role: "user", content: "Start investigation" }, + { role: "assistant", content: [{ type: "text", text: "Ready for your screenshot." }] }, + { + role: "user", + content: [ + { type: "image", source: { type: "base64", media_type: "image/png", data: TINY_PNG_B64 } }, + { type: "text", text: "What is in this screenshot?" }, + ], + }, + ], + }))) + assert.equal(kit.acpSpawns.length, 1) + + const turn3 = await readSse(await kit.request(baseBody({ + tools: [HOSTED_WEB_SEARCH], + messages: [ + { role: "user", content: "Start investigation" }, + { role: "assistant", content: [{ type: "text", text: "Ready for your screenshot." }] }, + { + role: "user", + content: [ + { type: "text", text: "[An earlier image was omitted here to keep this request within the model's image limit.]" }, + { type: "text", text: "What is in this screenshot?" }, + ], + }, + { role: "assistant", content: [{ type: "text", text: "Turn 2 answer with image and search." }] }, + { role: "user", content: "Tell me more." }, + ], + }))) + assert.equal(turn3.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1, "must reuse live session when both image-slim and stripped search blocks occur") + assert.equal(turn3.content.find((b) => b.type === "text")?.text, "Turn 3 reused live session.") + }) + } finally { + await mock.close() + } +}) + +test("batch concurrency is per-call (<=2 each, not global), starts per-task timeouts on execution, stops on abort/batch-deadline without billing unstarted items, and clamps default max_uses <= 20", async () => { + const wsConfig = buildHostedTool(HOSTED_WEB_SEARCH).config + const wfConfig = buildHostedTool(HOSTED_WEB_FETCH).config + + // 1. web_fetch 3-URL batch runs at most 2 in flight at once; two concurrent sessions do NOT block each other (maxInFlight === 4 across 2 sessions, <= 2 per session) + const fetchMock = await startMockMcpServer(async ({ toolArgs }) => { + await new Promise((r) => setTimeout(r, 40)) + return { text: `URL: ${toolArgs.url}\n\nBody` } + }) + try { + const fRes = await executeHostedWebFetch( + wfConfig, + { urls: ["https://u1.test", "https://u2.test", "https://u3.test"] }, + { env: { AGY_BRIDGE_SEARCH_URL: fetchMock.url } }, + ) + assert.equal(fRes.mcpResult.isError, false) + assert.equal(fetchMock.calls.length, 3) + assert.equal(fetchMock.maxInFlight, 2, "3-URL web_fetch batch must cap in-flight MCP calls at 2") + } finally { + await fetchMock.close() + } + + const dualMock = await startMockMcpServer(async ({ toolArgs }) => { + await new Promise((r) => setTimeout(r, 50)) + return { text: `1. Hit — https://example.com/${toolArgs.query}\nSnippet.` } + }) + try { + const [b1, b2] = await Promise.all([ + executeHostedWebSearch(wsConfig, { queries: ["s1-a", "s1-b", "s1-c", "s1-d"] }, { env: { AGY_BRIDGE_SEARCH_URL: dualMock.url } }), + executeHostedWebSearch(wsConfig, { queries: ["s2-a", "s2-b", "s2-c", "s2-d"] }, { env: { AGY_BRIDGE_SEARCH_URL: dualMock.url } }), + ]) + assert.equal(b1.mcpResult.isError, false) + assert.equal(b2.mcpResult.isError, false) + assert.equal(dualMock.maxInFlight, 4, "two separate sessions may each run 2 in flight (4 total) without global queueing") + } finally { + await dualMock.close() + } + + // 2. Per-task timeout starts when a task begins (4 queries x 45ms across 2 waves = ~90ms > 70ms per-call timeout, all 4 succeed) + const waveMock = await startMockMcpServer(async ({ toolArgs }) => { + await new Promise((r) => setTimeout(r, 45)) + return { text: `1. Wave — https://example.com/${toolArgs.query}\nOk.` } + }) + try { + const wRes = await executeHostedWebSearch( + wsConfig, + { queries: ["w1", "w2", "w3", "w4"] }, + { env: { AGY_BRIDGE_SEARCH_URL: waveMock.url, AGY_BRIDGE_SEARCH_TIMEOUT_MS: "75" } }, + ) + assert.equal(wRes.mcpResult.isError, false) + assert.equal(wRes.usedDelta, 4) + assert.doesNotMatch(wRes.mcpResult.content[0].text, /failed/) + } finally { + await waveMock.close() + } + + // 3. Cancellation (AbortController) prevents queued Wave 2+ items from starting or charging max_uses + const abortController = new AbortController() + let seenBeforeAbort = 0 + const abortMock = await startMockMcpServer(async () => { + seenBeforeAbort++ + if (seenBeforeAbort === 2) setTimeout(() => abortController.abort(), 10) + await new Promise((r) => setTimeout(r, 50)) + return { text: "1. Hit — https://example.com/x\nOk." } + }) + try { + const aRes = await executeHostedWebSearch( + wsConfig, + { queries: ["a1", "a2", "a3", "a4", "a5", "a6"] }, + { signal: abortController.signal, env: { AGY_BRIDGE_SEARCH_URL: abortMock.url } }, + ) + assert.equal(abortMock.calls.length, 2, "queued queries must not start after abort") + assert.equal(aRes.usedDelta, 2, "unstarted cancelled queries must not spend max_uses") + } finally { + await abortMock.close() + } + + // 4. Batch wall-clock deadline stops remaining queued items and does NOT bill them against max_uses + const deadlineMock = await startMockMcpServer(async ({ toolArgs }) => { + await new Promise((r) => setTimeout(r, 65)) + return { text: `1. Hit — https://example.com/${toolArgs.query}\nOk.` } + }) + try { + let reservedCount = 0 + const dRes = await executeHostedWebSearch( + wsConfig, + { queries: ["d1", "d2", "d3", "d4", "d5", "d6"] }, + { + onReserve: (n) => { reservedCount += n }, + batchDeadlineMs: 50, + env: { AGY_BRIDGE_SEARCH_URL: deadlineMock.url }, + }, + ) + assert.equal(deadlineMock.calls.length, 2, "waves after batch deadline must not start") + assert.equal(dRes.usedDelta, 2, "unstarted items past batch deadline must not spend max_uses") + assert.equal(reservedCount, 2) + assert.match(dRes.mcpResult.content[0].text, /batch time limit reached/) + } finally { + await deadlineMock.close() + } + + // 5. AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES can lower within 1..20, but NEVER raise past 20 + const capMock = await startMockMcpServer(async ({ toolArgs }) => ({ + text: `1. Hit — https://example.com/${toolArgs.query}\nOk.`, + })) + try { + const lowered = await executeHostedWebSearch( + wsConfig, + { queries: ["c1", "c2", "c3", "c4", "c5"] }, + { env: { AGY_BRIDGE_SEARCH_URL: capMock.url, AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES: "3" } }, + ) + assert.equal(lowered.usedDelta, 3, "AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES=3 lowers default cap to 3") + + const clamped = await executeHostedWebSearch( + wsConfig, + { queries: ["m1", "m2", "m3"] }, + { usedCount: 19, env: { AGY_BRIDGE_SEARCH_URL: capMock.url, AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES: "200" } }, + ) + assert.equal(clamped.usedDelta, 1, "AGY_BRIDGE_SEARCH_DEFAULT_MAX_USES=200 must clamp at 20 (only 1 left at usedCount=19)") + } finally { + await capMock.close() + } +}) diff --git a/test/image-bytes.mjs b/test/image-bytes.mjs index 0178680..ade69e3 100644 --- a/test/image-bytes.mjs +++ b/test/image-bytes.mjs @@ -5,6 +5,7 @@ import { test } from "node:test" import assert from "node:assert/strict" +import { createHash } from "node:crypto" import { baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" const b64 = (hex, tail = "") => Buffer.concat([Buffer.from(hex, "hex"), Buffer.from(tail)]).toString("base64") @@ -84,3 +85,86 @@ test("a -preview flash id goes to the account's flash model; an -image one does assert.ok(!kit.setModels.slice(before).includes(flash), JSON.stringify(kit.setModels.slice(before))) }) }) + +test("a user image is validated and hashed once per parsed block within a turn and on continuation", async () => { + const largePng = b64("89504e470d0a1a0a0000000d49484452", "x".repeat(2048)) + const kit = await createBridgeKit({ + promptImages: true, + sessionResume: true, + indexTransform: (source) => { + const prelude = + "const __imgCounts = { imageContent: 0, imageDigest: 0 };\n" + + "export function __resetImageCounts() { __imgCounts.imageContent = 0; __imgCounts.imageDigest = 0; }\n" + + "export function __getImageCounts() { return { ...__imgCounts }; }\n" + return prelude + source + .replace("function imageContent(block) {", "function imageContent(block) { __imgCounts.imageContent++;") + .replace("function digest(value) {", `function digest(value) { if (value === ${JSON.stringify(largePng)}) __imgCounts.imageDigest++;`) + }, + }) + try { + kit.defaultPrompt = async (agent) => { await agent.text("ok"); return { stopReason: "end_turn" } } + const firstBody = baseBody({ messages: [{ role: "user", content: [image(largePng), { type: "text", text: "describe" }] }] }) + kit.module.__resetImageCounts() + const first = await readSse(await kit.request(firstBody)) + assert.equal(first.stopReason, "end_turn") + assert.deepEqual(kit.module.__getImageCounts(), { imageContent: 1, imageDigest: 1 }) + + const secondBody = JSON.parse(JSON.stringify({ + ...firstBody, + messages: [ + ...firstBody.messages, + { role: "assistant", content: first.content }, + { role: "user", content: "follow up" }, + ], + })) + kit.module.__resetImageCounts() + const second = await readSse(await kit.request(secondBody)) + assert.equal(second.stopReason, "end_turn") + assert.deepEqual(kit.module.__getImageCounts(), { imageContent: 1, imageDigest: 1 }) + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/prompt").length, 2) + } finally { + await kit.dispose() + } +}) + +test("cached user image parsing and digests invalidate on mutation and isolate callers", async () => { + const kit = await createBridgeKit({ + promptImages: true, + indexTransform: (source) => source + "\nexport { parseUserImage, userImageDigest }\n", + }) + try { + const { parseUserImage, userImageDigest } = kit.module + const sha = (data) => createHash("sha256").update(data).digest("hex") + const block = image(PNG) + + const first = parseUserImage(block) + assert.deepEqual(first, { type: "image", data: PNG, mimeType: "image/png" }) + assert.equal(userImageDigest(block, first.data), sha(PNG)) + + first.mimeType = "mutated" + assert.equal(parseUserImage(block).mimeType, "image/png") + + block.source.data = JPEG + const swapped = parseUserImage(block) + assert.deepEqual(swapped, { type: "image", data: JPEG, mimeType: "image/jpeg" }) + assert.equal(userImageDigest(block, swapped.data), sha(JPEG)) + + block.source.media_type = "image/bmp" + assert.throws(() => parseUserImage(block), /PNG, JPEG, GIF or WebP/) + + block.source.media_type = "image/jpeg" + block.source.type = "url" + assert.throws(() => parseUserImage(block), /other than base64/) + + block.source.type = "base64" + block.source.data = TEXT + assert.throws(() => parseUserImage(block), /not an image/) + assert.throws(() => parseUserImage(block), /not an image/) + + block.source.data = PNG + assert.equal(parseUserImage(block).mimeType, "image/png") + assert.equal(userImageDigest(block, PNG), sha(PNG)) + } finally { + await kit.dispose() + } +}) diff --git a/test/media-input.mjs b/test/media-input.mjs index 7f1bce5..a26d82a 100644 --- a/test/media-input.mjs +++ b/test/media-input.mjs @@ -219,7 +219,7 @@ test("a video to a model other than Gemini is refused before agy", async () => { assert.equal(response.headers.get("x-should-retry"), "false") const body = await response.json() assert.equal(body.error.type, "invalid_request_error") - assert.equal(body.error.message, `agy bridge: video or audio input to ${model} is not supported. Choose a Gemini model`) + assert.equal(body.error.message, `agy bridge: video, audio or PDF input to ${model} is not supported. Choose a Gemini model`) } assert.equal(kit.acpSpawns.length, 0) }) @@ -227,14 +227,57 @@ test("a video to a model other than Gemini is refused before agy", async () => { test("Gemini models take video and audio; Claude and GPT-OSS don't", async () => { await withKit(async (kit) => { - await kit.models() - // the probe session says what agy offers + // the refresh's session says what agy offers + await kit.refresh() for (let i = 0; i < 20 && kit.children.size; i++) await sleep(10) await tick() const models = await kit.models() - assert.deepEqual(models["gemini-4-argon"].capabilities.input, { text: true, image: true, video: true, audio: true }) - assert.deepEqual(models["gemini-3.8-flash"].capabilities.input, { text: true, image: true, video: true, audio: true }) + assert.deepEqual(models["gemini-4-argon"].capabilities.input, { text: true, image: true, video: true, audio: true, pdf: true }) + assert.deepEqual(models["gemini-3.8-flash"].capabilities.input, { text: true, image: true, video: true, audio: true, pdf: true }) assert.deepEqual(models["claude-opus-5-5"].capabilities.input, { text: true, image: true }) assert.equal(models["gpt-oss-120b"].capabilities.input, undefined) }, { offeredModels: BASE_MODEL_ROWS }) }) + +// #1862: a PDF the user attached went back as HTTP 400. agy's read_file and +// view_file hand a PDF to the model as they do an image, so it goes the +// way a video does. +const PDF = Buffer.from("%PDF-1.4\n1 0 obj << /Type /Catalog >> endobj\n%%EOF\n") +const pdf = (bytes, title) => ({ type: "document", ...(title ? { title } : {}), source: { type: "base64", media_type: "application/pdf", data: bytes.toString("base64") } }) + +test("a PDF the user attached goes to agy as a file in the session's folder, read with view_file", async () => { + await withKit(async (kit) => { + const first = baseBody({ messages: [{ role: "user", content: [pdf(PDF, "paper.pdf"), pdf(Buffer.from("%PDF-1.7 untitled")), { type: "text", text: "summarise it" }] }] }) + const response = await kit.request(first) + assert.equal(response.status, 200, await response.clone().text()) + const answer = await reply(response) + const sent = prompts(kit).at(-1) + const attachments = path.join(workspaceOf(kit, sent), "attachments") + const file = path.join(attachments, `${sha256(PDF)}.pdf`) + const untitled = path.join(attachments, `${sha256(Buffer.from("%PDF-1.7 untitled"))}.pdf`) + const text = promptText(sent) + assert.ok(text.includes(`[The user attached a PDF (paper.pdf): ${file}. Read it with your file reading tool before answering.]`), text) + assert.ok(text.includes(`[The user attached a PDF: ${untitled}. Read it with your file reading tool before answering.]`), text) + assert.ok(text.indexOf(file) < text.indexOf("summarise it")) + assert.ok(!text.includes(PDF.toString("base64"))) + assert.deepEqual(fs.readFileSync(file), PDF) + assert.equal(agentTools(kit, sent), WITH_MEDIA) + + // the history sends it again: the same file, nothing new in the turn + const next = { ...first, messages: [...first.messages, answer, { role: "user", content: "and the title?" }] } + await readSse(await kit.request(next)) + assert.equal(kit.acpSpawns.length, 1) + assert.equal(promptText(prompts(kit).at(-1)).includes("attached"), false) + assert.equal(fs.readdirSync(attachments).length, 2) + }) +}) + +test("a PDF to a model other than Gemini is refused before agy", async () => { + await withKit(async (kit) => { + const response = await kit.request(baseBody({ model: "agy-cli/claude-opus-5-5", stream: false, messages: [{ role: "user", content: [ + pdf(PDF, "paper.pdf"), { type: "text", text: "summarise it" }] }] })) + assert.equal(response.status, 400) + assert.equal((await response.json()).error.message, "agy bridge: video, audio or PDF input to claude-opus-5-5 is not supported. Choose a Gemini model") + assert.equal(kit.acpSpawns.length, 0) + }) +}) diff --git a/test/repeat-batch.mjs b/test/repeat-batch.mjs index 644fecc..9d8c847 100644 --- a/test/repeat-batch.mjs +++ b/test/repeat-batch.mjs @@ -1813,11 +1813,45 @@ test("agy's Verification Required ending fails the stream as a no-retry 403 that assert.equal(error.type, "permission_error") assert.equal(error.status, 403) assert.equal(error.noRetry, true) - assert.match(error.message, /this Google account needs to be verified: open the Antigravity app, or run `agy` in a terminal/) + assert.match(error.message, /this Google account needs to be verified, and agy passed on no link/) + assert.match(error.message, /asked on this model request, not at sign-in/) + // a user whose terminal agy answers is not sent there to verify + assert.doesNotMatch(error.message, /run `agy` in a terminal/) assert.ok(!text.includes("⚠"), "no banner reaches the client") }) }) +// 0xiaoge0 on X (12-03, macOS, Codex at high on gemini-4-neon): refused +// with "Verification Required" while `agy` in a terminal, signed in to the +// same account, answered at Medium. agy's log keeps Google's message, and a +// whole body's Help detail carries the link Gemini CLI opens. +test("agy's Verification Required on a model call says Google's logged words, and the Help detail's link", async () => { + const link = "https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv" + const words = "PERMISSION_DENIED (code 403): To continue, verify your account." + const body = `{"error":{"code":403,"message":"To continue, verify your account.","status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED","domain":"cloudcode-pa.googleapis.com"},{"@type":"type.googleapis.com/google.rpc.Help","links":[{"description":"Verify your account","url":"${link.replace(/&/g, "\\u0026")}"},{"description":"Learn more","url":"https://support.google.com/accounts?p=al_alert"}]}]}}` + for (const [logged, linked] of [[words, false], [`${words}: ${body}`, true]]) { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + fs.appendFileSync(agyLogOf(kit), `E1203 10:21:07.481000 6120 errorreport.go:307] agent executor error: generating and executing: ${logged}\n`) + await agent.text(VERIFY) + return { stopReason: "end_turn" } + } + const response = await kit.request(baseBody({ metadata: { user_id: `verify-words-${linked}` }, + messages: [{ role: "user", content: "hello" }], stream: false })) + const reply = await response.json() + assert.equal(response.status, 403) + assert.equal(reply.error.type, "permission_error") + assert.ok(reply.error.message.includes(`Google: "${words}`), reply.error.message) + if (linked) { + assert.ok(reply.error.message.includes(`this Google account needs to be verified: open ${link} in a browser`), reply.error.message) + } else { + assert.match(reply.error.message, /agy passed on no link/) + assert.doesNotMatch(reply.error.message, /run `agy` in a terminal/) + } + }) + } +}) + test("agy's Verification Required ending carries the link agy logged, as a non-stream HTTP 403", async () => { const link = "https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv" await withKit({}, async (kit) => { diff --git a/test/same-opening.mjs b/test/same-opening.mjs index 1f4cc29..2cf0d34 100644 --- a/test/same-opening.mjs +++ b/test/same-opening.mjs @@ -104,6 +104,39 @@ test("a conversation that went on, then opened again from its start, keeps its a assert.equal(rows.at(-1).first_diff, undefined) }) +// plugins#1757: two conversations open the same way, and their answers +// differ only by an id of a key's form (tok-abcdefgh, tok-qrstuvwx), which +// masking's tolerance reads as one key re-shaped (sameTextUpToMasking). The +// first one's next turn is that conversation's, never the second one's +// live session: it replays its own history in a session of its own. +for (const spare of ["0", "1"]) { + test(`a same-opening conversation whose answer differs only by a key-shaped id goes on in its own history (spares ${spare === "1" ? "on" : "off"})`, async () => { + await withKit({ env: { AGY_BRIDGE_SPARE: spare } }, async (kit) => { + const answer = (text) => async (agent) => { + await agent.text(text) + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 4 } } + } + kit.prompts[0] = answer("OK tok-abcdefgh") + kit.prompts[1] = answer("OK tok-qrstuvwx") + kit.defaultPrompt = answer("next") + const first = await readSse(await kit.request(single())) + await readSse(await kit.request(single())) + const opened = calls(kit, "session/new") + assert.equal(opened.length, 2) + const followUp = await readSse(await kit.request({ + ...single(), + messages: [...single().messages, { role: "assistant", content: first.content }, { role: "user", content: "and again" }], + })) + assert.equal(followUp.error, null) + assert.equal(calls(kit, "session/new").length, 3, "the first conversation went on in the second one's session") + const prompt = calls(kit, "session/prompt").at(-1) + const text = (prompt.params?.prompt || []).map((part) => part.text || "").join("") + assert.notEqual(prompt.params.sessionId, calls(kit, "session/prompt")[1].params.sessionId) + assert.ok(text.includes("tok-abcdefgh") && !text.includes("tok-qrstuvwx"), text) + }) + }) +} + test("an agy that can't close a session isn't given a second one while it holds a conversation", async () => { await withKit({ sessionClose: false }, async (kit) => { const body = single() diff --git a/test/smoke.mjs b/test/smoke.mjs index 680c372..f2ba3f4 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -531,7 +531,9 @@ async function handle(message) { if (!fs.existsSync(statePath(params.sessionId))) throw { code: -32602, message: "Conversation Not Found" } prompts = JSON.parse(fs.readFileSync(statePath(params.sessionId), "utf8")).prompts } - session = { id: message.method === "session/new" ? "sess-" + Math.random().toString(36).slice(2, 10) : params.sessionId, prompts } + // letters alone: two ids are always of one key's form, as the + // same-opening checks need them to be (plugins#1757) + session = { id: message.method === "session/new" ? "sess-" + Array.from({ length: 8 }, () => "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)]).join("") : params.sessionId, prompts } model = "gemini-test-medium" await connectIde() log({ @@ -773,9 +775,10 @@ const legacyModel = "agy-cli/gemini-test-low" } { - // models() serves a cached catalog and refreshes it in the background. Point - // AGY_PATH at a copy of the same wrapper so this probe always starts a real - // refresh, wait for it, then restore the original executable. + // models() serves the kept catalog; the user's refresh lists it again and + // asks agy's ACP server what it offers. Point AGY_PATH at a copy of the + // same wrapper so this refresh starts from no list, then restore the + // original executable. // Same directory and extension (.cmd on Windows), only a different name. const probeWrapper = path.join(path.dirname(wrapper), "probe-" + path.basename(wrapper)) fs.copyFileSync(wrapper, probeWrapper) @@ -785,7 +788,7 @@ const legacyModel = "agy-cli/gemini-test-low" let models = {} for (let attempt = 0; attempt < 50 && !(models["gemini-test"] && models["claude-test-medium"]); attempt++) { if (attempt) await new Promise(resolve => setTimeout(resolve, 100)) - models = await plugin.provider.models() + models = await plugin.provider.models(undefined, { refresh: attempt === 0 }) } const probes = logs().filter(event => event.type === "models").slice(probesBefore) check("directory refresh disables auto update when the user set nothing", probes.length > 0 && probes.every(event => event.update === "true")) @@ -797,9 +800,9 @@ const legacyModel = "agy-cli/gemini-test-low" check("grouped model declares sorted variants", Object.keys(models["gemini-test"]?.variants || {}).join(",") === "low,medium,high") check("grouped model declares Magpie and OpenCode reasoning", models["gemini-test"]?.capabilities?.reasoning === true && models["gemini-test"]?.reasoning === true) check("Gemini models expose image input to the host", models["gemini-test"]?.capabilities?.input?.image === true) - // Listing asks agy's ACP server what it offers this client (a session, no - // prompt), so a non-Gemini model it offers is served before any request. - check("listing models learns what agy's ACP server offers, before any request", !!models["claude-test-medium"], Object.keys(models).join(",")) + // A refresh asks agy's ACP server what it offers this client (a session, + // no prompt), so a non-Gemini model it offers is served before any request. + check("a refresh learns what agy's ACP server offers, before any request", !!models["claude-test-medium"], Object.keys(models).join(",")) process.env.AGY_PATH = wrapper // The original executable gets its own fresh catalog before later requests route on it. for (let attempt = 0; attempt < 50 && !(await plugin.provider.models())["gemini-test"]; attempt++) { @@ -1475,7 +1478,7 @@ let nativeConv { ...image, source: { ...image.source, data: "" } }, { ...image, source: { ...image.source, data: "not base64!" } }, { ...image, source: { ...image.source, media_type: "application/pdf" } }, - { type: "document", source: { type: "base64", media_type: "application/pdf", data: "AAAA" } }, + { type: "document", source: { type: "base64", media_type: "application/zip", data: "AAAA" } }, ] const before = inits().length for (const block of invalid) { @@ -2554,12 +2557,12 @@ for (const location of ["inline", "system", "developer", "user"]) { model, messages: [{ role: "user", - content: [{ type: "document", source: { type: "base64", media_type: "application/pdf", data: "JVBERi0=" } }], + content: [{ type: "document", source: { type: "base64", media_type: "application/zip", data: "UEsDBA==" } }], }], }) const pdfError = await pdfRes.json() - check("binary PDF document block returns HTTP 400 that says what to do", - pdfRes.status === 400 && /PDF attached as a document is not supported/.test(pdfError.error?.message) && + check("a binary document other than a PDF returns HTTP 400 that says what to do", + pdfRes.status === 400 && /application\/zip file attached as a document is not supported/.test(pdfError.error?.message) && /Paste the document's text/.test(pdfError.error?.message), JSON.stringify(pdfError)) // A client's URL document (daoche_wuzui on X) and a base64 text file go diff --git a/test/spilled-output.mjs b/test/spilled-output.mjs index 253932c..c112036 100644 --- a/test/spilled-output.mjs +++ b/test/spilled-output.mjs @@ -78,19 +78,158 @@ test("any other file, or a link out of agy's folder, still goes to the client", } }) -test("a tool that isn't a read is never answered from the saved output", async () => { +// plugins#1848 (OiAnthony): magpie and agy on a Linux server, Oh My Pi on +// a Mac. Oh My Pi's read puts the lines in the path (read-selector.ts), and +// the model read the file with eval and bash too; each went to the Mac and +// failed with not found. +const OMP_READ = { name: "read", description: "Read a file", input_schema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] } } +const OMP_EVAL = { name: "eval", description: "Run code", input_schema: { type: "object", properties: { language: { type: "string", enum: ["py", "js"] }, code: { type: "string" } }, required: ["language", "code"] } } +const OMP_BASH = { name: "bash", description: "Run a command", input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } } +const HUNDRED_TWENTY = Array.from({ length: 120 }, (_, i) => `row ${i + 1}`).join("\n") + "\n" + +async function callThrough(kit, name, args, system = "You are a test agent.") { + let reply + kit.prompts.push(async (agent) => { + const [proc] = [...kit.module.__agyTestAllProcs] + reply = await agent.tool(name, args(proc.agyDir)) + if (reply?.result) await agent.text("read it") + }) + const body = baseBody({ system, tools: [OMP_READ, OMP_EVAL, OMP_BASH] }) + const result = await readSse(await kit.request(body)) + return { reply, result } +} + +const rows = (from, to, raw = false) => Array.from({ length: to - from + 1 }, (_, i) => + raw ? `row ${from + i}` : `${String(from + i).padStart(6)}\trow ${from + i}`).join("\n") + +test("Oh My Pi's read with lines after the path is answered by the bridge (plugins#1848)", async () => { + for (const [selector, want] of [ + [":1-100", rows(1, 100)], + [":raw:1-100", rows(1, 100, true)], + [":-60", rows(61, 120)], + ]) { + const kit = await createBridgeKit() + try { + const { reply, result } = await callThrough(kit, "read", (dir) => ({ path: spill(dir, HUNDRED_TWENTY, "8e1f", "12") + selector })) + assert.equal(reply?.result?.isError, false, selector) + assert.equal(reply.result.content[0].text, want, selector) + assert.equal(result.content.find((item) => item.type === "tool_use"), undefined, `${selector}: sent to the client`) + } finally { + await kit.dispose() + } + } +}) + +test("eval and bash reads of a saved output are answered by the bridge (plugins#1848)", async () => { + for (const [name, args, want] of [ + ["eval", (file) => ({ language: "py", code: `pathlib.Path("${file}").read_text()` }), HUNDRED_TWENTY], + ["bash", (file) => ({ command: `cat ${file}` }), rows(1, 120, true)], + ["bash", (file) => ({ command: `sed -n '1,100p' ${file}` }), rows(1, 100, true)], + ]) { + const kit = await createBridgeKit() + try { + const { reply, result } = await callThrough(kit, name, (dir) => args(spill(dir, HUNDRED_TWENTY, "8e1f", "12"))) + assert.equal(reply?.result?.isError, false, name) + assert.equal(reply.result.content[0].text, want, name) + assert.equal(result.content.find((item) => item.type === "tool_use"), undefined, `${name}: sent to the client`) + } finally { + await kit.dispose() + } + } +}) + +test("a command that does more than read a saved output is told how to read it, or runs where the client is this machine", async () => { + for (const place of ["elsewhere", "unknown", "here"]) { + const kit = await createBridgeKit() + try { + const system = place === "here" ? `You are a test agent.\n - Primary working directory: ${kit.tmp}` + : place === "elsewhere" ? "You are a test agent.\n - Primary working directory: /Users/nobody-1848/project" + : "You are a test agent." + const { reply, result } = await callThrough(kit, "bash", (dir) => ({ command: `grep -n 'row 7' ${spill(dir, HUNDRED_TWENTY)}` }), system) + const call = result.content.find((item) => item.type === "tool_use") + if (place === "here") { + assert.equal(reply, undefined, "here: answered by the bridge") + assert.equal(call?.name, "bash", "here: not sent to the client") + continue + } + assert.equal(call, undefined, `${place}: sent to the client`) + assert.equal(reply?.result?.isError, true, place) + assert.match(reply.result.content[0].text, /output\.txt is where this session saves tool outputs[\s\S]* with read on that path/, place) + } finally { + await kit.dispose() + } + } +}) + +test("every read form gives the lines it asks for, and any other call is left alone", async () => { const kit = await createBridgeKit() try { - const { result } = await (async () => { - let reply - kit.prompts.push(async (agent) => { - const [proc] = [...kit.module.__agyTestAllProcs] - reply = await agent.tool("Bash", { command: spill(proc.agyDir, "x") }) - }) - const body = baseBody({ tools: [{ name: "Bash", input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } }] }) - return { reply, result: await readSse(await kit.request(body)) } - })() - assert.equal(result.content.find((item) => item.type === "tool_use")?.name, "Bash") + const { spilledOutput } = kit.module + const dir = path.join(kit.tmp, "agy") + const file = spill(dir, Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join("\n") + "\n") + const lines = (from, to, raw = false) => Array.from({ length: to - from + 1 }, (_, i) => + raw ? `line ${from + i}` : `${String(from + i).padStart(6)}\tline ${from + i}`).join("\n") + const text = (name, args, opts) => { + const reply = spilledOutput(dir, name, args, opts) + return reply && (reply.isError ? `error: ${reply.content[0].text}` : reply.content[0].text) + } + // Oh My Pi's selectors, as read-selector.ts and line-ranges.ts take them + for (const [selector, want] of [ + ["", lines(1, 10)], [":3", lines(3, 3)], [":2-4", lines(2, 4)], [":4+2", lines(4, 5)], + [":9-", lines(9, 10)], [":-2", lines(9, 10)], [":L2..L3", lines(2, 3)], [":2-4:raw", lines(2, 4, true)], + [":raw:-3", lines(8, 10, true)], [":raw", lines(1, 10, true)], [":1-2,-1", `${lines(1, 2)}\n${lines(10, 10)}`], + [":40-50", "(nothing in that range: the file has 10 lines)"], + ]) assert.equal(text("read", { path: file + selector }), want, selector) + assert.match(text("read", { path: `${file}:conflicts` }), /^error: Invalid selector ':conflicts'/) + assert.equal(text("Read", { file_path: file, offset: 4, limit: 2 }), lines(4, 5)) + assert.equal(text("str_replace_based_edit_tool", { command: "view", path: file, view_range: [2, -1] }), lines(2, 10)) + assert.equal(text("read_file", { path: `file://${file}` }), lines(1, 10)) + // a command or code that only reads it + const whole = lines(1, 10, true) + for (const [name, args, want] of [ + ["bash", { command: `cat ${file}` }, whole], + ["bash", { command: `cat -n '${file}' | head -n 2` }, lines(1, 2)], + ["bash", { command: `head -n 3 "${file}"` }, lines(1, 3, true)], + ["bash", { command: `head -3 ${file}` }, lines(1, 3, true)], + ["bash", { command: `tail -n 2 ${file}` }, lines(9, 10, true)], + ["bash", { command: `tail -n +9 ${file} 2>/dev/null` }, lines(9, 10, true)], + ["bash", { command: `sed -n '2,3p' ${file}` }, lines(2, 3, true)], + ["bash", { command: `sed -n '9,$p' ${file}` }, lines(9, 10, true)], + ["shell", { command: ["bash", "-lc", `cat ${file} | tail -1`] }, lines(10, 10, true)], + ["exec_command", { cmd: `cat ${file} | sed -n 4p` }, lines(4, 4, true)], + ["powershell", { command: `Get-Content -Path '${file}' -TotalCount 2` }, lines(1, 2, true)], + ["powershell", { command: `Get-Content '${file}' | Select-Object -Last 1` }, lines(10, 10, true)], + ["eval", { language: "py", code: `import pathlib\nprint(pathlib.Path("${file}").read_text(encoding="utf-8"))` }, `${whole}\n`], + ["eval", { language: "py", code: `print(open('${file}').read())` }, `${whole}\n`], + ["eval", { language: "js", code: `console.log(fs.readFileSync("${file}", "utf8"))` }, `${whole}\n`], + ["eval", { language: "js", code: `await Bun.file("${file}").text()` }, `${whole}\n`], + ]) assert.equal(text(name, args), want, JSON.stringify(args).replaceAll(dir, "<agy>")) + // anything else that names it: told how to read it, unless the client is here + for (const [name, args] of [ + ["bash", { command: `grep -n 'line 5' ${file}` }], + ["bash", { command: `cat ${file}; rm -rf build` }], + ["bash", { command: `cat $(echo ${file})` }], + ["bash", { command: `cat ${file} > copy.txt` }], + ["eval", { language: "py", code: `print(len(pathlib.Path("${file}").read_text()))` }], + ["Grep", { pattern: "line", path: file }], + ]) { + const label = JSON.stringify(args).replaceAll(dir, "<agy>") + assert.match(text(name, args, { readTool: "Read" }), /^error: .*output\.txt is where this session saves tool outputs.* with Read on that path/, label) + assert.equal(text(name, args, { readTool: "Read", here: true }), null, label) + } + // a call that only mentions it, or another file + assert.equal(text("Write", { file_path: path.join(kit.tmp, "notes.md"), content: `see ${file}` }), null) + assert.equal(text("Task", { prompt: `summarize ${file}` }), null) + assert.equal(text("bash", { command: `cat ${path.join(kit.tmp, "elsewhere.txt")}` }), null) + assert.equal(text("read", { path: `${path.join(kit.tmp, "elsewhere", "output.txt")}:1-2` }), null) + // a link out of agy's folder, read through a command + const target = path.join(kit.tmp, "secret.txt") + fs.writeFileSync(target, "secret") + const link = path.join(dir, "brain", "s2", ".system_generated", "steps", "1", "output.txt") + fs.mkdirSync(path.dirname(link), { recursive: true }) + fs.symlinkSync(target, link) + assert.equal(text("bash", { command: `cat ${link}` }), null) + assert.equal(text("read", { path: `${link}:1-2` }), null) } finally { await kit.dispose() } diff --git a/test/steer-in-session.mjs b/test/steer-in-session.mjs index 62c4d6f..4b6026b 100644 --- a/test/steer-in-session.mjs +++ b/test/steer-in-session.mjs @@ -5,6 +5,13 @@ // deferred (`LONGTOOL`) self-poll vs non-polled `withoutAnswered` filtering, // `AGY_BRIDGE_MCP_COMMIT_WAIT_MS` bounds, and stale MCP socket rejection before // the next `session/prompt` starts (`turn.promptInFlight`). +// +// Every order a test is about is waited for as a state: the steer is under +// way, the poll is waiting, the other request has its answer. A sleep is only +// a window in which a broken bridge would show itself, never what makes the +// right order happen (#1853). Where a test is not about the commit wait's +// timeout, the wait is the longest there is, so a busy machine can't run it +// out; where a test is about waking it, the bound is half that wait. import { test } from "node:test" import assert from "node:assert/strict" @@ -13,6 +20,13 @@ import { } from "./testkit.mjs" const USAGE = { inputTokens: 100, cachedReadTokens: 0, cachedWriteTokens: 0, outputTokens: 5, totalTokens: 105 } +// MAX_MCP_COMMIT_WAIT_MS: a commit that is never woken waits this long +const LONG_COMMIT_WAIT = "60000" +// well inside LONG_COMMIT_WAIT, and far past any wake on a busy machine +const WOKEN_WITHIN_MS = 30_000 +// bun's 5s default per test is itself a duration a busy machine runs out +// (#1853); a broken bridge still shows red, by an assertion or by this +const TEST_TIMEOUT = 120_000 async function withKit(options, fn) { const kit = await createBridgeKit(options) @@ -23,6 +37,31 @@ async function withKit(options, fn) { } } +// Wait for a state, never a duration; the cap only bounds a hang. +async function until(what, check, capMs = 20_000) { + const started = Date.now() + while (!check()) { + if (Date.now() - started > capMs) throw new Error(`timed out waiting for ${what}`) + await sleep(5) + } +} + +function liveProc(kit) { + const procs = [...kit.module.__agyTestAllProcs] + return procs.find((proc) => proc.turn) ?? procs[0] +} + +function steering(kit) { + return until("the steer to be under way", () => liveProc(kit)?.turn?.steering === true) +} + +// A promise the test resolves, for the fake agy to wait on. +function gate() { + let open + const opened = new Promise((resolve) => { open = resolve }) + return { open, opened } +} + function steerBody(body, prev, text = "Steer to new instruction", resultFn = () => "REAL_RESULT_42") { const next = continueWithToolResults(body, prev, resultFn) next.messages.at(-1).content.push({ type: "text", text }) @@ -48,15 +87,17 @@ async function settleResponse(resPromise) { } } -test("steerInSession: duplicate steer and plain continuation during waitAcpToolsCommitted return 503 without early cancel", async () => { +test("steerInSession: duplicate steer and plain continuation during waitAcpToolsCommitted return 503 without early cancel", { timeout: TEST_TIMEOUT }, async () => { // Duplicate steer hitting waitAcpToolsCommitted window - await withKit({}, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { let cancelBeforeCommit = null + const second = gate() kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) const reply = await agent.tool("Read", { path: "/a" }) assert.equal(reply?.result?.content?.[0]?.text, "REAL_RESULT_42") - await sleep(140) + // the call stays uncommitted until the second request has its answer + await second.opened cancelBeforeCommit = agent.cancelPending agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) await agent.waitCancel() @@ -71,9 +112,10 @@ test("steerInSession: duplicate steer and plain continuation during waitAcpTools const first = await readSse(await kit.request(body)) const steered = steerBody(body, first) const reqA = kit.request(steered) - await sleep(30) - const reqB = kit.request(steered) - const [resA, resB] = await Promise.all([settleResponse(reqA), settleResponse(reqB)]) + await steering(kit) + const resB = await settleResponse(kit.request(steered)) + second.open() + const resA = await settleResponse(reqA) assert.equal(cancelBeforeCommit, false, "duplicate steer must not trigger session/cancel before tool_call_update") assert.equal(resA.status, 200) @@ -85,12 +127,13 @@ test("steerInSession: duplicate steer and plain continuation during waitAcpTools }) // Plain non-steer continuation hitting waitAcpToolsCommitted window - await withKit({}, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { let cancelBeforeCommit = null + const second = gate() kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/a" }) - await sleep(140) + await second.opened cancelBeforeCommit = agent.cancelPending agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) await agent.waitCancel() @@ -104,9 +147,10 @@ test("steerInSession: duplicate steer and plain continuation during waitAcpTools const body = baseBody() const first = await readSse(await kit.request(body)) const reqA = kit.request(steerBody(body, first)) - await sleep(30) - const reqB = kit.request(continueWithToolResults(body, first, () => "REAL_RESULT_42")) - const [resA, resB] = await Promise.all([settleResponse(reqA), settleResponse(reqB)]) + await steering(kit) + const resB = await settleResponse(kit.request(continueWithToolResults(body, first, () => "REAL_RESULT_42"))) + second.open() + const resA = await settleResponse(reqA) assert.equal(cancelBeforeCommit, false) assert.equal(resA.status, 200) @@ -117,8 +161,8 @@ test("steerInSession: duplicate steer and plain continuation during waitAcpTools }) }) -test("steerInSession: parallel same-name tool calls wait until every in-flight ACP toolCallId commits", async () => { - await withKit({}, async (kit) => { +test("steerInSession: parallel same-name tool calls wait until every in-flight ACP toolCallId commits", { timeout: TEST_TIMEOUT }, async () => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { let cancelAfterSecondOnly = null let seenReplies = null kit.prompts.push(async (agent) => { @@ -127,6 +171,7 @@ test("steerInSession: parallel same-name tool calls wait until every in-flight A const replies = await agent.tools([["Read", { path: "/a" }], ["Read", { path: "/b" }]]) seenReplies = replies.map((r) => r?.result?.content?.[0]?.text) agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c2", status: "completed" }) + // a window for a bridge that stopped waiting at c2 to send its cancel await sleep(80) cancelAfterSecondOnly = agent.cancelPending agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) @@ -151,8 +196,8 @@ test("steerInSession: parallel same-name tool calls wait until every in-flight A }) }) -test("steerInSession: trailing sibling MCP call during steer is held quiet and its socket destroyed on finalize", async () => { - await withKit({}, async (kit) => { +test("steerInSession: trailing sibling MCP call during steer is held quiet and its socket destroyed on finalize", { timeout: TEST_TIMEOUT }, async () => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { let heldPromise = null let heldSettledBeforeCancel = false kit.prompts.push(async (agent) => { @@ -163,6 +208,8 @@ test("steerInSession: trailing sibling MCP call during steer is held quiet and i if (!agent.cancelPending) heldSettledBeforeCancel = true return reply }) + await until("the sibling call to be held", () => liveProc(kit).turn?.cancelledMcpSockets.size === 1) + // a window for a bridge that answers the held call to do it await sleep(40) agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) await agent.waitCancel() @@ -181,14 +228,14 @@ test("steerInSession: trailing sibling MCP call during steer is held quiet and i assert.equal(kit.acpSpawns.length, 1, "held sibling call must not break cancelTurn or force a new session") assert.equal(heldSettledBeforeCancel, false, "held sibling socket must stay quiet until cancel/finalize") - const heldOutcome = await Promise.race([heldPromise, sleep(250).then(() => "hung")]) + const heldOutcome = await Promise.race([heldPromise, sleep(20_000).then(() => "hung")]) assert.equal(heldOutcome, null, "finalizeTurn must destroy held sibling sockets so MCP helpers never hang") }) }) -test("steerInSession: generation output (text or thought) wakes commit wait early and is suppressed on steered turn", async () => { +test("steerInSession: generation output (text or thought) wakes commit wait early and is suppressed on steered turn", { timeout: TEST_TIMEOUT }, async () => { for (const kind of ["text", "thought"]) { - await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "2500" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { kit.prompts.push(async (agent) => { // Deliberately omit tool_call_update: moving on to generation proves MCP committed. agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) @@ -215,7 +262,7 @@ test("steerInSession: generation output (text or thought) wakes commit wait earl assert.equal(res.status, 200) assert.equal(res.text, `steered-${kind}`) assert.equal(kit.acpSpawns.length, 1, `${kind} chunk must resolve waitAcpToolsCommitted and keep session`) - assert.ok(elapsed < 800, `${kind} chunk should wake waitAcpToolsCommitted immediately, took ${elapsed}ms`) + assert.ok(elapsed < WOKEN_WITHIN_MS, `${kind} chunk should wake waitAcpToolsCommitted, not wait it out: took ${elapsed}ms`) assert.equal( turn1.events.some((ev) => ev.type === "text" || ev.type === "thinking"), false, @@ -225,9 +272,9 @@ test("steerInSession: generation output (text or thought) wakes commit wait earl } }) -test("steerInSession: natural end_turn and child crash during commit wait wake immediately and handle session state cleanly", async () => { +test("steerInSession: natural end_turn and child crash during commit wait wake immediately and handle session state cleanly", { timeout: TEST_TIMEOUT }, async () => { // Natural end_turn without tool_call_update or chunks: wakes immediately, finalizes turn1, reuses session - await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "2500" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/a" }) @@ -251,13 +298,13 @@ test("steerInSession: natural end_turn and child crash during commit wait wake i assert.equal(res.text, "steered after natural end") assert.equal(kit.acpSpawns.length, 1, "natural completion must finalize turn1 and keep the live session") assert.equal(cancelCount(kit), 0) - assert.ok(elapsed < 800, `Turn.complete() must wake waitAcpToolsCommitted immediately, took ${elapsed}ms`) + assert.ok(elapsed < WOKEN_WITHIN_MS, `Turn.complete() must wake waitAcpToolsCommitted, not wait it out: took ${elapsed}ms`) assert.equal(prompt2Text.includes("REAL_RESULT_42"), false) assert.equal(prompt2Text.includes("Steer to new instruction"), true) }) // Child SIGKILL during commit wait: wakes immediately and replays in a fresh session - await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "2500" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/a" }) @@ -279,18 +326,20 @@ test("steerInSession: natural end_turn and child crash during commit wait wake i assert.equal(res.status, 200) assert.equal(res.text, "replayed after crash") assert.equal(kit.acpSpawns.length, 2) - assert.ok(elapsed < 1000, `Turn.fail() must wake waitAcpToolsCommitted immediately, took ${elapsed}ms`) + assert.ok(elapsed < WOKEN_WITHIN_MS, `Turn.fail() must wake waitAcpToolsCommitted, not wait it out: took ${elapsed}ms`) }) }) -test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or in steer prompt when unpolled", async () => { +test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or in steer prompt when unpolled", { timeout: TEST_TIMEOUT }, async () => { // Unpolled deferred call: agy received "still running" and moved on without polling -> steer prompt MUST carry REAL_RESULT await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50" } }, async (kit) => { + const movedOn = gate() kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) const firstReply = await agent.tool("Read", { path: "/long" }) assert.match(firstReply?.result?.content?.[0]?.text || "", /still running/) agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + movedOn.open() await agent.waitCancel() return { stopReason: "cancelled", usage: USAGE } }) @@ -303,7 +352,7 @@ test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or const body = baseBody() const first = await readSse(await kit.request(body)) - await sleep(90) + await movedOn.opened const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_RESULT_77"))) assert.equal(res.status, 200) @@ -319,6 +368,8 @@ test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/long" }) agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + // the poll waits for the steer however long the machine takes to send it + kit.env.AGY_BRIDGE_IDE_CALL_DEADLINE_MS = "600000" agent.update({ sessionUpdate: "tool_call", toolCallId: "c2", status: "in_progress" }) const pollReply = await agent.tool("Read", { path: "/long" }) pollReplyText = pollReply?.result?.content?.[0]?.text @@ -335,7 +386,7 @@ test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or const body = baseBody() const first = await readSse(await kit.request(body)) - await sleep(240) + await until("agy's poll to wait for the result", () => liveProc(kit).turn?.awaitCalls.length === 1) const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_RESULT_77"))) assert.equal(res.status, 200) @@ -346,7 +397,19 @@ test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or }) }) -test("steerInSession: AGY_BRIDGE_MCP_COMMIT_WAIT_MS clamps int32 overflow and supports 0ms immediate fallback", async () => { +// The timeout the steer handed to the commit wait, read where it is used. +function recordCommitWaits(kit) { + const turn = liveProc(kit).turn + const waits = [] + const wait = turn.waitAcpToolsCommitted + turn.waitAcpToolsCommitted = function (ids, timeoutMs) { + waits.push(timeoutMs) + return wait.call(this, ids, timeoutMs) + } + return waits +} + +test("steerInSession: AGY_BRIDGE_MCP_COMMIT_WAIT_MS clamps int32 overflow and supports 0ms immediate fallback", { timeout: TEST_TIMEOUT }, async () => { // > 2^31 - 1 must clamp to 60s instead of overflowing setTimeout to 1ms await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "3000000000" } }, async (kit) => { kit.prompts.push(async (agent) => { @@ -364,7 +427,9 @@ test("steerInSession: AGY_BRIDGE_MCP_COMMIT_WAIT_MS clamps int32 overflow and su const body = baseBody() const first = await readSse(await kit.request(body)) + const waits = recordCommitWaits(kit) const res = await settleResponse(kit.request(steerBody(body, first))) + assert.deepEqual(waits, [60_000], "the commit wait is clamped to MAX_MCP_COMMIT_WAIT_MS") assert.equal(res.status, 200) assert.equal(res.text, "clamped ok") assert.equal(kit.acpSpawns.length, 1, "clamped timeout must not fire at 1ms before tool_call_update") @@ -385,18 +450,17 @@ test("steerInSession: AGY_BRIDGE_MCP_COMMIT_WAIT_MS clamps int32 overflow and su const body = baseBody() const first = await readSse(await kit.request(body)) - const startedAt = Date.now() + const waits = recordCommitWaits(kit) const res = await settleResponse(kit.request(steerBody(body, first))) - const elapsed = Date.now() - startedAt + assert.deepEqual(waits, [0], "0ms commit wait should fall back at once, not wait the default 5s") assert.equal(res.status, 200) assert.equal(res.text, "zero-wait replay") assert.equal(kit.acpSpawns.length, 2) - assert.ok(elapsed < 800, `0ms commit wait should fall back immediately, took ${elapsed}ms`) }) }) -test("steerInSession: stale MCP socket arriving before next session/prompt is rejected instead of leaking a phantom tool_use", async () => { +test("steerInSession: stale MCP socket arriving before next session/prompt is rejected instead of leaking a phantom tool_use", { timeout: TEST_TIMEOUT }, async () => { await withKit({}, async (kit) => { let agent1 = null kit.prompts.push(async (agent) => { @@ -420,6 +484,8 @@ test("steerInSession: stale MCP socket arriving before next session/prompt is re let staleCall = null proc.startTurn = function (...args) { const nextTurn = origStartTurn.apply(this, args) + // the fake agy's control socket is served in this same tick, so the + // call is in before the turn's session/prompt goes out staleCall = agent1.tool("Read", { path: "/STALE_FROM_CANCELLED_TURN" }) proc.startTurn = origStartTurn return nextTurn @@ -437,13 +503,15 @@ test("steerInSession: stale MCP socket arriving before next session/prompt is re }) }) -test("steerInSession: pool pressure and repeated unmatched tool results cannot evict or reclaim an active steer", async () => { +test("steerInSession: pool pressure and repeated unmatched tool results cannot evict or reclaim an active steer", { timeout: TEST_TIMEOUT }, async () => { // Pool pressure (evictLRU) while steering - await withKit({ env: { AGY_BRIDGE_MAX_PROCS: "1", AGY_BRIDGE_DETACHED_EVICT_MS: "10" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MAX_PROCS: "1", AGY_BRIDGE_DETACHED_EVICT_MS: "10", AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { + const other = gate() kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/a" }) - await sleep(120) + // the steer stays under way until the other conversation has its answer + await other.opened agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) await agent.waitCancel() return { stopReason: "cancelled", usage: USAGE } @@ -456,10 +524,11 @@ test("steerInSession: pool pressure and repeated unmatched tool results cannot e const body1 = baseBody({ messages: [{ role: "user", content: "conversation one" }] }) const first = await readSse(await kit.request(body1)) const steerReq = kit.request(steerBody(body1, first)) - await sleep(25) + await steering(kit) kit.clock.advance(60_000) const body2 = baseBody({ messages: [{ role: "user", content: "conversation two" }] }) const otherRes = await settleResponse(kit.request(body2)) + other.open() const steerRes = await settleResponse(steerReq) assert.equal(otherRes.status, 503, "pool pressure must reject new conversation rather than evicting steering turn") @@ -470,11 +539,12 @@ test("steerInSession: pool pressure and repeated unmatched tool results cannot e }) // unmatched tool results while steering are busy (503, try again) and never reclaim - await withKit({}, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { + const repeated = gate() kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/a" }) - await sleep(150) + await repeated.opened agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) await agent.waitCancel() return { stopReason: "cancelled", usage: USAGE } @@ -487,7 +557,7 @@ test("steerInSession: pool pressure and repeated unmatched tool results cannot e const body = baseBody({ messages: [{ role: "user", content: "conversation repeat guard" }] }) const first = await readSse(await kit.request(body)) const steerReq = kit.request(steerBody(body, first)) - await sleep(25) + await steering(kit) const bogus = continueWithToolResults(body, first, () => "BOGUS") for (const block of bogus.messages.at(-1).content) { @@ -497,6 +567,7 @@ test("steerInSession: pool pressure and repeated unmatched tool results cannot e for (let i = 0; i < 3; i++) { boguses.push(await settleResponse(kit.request(bogus))) } + repeated.open() const steerRes = await settleResponse(steerReq) assert.deepEqual(boguses.map((r) => r.status), [503, 503, 503]) @@ -506,18 +577,21 @@ test("steerInSession: pool pressure and repeated unmatched tool results cannot e }) }) -test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation, failed status commit, and waitLate promptInFlight guard", async () => { +test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation, failed status commit, and waitLate promptInFlight guard", { timeout: TEST_TIMEOUT }, async () => { // 1. Self-polled deferred call must wait for agy's ACP tool_call_update on the poll before session/cancel - await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "180" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "180", AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { let cancelBeforeCommit = null let pollText = null kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/long" }) agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + // the poll waits for the steer however long the machine takes to send it + kit.env.AGY_BRIDGE_IDE_CALL_DEADLINE_MS = "600000" agent.update({ sessionUpdate: "tool_call", toolCallId: "c2", status: "in_progress" }) const poll = await agent.tool("Read", { path: "/long" }) pollText = poll?.result?.content?.[0]?.text + // a window for a bridge that doesn't wait for the poll's commit to cancel await sleep(120) cancelBeforeCommit = agent.cancelPending agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c2", status: "completed" }) @@ -530,7 +604,7 @@ test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation } const body = baseBody() const first = await readSse(await kit.request(body)) - await sleep(240) + await until("agy's poll to wait for the result", () => liveProc(kit).turn?.awaitCalls.length === 1) const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_77"))) assert.equal(res.status, 200) assert.equal(pollText, "LONG_77") @@ -539,7 +613,7 @@ test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation }) // 2. Unrelated agy-internal ACP tool in flight must not stall a steer that delivers no live MCP socket - await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50", AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "1500" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50", AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/long" }) @@ -554,13 +628,15 @@ test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation } const body = baseBody() const first = await readSse(await kit.request(body)) - await sleep(90) + const turn1 = liveProc(kit).turn + await until("the call deferred and agy's own tool in flight", () => + turn1.calls.some((call) => call.deferred) && turn1.activeAcpToolCalls.has("internal9")) const t0 = Date.now() const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_77"))) const elapsed = Date.now() - t0 assert.equal(res.status, 200) assert.equal(kit.acpSpawns.length, 1) - assert.ok(elapsed < 800, `stalled ${elapsed}ms on a foreign ACP tool`) + assert.ok(elapsed < WOKEN_WITHIN_MS, `stalled ${elapsed}ms on a foreign ACP tool`) }) // 3. Stale MCP call arriving during waitLate between two prompts of the same turn is rejected @@ -577,18 +653,18 @@ test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation } const body = baseBody() await readSse(await kit.request(body)) - await sleep(120) const [proc] = [...kit.module.__agyTestAllProcs] + await until("the turn to wait for the late result", () => proc.turn?.lateWaiters.length === 1) assert.ok(proc.turn && !proc.turn.done, "turn should be waiting for the late result") const outcome = await Promise.race([ agent1.tool("Read", { path: "/STALE_BETWEEN_PROMPTS" }), - sleep(300).then(() => "accepted-and-pending"), + sleep(20_000).then(() => "accepted-and-pending"), ]) assert.match(outcome?.error?.message || String(outcome), /no prompt in flight/) }) // 4. tool_call_update with status "failed" (e.g. client tool_result is_error) counts as committed - await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "1500" } }, async (kit) => { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: LONG_COMMIT_WAIT } }, async (kit) => { kit.prompts.push(async (agent) => { agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) await agent.tool("Read", { path: "/a" }) @@ -608,7 +684,7 @@ test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation const elapsed = Date.now() - t0 assert.equal(res.status, 200) assert.equal(kit.acpSpawns.length, 1) - assert.ok(elapsed < 800, `failed status did not count as commit: ${elapsed}ms`) + assert.ok(elapsed < WOKEN_WITHIN_MS, `failed status did not count as commit: ${elapsed}ms`) }) }) diff --git a/test/testkit.mjs b/test/testkit.mjs index 7cb56fa..4bc5c2c 100644 --- a/test/testkit.mjs +++ b/test/testkit.mjs @@ -50,10 +50,10 @@ export const ONESHOT_ACP_FILE = path.join(REPO_DIR, "oneshot-acp.mjs") export const GATEWAY_FREE_FILE = path.join(REPO_DIR, "gateway-free.mjs") export const DEFAULT_AGENT_FILE = path.join(REPO_DIR, "default-agent.mjs") export const AGENT_SUMMARY_FILE = path.join(REPO_DIR, "agent-summary.mjs") +export const HOSTED_SEARCH_FILE = path.join(REPO_DIR, "hosted-search.mjs") export const MESSAGES_URL = "agy://local/v1/messages" export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens" export const CATALOG_TTL_MS = 5 * 60 * 1000 -export const OFFERED_TTL_MS = 60 * 60 * 1000 const RUNTIME_SPECIFIER = "agy-testkit:runtime" const RUNTIME_NAMES = ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval", "process"] @@ -745,6 +745,7 @@ export async function createBridgeKit(options = {}) { const gatewayFreeUrl = pathToFileURL(GATEWAY_FREE_FILE).href const defaultAgentUrl = pathToFileURL(DEFAULT_AGENT_FILE).href const agentSummaryUrl = pathToFileURL(AGENT_SUMMARY_FILE).href + const hostedSearchUrl = pathToFileURL(HOSTED_SEARCH_FILE).href const linker = (specifier) => { const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER ? specifier @@ -767,11 +768,16 @@ export async function createBridgeKit(options = {}) { else if (key === "./account.mjs") module = sourceModule(ACCOUNT_FILE, "", accountUrl) else if (key === "./import.mjs") module = sourceModule(IMPORT_FILE, "", importUrl) else if (key === "./documents.mjs") module = sourceModule(DOCUMENTS_FILE, "", documentsUrl) + else if (key === "./spilled.mjs") { + const file = path.join(REPO_DIR, "spilled.mjs") + module = sourceModule(file, "", pathToFileURL(file).href) + } else if (key === "./image.mjs") module = sourceModule(IMAGE_FILE, "", imageUrl) else if (key === "./oneshot-acp.mjs") module = sourceModule(ONESHOT_ACP_FILE, "", oneshotAcpUrl) else if (key === "./gateway-free.mjs") module = sourceModule(GATEWAY_FREE_FILE, "", gatewayFreeUrl) else if (key === "./default-agent.mjs") module = sourceModule(DEFAULT_AGENT_FILE, "", defaultAgentUrl) else if (key === "./agent-summary.mjs") module = sourceModule(AGENT_SUMMARY_FILE, "", agentSummaryUrl) + else if (key === "./hosted-search.mjs") module = sourceModule(HOSTED_SEARCH_FILE, "", hostedSearchUrl) else if (key === "./agy-version.mjs") { const file = path.join(REPO_DIR, "agy-version.mjs") module = sourceModule(file, "", pathToFileURL(file).href) @@ -792,10 +798,13 @@ export async function createBridgeKit(options = {}) { if (!kit.turns.includes(this)) kit.turns.push(this) return originalRegister.apply(this, args) } - kit.plugin = await ns.AntigravityBridgePlugin() + kit.plugin = await ns.AntigravityBridgePlugin(options.pluginInput, options.pluginOptions) kit.loaded = await kit.plugin.auth.loader() - kit.models = () => kit.plugin.provider.models() + // ctx as magpie's host gives it; { refresh: true } is the user refreshing + // the list (kit.refresh) + kit.models = (ctx) => kit.plugin.provider.models(undefined, ctx) + kit.refresh = () => kit.models({ refresh: true }) kit.fetch = (url, init) => kit.loaded.fetch(url, init) kit.request = (body, init = {}) => kit.fetch(MESSAGES_URL, { method: "POST", body: JSON.stringify(body), ...init }) kit.countTokens = async (body) => { @@ -864,7 +873,7 @@ export async function readSse(response) { } else if (event === "content_block_stop") { const block = blocks.get(data.index) blocks.delete(data.index) - if (block.type === "tool_use") block.input = block.json ? JSON.parse(block.json) : {} + if (block.type === "tool_use" || block.type === "server_tool_use") block.input = block.json ? JSON.parse(block.json) : {} delete block.json content.push(block) } else if (event === "message_delta") { diff --git a/test/usage.mjs b/test/usage.mjs index 60e2f9b..99b98bc 100644 --- a/test/usage.mjs +++ b/test/usage.mjs @@ -6,7 +6,7 @@ import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { test } from "node:test" -import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, retryIn, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyLinkIn } from "../usage.mjs" +import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, retryIn, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyAskedAtSignIn, verifyLinkIn, verifyRefused } from "../usage.mjs" import { catalogRows, familiesInGroup, modelsInGroup, storeCatalogRows } from "../model-ids.mjs" import { inAccount } from "../account.mjs" import { forgetStoredSignIn } from "../signin.mjs" @@ -1327,6 +1327,40 @@ test("the statusLine's buckets read as /usage's groups, by the same names and th assert.throws(() => parseStatusLineQuota({})) }) +// plugins#1891 (keleus, Google AI Ultra): the menu bar showed one figure, +// "Gemini · Orchestrator (Argon)", for a card of two pools. agy lists +// Orchestrator (Neon, Carbon, Argon) beside the Gemini models, and the +// statusLine's Gemini pool, and /usage's Gemini group, named it, so it got +// a window of its own; the bridge never serves it (orchestratorRefusal), so +// magpie couldn't tell it from the account's picks, and with the pools' +// models unpicked it was the one window left. No window, and no pool's +// list, names it. The rows are an Ultra account's `agy models`, as saved. +test("Orchestrator, which the bridge doesn't serve, gets no window and no pool lists it", () => { + const ultra = [ + ...LIVE_MODEL_ROWS, + { id: "gemini-pro-orchestrator-neon", name: "Orchestrator (Neon)" }, + { id: "gemini-pro-orchestrator", name: "Orchestrator (Carbon)" }, + { id: "gemini-pro-orchestrator-argon", name: "Orchestrator (Argon)" }, + ] + const orchestrator = id => /orchestrator/i.test(id) + try { + storeCatalogRows(ultra) + assert.ok(!catalogRows().some(r => orchestrator(r.id))) + const status = parseStatusLineQuota(structuredClone(STATUS_QUOTA)) + // as the /usage group names the models of an account whose card has them + const named = parseUsageReport(report([group([bucket(), bucket({ id: "gemini-weekly", name: "Weekly Limit Remaining", window: "weekly", remaining_fraction: 0.794 })], "Gemini Models", + "Models within this group: Gemini 4 Hydrogen, Gemini 3.8 Flash, Orchestrator (Neon), Orchestrator (Carbon), Orchestrator (Argon)")])) + for (const result of [status, named]) { + assert.ok(!result.windows.some(w => /orchestrator/i.test(w.name) || orchestrator(w.model ?? "")), JSON.stringify(result.windows.map(w => w.name))) + assert.ok(!result.windows.some(w => (w.models ?? []).some(orchestrator))) + } + // the Gemini models it names still have theirs + assert.deepEqual(named.windows.filter(w => w.model).map(w => w.name), ["Gemini 3.8 Flash", "Gemini 4 Hydrogen"]) + } finally { + storeCatalogRows(null) + } +}) + test("an account agy -p calls ineligible while agy acp names its tier reads its quota from agy's TUI", { skip: !PTY }, async t => { const asked = noFetch(t) storeCatalogRows(LIVE_MODEL_ROWS) @@ -1502,6 +1536,120 @@ test("a read longer than magpie waits says agy is still reading, and the next ca await f.assertClean() }) +// #1877: nothing reads usage in the background, so a reading agy finished +// after the refresh gave up ("It shows on the next refresh") waits for the +// next refresh however late it comes, not three minutes. That refresh reads +// again, and while agy is slow again it answers with the kept reading. +test("a reading agy finished after the call gave up waits for the next refresh past three minutes", async t => { + const f = await fixture(t, { TEST_MODE: "delay", TEST_REPORT_DELAY_MS: "1500" }) + let settled + let clock = 1_000_000 + const read = createUsageReader(() => f.executable, { ...f.options, waitMs: 300, timeoutMs: 20_000, now: () => clock, onSettled: () => settled() }) + const runs = async () => (await f.logs()).filter(l => l.args[0] === "-p").length + let done = new Promise(r => { settled = r }) + assert.equal((await read()).error, STILL_READING) + await done + // two hours on, agy has 50% used now and is slow again + clock += 2 * 3600_000 + f.env.TEST_REPORT = JSON.stringify(report([group([bucket({ remaining_fraction: 0.5 })])])) + done = new Promise(r => { settled = r }) + const next = await read() + assert.equal(next.error, undefined, "the reading finished after the first refresh was let go") + assert.equal(next.signIn, "kept") + assert.equal(next.windows.length, 1) + assert.equal(next.windows[0].used, 25, "not the reading kept from before") + // the refresh's read is started, not waited for: its agy writes its log + // line once spawned, which a loaded machine takes a while to do + for (let i = 0; i < 200 && await runs() < 2; i++) await new Promise(r => setTimeout(r, 25)) + assert.equal(await runs(), 2, "the refresh didn't read again") + // what that read finished with is the next refresh's, without agy + await done + clock += 60_000 + const after = await read() + assert.equal(after.error, undefined) + assert.equal(after.windows[0].used, 50) + assert.equal(await runs(), 2) + await f.assertClean() +}) + +test("a kept reading is let go at a window's reset, after five hours, on another sign-in, and after a failed read", async t => { + const start = Date.parse("2030-01-01T00:00:00Z") + const steps = async (t, { reset = "", stored: given } = {}) => { + const f = await fixture(t, { TEST_MODE: "delay", TEST_REPORT_DELAY_MS: "1500", TEST_REPORT: JSON.stringify(report([group([bucket(reset ? { reset_time: reset } : {})])])) }) + let settled + const s = { f, clock: start, stored: given ?? { state: "present", fp: "a", canRenew: true, expiresAt: start + 100 * 3600_000, expired: false } } + s.read = createUsageReader(() => f.executable, { ...f.options, waitMs: 300, timeoutMs: 20_000, now: () => s.clock, signIn: async () => s.stored, onSettled: () => settled() }) + // a call whose read goes on past it, and that read's end (a call that + // ran no read fails here rather than waiting for its test's timeout) + s.late = async () => { + const done = new Promise(r => { settled = r }) + const reply = await s.read() + let guard + const none = new Promise((_, reject) => { guard = setTimeout(() => reject(new Error(`no read ran for ${JSON.stringify(reply)}`)), 30_000) }) + await Promise.race([done, none]).finally(() => clearTimeout(guard)) + return reply + } + assert.equal((await s.late()).error, STILL_READING) + return s + } + // a window's reset + { + const s = await steps(t, { reset: new Date(start + 3600_000).toISOString() }) + s.clock += 3600_000 - 1000 + assert.equal((await s.late()).windows[0]?.used, 25, "let go before the reset") + s.clock += 1000 + assert.equal((await s.late()).error, STILL_READING, "kept past its window's reset") + await s.f.assertClean() + } + // five hours, with no reset time + { + const s = await steps(t) + s.clock += 5 * 3600_000 - 1000 + assert.equal((await s.late()).windows[0]?.used, 25, "let go before five hours") + s.clock += 5 * 3600_000 + assert.equal((await s.late()).error, STILL_READING, "kept past five hours") + await s.f.assertClean() + } + // another account's sign-in, then the first one's again + { + const s = await steps(t) + const a = s.stored + s.stored = { ...a, fp: "b" } + s.clock += 60_000 + assert.equal((await s.late()).error, STILL_READING, "another sign-in took the reading") + s.stored = a + s.clock += 60_000 + assert.equal((await s.late()).error, STILL_READING, "the reading outlived another sign-in") + await s.f.assertClean() + } + // signed out, then in again + { + const s = await steps(t) + const a = s.stored + s.stored = { state: "missing" } + assert.equal((await s.read()).signIn, "expired") + s.stored = a + s.clock += 60_000 + assert.equal((await s.late()).error, STILL_READING, "the reading outlived signing out") + await s.f.assertClean() + } + // a read after it failed: the failure is what shows + { + const s = await steps(t) + s.clock += 10 * 60_000 + s.f.env.TEST_MODE = "fail" + await s.late() + s.f.env.TEST_MODE = "delay" + const held = await s.read() + assert.deepEqual(held.windows, []) + assert.match(held.error, /magpie asks agy again in/) + // asked again once the hold is over, and slow again + s.clock += 10 * 60_000 + assert.equal((await s.late()).error, STILL_READING, "the reading outlived a failed read") + await s.f.assertClean() + } +}) + test("a read that runs out of time says so plainly, and is asked again a minute later", async t => { const f = await fixture(t, { TEST_MODE: "hang" }) const live = { state: "present", fp: "live", canRenew: true, expiresAt: Date.now() + 3600_000, expired: false } @@ -1571,3 +1719,28 @@ test("verifyLinkIn: Google's validation link from a logged error, validation_lin assert.equal(verifyLinkIn('validation_url: "http://example.com/x"'), "") assert.equal(verifyLinkIn("Verification Required"), "") }) + +test("verifyLinkIn: the Help detail's link past Learn more, only in a VALIDATION_REQUIRED body", () => { + const help = (links) => `{"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED","domain":"cloudcode-pa.googleapis.com"},{"@type":"type.googleapis.com/google.rpc.Help","links":${JSON.stringify(links)}}]}}` + const verify = { description: "Verify your account", url: "https://accounts.google.com/signin/continue?sarp=1&x=2" } + const more = { description: "Learn more", url: "https://example.com/learn" } + const support = { description: "Help", url: "https://support.google.com/accounts" } + assert.equal(verifyLinkIn(help([verify, more])), verify.url) + assert.equal(verifyLinkIn(help([more, support, verify])), verify.url) + assert.equal(verifyLinkIn(help([more, support])), "") + assert.equal(verifyLinkIn(help([{ description: "Open", url: "https://example.com/validate?a=1" }])), "https://example.com/validate?a=1") + // another error's Help link (an API to enable) is not a way to verify + assert.equal(verifyLinkIn(help([{ description: "Enable the API", url: "https://console.developers.google.com/apis/x" }]).replace("VALIDATION_REQUIRED", "SERVICE_DISABLED")), "") +}) + +test("verifyRefused: a model call's refusal with no link never sends the user to run agy in a terminal", () => { + const request = verifyRefused("", { request: true, google: "PERMISSION_DENIED (code 403): Verify\n your account." }) + assert.match(request, /this Google account needs to be verified, and agy passed on no link/) + assert.match(request, /Google: "PERMISSION_DENIED \(code 403\): Verify your account\."/) + assert.doesNotMatch(request, /run `agy` in a terminal/) + assert.match(verifyRefused(""), /open the Antigravity app, or run `agy` in a terminal/) + const link = "https://accounts.google.com/v?a=1" + assert.ok(verifyRefused(link, { request: true }).includes(`this Google account needs to be verified: open ${link} in a browser`)) + assert.ok(verifyAskedAtSignIn("Error: Eligibility check failed: Verify your account to continue.")) + assert.ok(!verifyAskedAtSignIn("\n⚠ Verification Required\n")) +}) diff --git a/usage.mjs b/usage.mjs index 7d6baa3..12245fd 100644 --- a/usage.mjs +++ b/usage.mjs @@ -81,14 +81,36 @@ const VERIFY_REFUSAL = /please verify your account in your browser to continue|v // for the Antigravity and Gemini CLI routes. export const VERIFY_ADVICE = "this Google account needs to be verified" +// The validation link of Google's google.rpc.Help detail, as Gemini CLI's +// classifyValidationRequiredError takes it (and magpie's +// provider.Verification): the first of its links that isn't the "Learn +// more" one, which is on support.google.com. Only in a VALIDATION_REQUIRED +// body: another error's Help links (an API to enable) are not a way to +// verify. +function helpLinkIn(said) { + if (!/VALIDATION_REQUIRED/.test(said)) return "" + for (const [object] of said.matchAll(/\{[^{}]*"url"\s*:\s*"https:\/\/[^"]+"[^{}]*\}/g)) { + const url = /"url"\s*:\s*"(https:\/\/[^"\s\\<>]+)"/.exec(object)?.[1] || "" + const description = /"description"\s*:\s*"([^"]*)"/.exec(object)?.[1] || "" + if (!url || /^\s*learn more\s*$/i.test(description)) continue + try { + if (new URL(url).hostname === "support.google.com") continue + } catch { + continue + } + return url + } + return "" +} + // verifyLinkIn is the https link agy's output or log gives to verify the -// account at, "" when it gives none: taken as Gemini CLI takes it, the -// validation_link before the validation_url, else the link agy prints after -// "continue:", else an accounts.google.com one. +// account at, "" when it gives none: the validation_link before the +// validation_url, else the Help detail's link (helpLinkIn), else the link +// agy prints after "continue:", else an accounts.google.com one. export function verifyLinkIn(output) { const said = String(output ?? "").replace(/\\u0026/g, "&").replace(/&/g, "&") const named = (key) => new RegExp(`"?${key}"?\\s*[:=]\\s*"?(https://[^\\s"'\\\\<>]+)`, "i").exec(said)?.[1] - const link = named("validation_?link") || named("validation_?url") || + const link = named("validation_?link") || named("validation_?url") || helpLinkIn(said) || /in your browser to continue:\s*(https:\/\/[^\s"'\\<>]+)/i.exec(said)?.[1] || /(https:\/\/accounts\.google\.com\/[^\s"'\\<>]+)/i.exec(said)?.[1] || "" const trimmed = link.replace(/[).,;\]}]+$/, "") @@ -100,13 +122,41 @@ export function verifyLinkIn(output) { } } +// agy's eligibility check, which runs when agy starts and at sign-in, asks +// in these words and prints the link; a model call's refusal is the bare +// "Verification Required" +const VERIFY_AT_SIGN_IN = /please verify your account in your browser to continue|verification required\. please complete verification|eligibility check failed:[^\n]*verify your account/i + +export function verifyAskedAtSignIn(text) { + return VERIFY_AT_SIGN_IN.test(String(text ?? "")) +} + // verifyRefused is what the agent is told when Google wants the account // verified: with the link to do it at when agy gave one, else where to go. -export function verifyRefused(link) { - const said = "Google wants this account verified before Antigravity serves it again (agy: \"Verification Required\")" - return link - ? `${said} — ${VERIFY_ADVICE}: open ${link} in a browser signed in to it, verify it, then try again` - : `${said} — ${VERIFY_ADVICE}: open the Antigravity app, or run \`agy\` in a terminal, signed in to it and do what it asks, then try again` +// +// Asked on a model call (request), Google's 403 VALIDATION_REQUIRED +// reaches agy 1.5.21 as "Verification Required" alone: its +// CustomUserErrorMessageFromHTTPError keeps only the reason, and its log +// line only Google's message, so neither carries the link. agy's own +// sign-in check doesn't ask then, and `agy` in a terminal can answer on +// the same account (0xiaoge0 on X, 12-03: Codex's requests to +// gemini-4-neon at high refused, agy in a terminal at Medium answering). +// So "run agy in a terminal" verifies nothing there. `google` is +// Google's own words from agy's log, when it logged them. +export function verifyRefused(link, { request = false, google = "" } = {}) { + // Google's message, without a body agy logged after it + const words = String(google ?? "").split(/:?\s*\{/)[0].replace(/\s+/g, " ").trim().slice(0, 300) + const said = "Google wants this account verified before Antigravity serves it again (agy: \"Verification Required\"" + + (words ? `; Google: "${words}"` : "") + ")" + if (link) return `${said} — ${VERIFY_ADVICE}: open ${link} in a browser signed in to it, verify it, then try again` + if (!request) { + return `${said} — ${VERIFY_ADVICE}: open the Antigravity app, or run \`agy\` in a terminal, signed in to it and do what it asks, then try again` + } + return `${said} — ${VERIFY_ADVICE}, and agy passed on no link to do it at. Google asked on this model request, ` + + "not at sign-in, so signing in again won't show it, and `agy` in a terminal can still answer on the same account. " + + "Verify where Google shows the link when it asks: the Antigravity app or Gemini CLI, signed in to this account. " + + "If `agy` in a terminal answers this model, Google may be turning away this request rather than the account: " + + "try a lower reasoning level or a new conversation." } // agyRefusal is what to tell the user when agy's output says Google turned @@ -443,7 +493,9 @@ function killGroup(pid) { // acpTier is the tier agy acp's session/new names for the signed-in // account ({ id, name }), or null when it names none or doesn't answer. -export function acpTier(file, folderArgs, { cwd, env, deadline, signal }) { +// acpArgs and clientInfo are what a turn's agy acp is run with (index.mjs: +// the same flags and client name), so this one looks like any other. +export function acpTier(file, folderArgs, { cwd, env, deadline, signal, acpArgs = [], clientInfo }) { return new Promise((resolve) => { let child let done = false @@ -461,7 +513,7 @@ export function acpTier(file, folderArgs, { cwd, env, deadline, signal }) { const abortNow = () => finish(null) if (signal?.aborted || Date.now() >= deadline) return finish(null) try { - child = spawn(file, ["acp", ...folderArgs], { cwd, env, detached: true, stdio: ["pipe", "pipe", "ignore"] }) + child = spawn(file, ["acp", ...acpArgs, ...folderArgs], { cwd, env, detached: true, stdio: ["pipe", "pipe", "ignore"] }) } catch { return finish(null) } @@ -498,7 +550,7 @@ export function acpTier(file, folderArgs, { cwd, env, deadline, signal }) { } } }) - send(1, "initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } }) + send(1, "initialize", { protocolVersion: 1, ...(clientInfo ? { clientInfo } : {}), clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } }) }) } @@ -621,9 +673,9 @@ export function parseStatusLineQuota(quota) { // served is the quota of an account print mode refused at the eligibility // check while agy serves it (above), or null: the refusal then stands. -async function servedQuota(agy, folder, options) { +async function servedQuota(agy, folder, options, acp = {}) { if (!terminalSpawn()) return null - const tier = await acpTier(agy, folder?.gateway ? ["--gemini-dir", folder.dir] : [], options) + const tier = await acpTier(agy, folder?.gateway ? ["--gemini-dir", folder.dir] : [], { ...options, ...acp }) if (!tier) return null const quota = await statusLineQuota(agy, folder?.gateway ? ["--gemini_dir", folder.dir] : [], options) if (!quota) return null @@ -644,6 +696,10 @@ export async function fetchUsage(agy, { // one reading it makes, when the user asks for it: agy's own /usage, run // headless, and nothing else (plugins#1824) printOnly = false, + // what a turn's agy acp is run with (index.mjs): its flags, by agy + // (async), and its client name + acpArgs = async () => [], + clientInfo, } = {}) { if (!agy) throw new UsageError(NO_AGY) const folder = await geminiDir(agy) @@ -724,7 +780,7 @@ export async function fetchUsage(agy, { : result.stderr + "\n" + result.stdout const failure = commandFailure(said) if (failure.ineligible && !printOnly) { - const served = await servedQuota(agy, folder, options) + const served = await servedQuota(agy, folder, options, { acpArgs: await acpArgs(agy).catch(() => []), clientInfo }) if (served) return served } throw failure @@ -782,7 +838,7 @@ export const NO_AGY = "agy CLI not found. Sign in to this account again in magpi const NEEDS_SIGN_IN = "Sign in again from this account's Sign in in magpie, or run `agy` in a terminal; magpie doesn't run agy for usage until then." // what usage says while agy's access token is due to be renewed (below) -export const DUE_FOR_RENEWAL = "agy's sign-in is due to be renewed, and agy renews it itself on this account's next chat; the quota is read after that. " + +export const DUE_FOR_RENEWAL = "agy's sign-in is due to be renewed, and agy renews it itself on this account's next chat; refresh usage again after that chat to read the quota. " + "magpie doesn't run agy just for usage meanwhile: a renewal that fails there can open a Google sign-in in the browser." // what usage says while agy is still reading, past what the caller waits @@ -800,7 +856,8 @@ export const STILL_READING = "agy is still reading this account's quota (its own // when it runs, and when that renewal fails, even for a moment (DNS at // startup, a slow keyring), agy starts its own Google sign-in, which on // Windows opens the browser past every shim (plugins#1234). agy's chats -// renew it; the quota is read once they have (DUE_FOR_RENEWAL). The +// renew it; a refresh after one reads the quota (DUE_FOR_RENEWAL): +// nothing reads it by itself once a chat has renewed the token. The // plugin never renews it, nor asks Google itself. // - an explicit authentication rejection, or an ended token hanging silently // or with sign-in talk, blocks further background runs for that credential. @@ -816,11 +873,33 @@ export const STILL_READING = "agy is still reading this account's quota (its own // Magpie waits 20 seconds for a usage call; agy's own read can take // longer (fetchUsage). A call waits waitMs at most and then says agy is // still reading (STILL_READING); the read goes on to its own deadline, and -// what it reads with nobody waiting is kept for the next call (taken once, -// within LATE_KEPT_MS), so the next refresh shows it without running agy -// again. A failure is held as any other is. +// what it reads with nobody waiting is kept until the next call takes it: +// nothing reads usage in the background (0.1.186), so a refresh is the only +// reader, and "It shows on the next refresh" holds however long the user +// takes to refresh again (#1877). The next call: +// - within LATE_FRESH_MS takes it as its answer, without running agy again; +// - later reads again, and answers with the kept reading in place of +// STILL_READING when agy is slow again: a reading of minutes or hours +// ago, with its windows' reset times, says more than "still reading". +// It is let go when it can no longer be right, or isn't this account's: +// once one of its windows has reset (its use then says too much), and at +// LATE_KEPT_MS at most, the shortest window agy reports (5h), for a reading +// with no reset time; when the sign-in changes (another account, signed +// out or ended) or another agy is found; and when a read after it fails, +// which is then what the account shows (held as any other failure is). const CALL_WAIT_MS = 17_000 -const LATE_KEPT_MS = 3 * 60 * 1000 +const LATE_FRESH_MS = 3 * 60 * 1000 +const LATE_KEPT_MS = 5 * 60 * 60 * 1000 + +// until when a reading taken at `at` can be kept (above) +function keptUntil(reply, at) { + let until = at + LATE_KEPT_MS + for (const w of reply?.windows ?? []) { + const reset = Date.parse(w?.resetsAt ?? "") + if (Number.isFinite(reset)) until = Math.min(until, reset) + } + return until +} export function createUsageReader(resolveAgy, options = {}) { const { signIn = () => storedSignIn(), now = () => Date.now(), waitMs = CALL_WAIT_MS, onSettled = () => {}, ...fetchOptions } = options @@ -837,12 +916,14 @@ export function createUsageReader(resolveAgy, options = {}) { if (!outcome.error) { const result = { ...structuredClone(outcome.result), signIn: saidExpired ? "renewed" : "kept" } held = null + late = null saidExpired = false return result } const error = outcome.error const message = error instanceof UsageError ? error.message : "agy usage query failed. Check the CLI and temporary-directory permissions." if (error?.kind === "cancel") return { windows: [], error: message, signIn: "kept" } + late = null const output = String(error.output ?? "") const auth = error?.kind === "auth" || error?.kind === "timeout" && stored?.state === "present" && stored.expired && (!output.trim() || SIGN_IN_TALK.test(withoutDiagnostics(output))) @@ -863,20 +944,26 @@ export function createUsageReader(resolveAgy, options = {}) { let stored try { stored = await signIn() } catch { stored = { state: "unknown" } } const why = cannotSignIn(stored) + // signed out or ended: a reading kept from before isn't kept + if (why || isDead(stored)) late = null // out of this process's reach, signing in again here mends nothing if (why && stored?.state === "unreachable") return { windows: [], error: `${why}.`, signIn: "expired" } if (why) return expired(why) if (isDead(stored)) return expired("agy's sign-in no longer works") const key = stored?.state === "present" ? stored.fp : "unknown" const agy = resolveAgy() + // another sign-in or another agy, or past what it can be kept for + if (late && (late.key !== key || late.agy !== agy || now() >= late.until)) late = null if (!agy) return { windows: [], error: NO_AGY, signIn: "kept" } - // read while nobody waited: this call's answer, once - if (late && late.key === key && late.agy === agy && (late.printOnly || !printOnly) && now() - late.at < LATE_KEPT_MS) { - const { reply } = late + // a reading kept for a printOnly call is any read's; one a read that + // could fall back made is no printOnly call's (it runs agy -p alone) + const keptFor = () => late && late.key === key && late.agy === agy && (late.printOnly || !printOnly) && now() < late.until ? late : null + // read while nobody waited, minutes ago: this call's answer, once + const kept = keptFor() + if (kept && now() - kept.at < LATE_FRESH_MS) { late = null - return reply + return structuredClone(kept.reply) } - late = null // a failure held for another agy (gone, another found since, or this // one updated in place) isn't this one's const binary = await binaryKey(agy) @@ -897,7 +984,10 @@ export function createUsageReader(resolveAgy, options = {}) { if (pending.get(reading) === entry) pending.delete(reading) const reply = settle(outcome, { agy, binary, key, stored }) // nobody waits for it any more: the next call takes it - if (entry.waiting === 0 && !outcome.error) late = { key, agy, reply, printOnly, at: now() } + if (entry.waiting === 0 && !outcome.error) { + const at = now() + late = { key, agy, reply, printOnly, at, until: keptUntil(reply, at) } + } onSettled(reply) return reply }) @@ -911,6 +1001,9 @@ export function createUsageReader(resolveAgy, options = {}) { clearTimeout(timer) read.waiting-- if (reply) return structuredClone(reply) + // agy is slow again: what was read before, while it reads on + const before = keptFor() + if (before) return { ...structuredClone(before.reply), signIn: "kept" } return { windows: [], error: STILL_READING, signIn: "kept" } } }