agy-cli: Antigravity on the local agy CLI over ACP (#785)
New package `@magpie-community/opencode-agy-cli-auth` (provider `agy-cli`, `packages/agy-cli`). It serves Antigravity models through the user's installed `agy` CLI over ACP (`agy acp`) and uses agy's own Google sign-in. The plugin reads and writes no Google tokens. The bridge is gitxm's. On top of it, after review: - **ACP identity.** The client names itself (`opencode-agy-cli-auth` and its package version) instead of `zed`. - **Catalog.** - Only what agy offers this client is listed: Gemini until a session says more, then the session's model option and `availableModels`. - Requests are still routed by everything `agy models` lists. - **Prompt.** agy keeps its own system prompt by default. The minimal agent is opt-in with `AGY_BRIDGE_MINIMAL_AGENT=1`, and the README says what turning it on sends upstream. - **Version check.** agy older than 1.4.12 is refused at the handshake. 1.4.12 is the oldest version the `nc` MCP bridge was checked on, and the README documents the bridge. - **Auto-update.** - `AGY_CLI_DISABLE_AUTO_UPDATE` defaults to `true` only for the plugin's own agy processes. - A value the user set is passed on as written. - **Docs.** The READMEs and the registry summary say how this differs from antigravity-acp (#87). - **Tests.** The author's tests came over under `test/` with a fake agy (an ACP stdio server). Each suite runs in its own `bun test`, and a `mock.module` preload stands in for `node:child_process`. - **Cleanup.** A duplicate, unreachable image branch in validateBody is gone. Run at ae5eafb0 on mote (macOS) with HOME=$(mktemp -d): - `bun test packages/agy-cli`: 7 pass. Per suite: - platform 14, compat 9, usage 20; - catalog 15, usage-settlement 18, repeat-batch 14; - smoke ALL OK (301 checks). - `bun scripts/check.mjs`: all ok. - Repo-wide `bun test`: 6792 pass, 0 fail (6812 tests, 492 files). Broken by hand, and each went red: - clientInfo set back to zed; - the version check turned off; - routing limited to the listed models; - auto-update forced to true; - the minimal agent on by default. Not tried: a real agy, since mote has none, or a real Antigravity account. Co-authored-by: gitxm <21175063+gitxm@users.noreply.github.com>
This commit is contained in:
@@ -13,6 +13,7 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
|---|---|---|
|
||||
| [agnes](packages/agnes) | Agnes AI international (agnes-ai.com), with Chrome browser sign-in, live text models, plan usage and USD balance | `agnes` |
|
||||
| [agnes-code](packages/agnes-code) | Agnes AI's Agnes Code desktop, with the desktop's saved session (Windows) or a pasted access token: live models, daily credit check-in and points balance (unofficial) | `agnes-code` |
|
||||
| [agy-cli](packages/agy-cli) | Antigravity on your installed agy CLI through ACP (`agy acp`), with agy's own Google sign-in: only the models agy offers this client, a process pool, MCP tool bridge and session resume (unofficial) | `agy-cli` |
|
||||
| [astudio](packages/astudio) | iFlytek's AStudio (科大讯飞 Astron Studio desktop), with the desktop's saved credentials or a pasted model token: live model catalog, daily login-points check-in and points balance (unofficial) | `astudio` |
|
||||
| [atomcode](packages/atomcode) | AtomGit CodingPlan, with browser OAuth or the local AtomCode CLI's sign-in, signed requests, live models, quota windows and a read-only diagnostics page (unofficial) | `atomcode` |
|
||||
| [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` |
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 DylanLIiii
|
||||
Copyright (c) 2026 gitxm
|
||||
Copyright (c) 2026 yce
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,90 @@
|
||||
# NOTICE:来源与合规说明
|
||||
|
||||
本包(`@magpie-community/opencode-agy-cli-auth`,版本 0.1.0)源自 Antigravity 桥接插件
|
||||
`opencode-antigravity-bridge`,由 gitxm 整理为 `gitxm/yce-magpie-agy` 后提交到
|
||||
magpie-community/plugins(plugins#785),以 MIT 协议发布。**与上游无隶属关系。** 上游版权声明原样保留在 [LICENSE](LICENSE),
|
||||
本仓新增部分的版权归 gitxm 与 yce。
|
||||
|
||||
## 1. 包与标识
|
||||
|
||||
| 项目 | 取值 |
|
||||
|---|---|
|
||||
| npm 包名 | `@magpie-community/opencode-agy-cli-auth` |
|
||||
| 版本 | `0.1.0` |
|
||||
| 仓库 | `https://github.com/magpie-community/plugins`(`packages/agy-cli`) |
|
||||
| Magpie provider ID | `agy-cli` |
|
||||
| 安装 | `magpie plugin add @magpie-community/opencode-agy-cli-auth` |
|
||||
| 原始仓库 | `https://github.com/gitxm/yce-magpie-agy`(包名 `@magpie-community/yce-magpie-agy`、provider ID `yce-magpie-agy`,均未发布到 npm) |
|
||||
|
||||
进程内部标识保持不变,以免影响已有的状态文件与日志:`AGY_BRIDGE_*` 环境变量、
|
||||
`magpie-agy-bridge/` 状态与临时目录、`[agy-bridge]` 日志前缀、导出名 `AntigravityBridgePlugin`。
|
||||
|
||||
## 2. 来源基线
|
||||
|
||||
| 基线 | 版本指纹 | 说明 |
|
||||
|---|---|---|
|
||||
| 上游主干 | `DylanLIiii/opencode-antigravity-bridge@7e13b127a62e8eaa41d8de2d3eedd8afe1cfd4eb` | 上游 main 的 HEAD |
|
||||
| PR #8 基线(代码底稿) | `gitxm/opencode-antigravity-bridge@acb8d84c5136d18889d7d4b91f119117b57abb74` | 分支 `fix/windows-bg-updater-popup`,父提交为上游 `7e13b12`;包含 `platform.mjs`、Windows 无弹窗修复与多步用量结算 |
|
||||
| 本机补丁(`index.mjs`) | `index.mjs.patched`,md5 `38aa8d42f3e76a2536d11be63b5807a5` | 基于上游 `212179f` 的本机补丁版 |
|
||||
| 本机补丁(`usage.mjs`) | `usage.mjs.patched`,md5 `df212a2c934ffd4a38d7f3ef95271c5d` | 基于上游 `7e13b12` 的本机补丁版 |
|
||||
|
||||
合并原则:代码以 PR #8(`acb8d84`)为底。本机补丁中 `acb8d84` 没有的修复,按下面的
|
||||
A1–A16、U1–U6 逐项并入。两边都有、且 `acb8d84` 写法更新的部分(多步用量结算、
|
||||
`requestedEffort`、`withStateLock`、`lineageVerdict`、`matchToolResults`、`inspectToolTurn`
|
||||
等)保留 `acb8d84` 的实现,不搬运补丁版代码。
|
||||
|
||||
## 3. `index.mjs` 并入的修复(A1–A16)
|
||||
|
||||
| 编号 | 内容 |
|
||||
|---|---|
|
||||
| A1 | 模型目录缓存:TTL 5 分钟;首次最多等 500 ms,超时先返回旧目录,后台单飞刷新;刷新失败保留上次成功结果;启动时先用 `FALLBACK_MODELS` 预热。`provider.models()` 不再每次强制执行 `agy models` |
|
||||
| A2 | `listAgyModels` 在报错、超时、退出码非 0 或输出为空时返回 `null`,不再用兜底列表覆盖动态目录 |
|
||||
| A3 | `execOnce` 超时立即 resolve(带 `timedOut`),子孙进程占着管道也不会挂起;后台刷新路径的计时器 `unref()`,前台调用保持 ref |
|
||||
| A4 | 为 `gpt-oss-120b` 补充指向 medium 的裸名别名 |
|
||||
| A5 | `modelLimits(id)`:`provider.models()` 输出每个型号的 `limit`(上下文与输出上限),与 `capabilities` 并存 |
|
||||
| A6 | `findAgy` 缓存键包含 `AGY_PATH`、`PATH`/`Path`、`LOCALAPPDATA` 与 home 目录,环境变化时重新查找 |
|
||||
| A7 | 无进展重复上限:同一无进展回合连续收到对不上的工具结果,前两次返回 409,第三次强制回收并重放;重放不了则返回终止性 400。`recoverStaleTurn` 区分 active、conflict、incomplete、replayed、fallthrough 五种情况 |
|
||||
| A8 | `jsonError(status, message, code, { extra, headers, noRetry })`,支持把 `extra` 并入 error 对象(A7 依赖它) |
|
||||
| A9 | 工具调用 30 ms 合批:相邻事件循环里到达的 MCP 调用合并到同一次响应;`Turn.next` 带等待者清理;按 `emittedIds` 去重;文本与结束事件的边界不合并 |
|
||||
| A10 | `canonicalBody` 只提取开头连续的 `role=system` 消息(沿用上游 `acb8d84` 规则),保证 Claude Code 尾随的 system 通知不会触发第二轮重建会话;同时并入 `contentText`、`requestLayout`、`noteLayout` 布局追踪 |
|
||||
| A11 | 诊断事件限流(60 秒窗口最多 30 条,附 `suppressed` 计数);请求级 `req_id`;冲突事件输出 `idle_ms` 与 `pending`;过期原因细分为 finalized、dead、done、running;`layout_flip` 只在 `AGY_BRIDGE_EVENTS=verbose` 时输出 |
|
||||
| A12 | `Turn.rawAcpUsages` 保存每个已记账 prompt 的原始 ACP usage 对象 |
|
||||
| A13 | `addUsage` 通过 `tokenCount` 把累加结果限制为非负整数 |
|
||||
| A14 | `reclaimStaleTurn` 同时清除该会话的无进展重复计数 |
|
||||
| A15 | 防止 503 进程池饿死:并发上限默认值由 8 改为 16(`AGY_BRIDGE_MAX_PROCS`,`magpie.maxConcurrency` 同为 16)。`evictLRU` 分两级淘汰,第二级淘汰客户端已断开超过 30 秒(`AGY_BRIDGE_DETACHED_EVICT_MS`)的挂起工具回合,之后补交的合法 `tool_result` 会在新进程上重放。`acquireProcLocked` 遇到同会话旧回合时先判断过期并回收。历史压缩后变短的新请求判为 fork,回收旧回合 |
|
||||
| A16 | 长历史重放预算:`renderInitialPromptParts` 默认限制在 112 KiB(`AGY_BRIDGE_MAX_PROMPT_BYTES`)内。先为必保段预留预算(system 说明、`</conversation_history>` 闭合标签及禁止输出工具调用声明的文字、完整的 `<current_turn>`),历史按头尾保留,超长的 `[tool result]` 保留首尾、省略中间,保证不被 agy 的 128 KiB 尾部截断切掉 |
|
||||
|
||||
## 4. `usage.mjs` 并入的修复(U1–U6)
|
||||
|
||||
| 编号 | 内容 |
|
||||
|---|---|
|
||||
| U1 | 去掉 win32 上直接报错 `agy bridge usage queries currently require macOS or Linux.` 的限制;接入 `agySpawnSpec`,兼容 `.cmd` 与 `.bat`,使 Windows 上的 `magpie quota` 可用 |
|
||||
| U2 | `spawn` 只在非 Windows 上使用 `detached`,Windows 上一律 `windowsHide: true` |
|
||||
| U3 | Windows 进程树清理:先执行 `taskkill /T /F /PID` 清除进程树,只有 `taskkill` 失败或超时才补 `SIGKILL`,避免提前杀掉父进程导致 `taskkill` 漏杀子树。父进程正常退出后延迟 30 ms 再清理进程树;`finish()` 只在出错或子进程仍在运行时清理 |
|
||||
| U4 | Windows 上拦截浏览器启动:写入内容为 `@exit /b 1` 的 `open.cmd`,并让 `BROWSER` 指向它 |
|
||||
| U5 | PATH 大小写去重:删除非大写的 `Path` 键,继承 `env.PATH`,没有时回落到 `env.Path` |
|
||||
| U6 | 临时目录删除遇到 `EBUSY`、`EPERM`、`ENOTEMPTY` 时,先等待在途的 `taskkill` 释放目录句柄,再最多重试 4 次,每次间隔递增 50 ms |
|
||||
|
||||
## 5. 包与文档层改动
|
||||
|
||||
- 包名改为 `@magpie-community/opencode-agy-cli-auth`,版本 `0.1.0`,`repository` 指向 magpie-community/plugins 的 `packages/agy-cli`。
|
||||
- `magpie.maxConcurrency` 与 `AGY_BRIDGE_MAX_PROCS` 默认值统一为 16。
|
||||
- `README.md`、`README.en.md` 整篇重写,`LICENSE` 追加本仓版权行。原仓库的 `HANDOFF.md` 不随包发布。
|
||||
- `NOTICE.md`(本文件)与 `LICENSE` 一并随包发布。
|
||||
|
||||
## 6. 版权
|
||||
|
||||
[LICENSE](LICENSE) 保留上游版权行 `Copyright (c) 2026 DylanLIiii`,并依次列出
|
||||
`Copyright (c) 2026 gitxm` 与 `Copyright (c) 2026 yce`。MIT 正文未作修改。
|
||||
|
||||
## 7. 从旧版迁移
|
||||
|
||||
旧版是包名 `magpie-agy` 0.2.0,provider ID 为 `antigravity-bridge`。改为 0.1.0 后:
|
||||
|
||||
1. **provider ID 变化**:Magpie 中的 provider 变为 `agy-cli`。所有写着旧 ID 的模型名
|
||||
(`antigravity-bridge/<模型>`,或从 GitHub 安装 `gitxm/yce-magpie-agy` 时的 `yce-magpie-agy/<模型>`)
|
||||
都要改成 `agy-cli/<模型>`,包括路由组和会话里的模型引用。
|
||||
2. **登录态**:登录状态按 provider ID 记录。切换后需要在新 provider 上重新登录,或者把登录记录改名。
|
||||
3. **内部状态不变**:会话停车文件仍在 `magpie-agy-bridge/sessions.json`,已有会话可以续接。
|
||||
4. **切换顺序**:先安装新包,确认新 provider 能返回 200,再逐个改模型名;旧包最后移除。
|
||||
本仓内不执行切换操作。
|
||||
@@ -0,0 +1,231 @@
|
||||
# agy-cli
|
||||
|
||||
Turn the local Antigravity CLI (`agy`) into a model provider inside Magpie. Once
|
||||
it is set up, clients such as OpenCode and Claude Code can reach the models agy
|
||||
offers this plugin through Magpie, and every request is actually carried out by
|
||||
an `agy` process.
|
||||
|
||||
**[中文 → README.md](README.md)** · Provenance, licensing and migration notes:
|
||||
[NOTICE.md](NOTICE.md)
|
||||
|
||||
## What it is
|
||||
|
||||
The plugin runs as a Magpie provider. A client sends an Anthropic Messages
|
||||
request; the plugin turns it into Agent Client Protocol (ACP) messages, hands
|
||||
them to a local `agy acp` process, and converts the output back into a streamed
|
||||
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, and the plugin does
|
||||
not call Google's internal endpoints directly.
|
||||
- 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
|
||||
calls.
|
||||
- Account standing is outside the plugin's control. If Google changes its usage
|
||||
policies, the plugin cannot promise your account will not be restricted.
|
||||
|
||||
## How it differs from Antigravity ACP
|
||||
|
||||
The community Antigravity ACP plugin (`antigravity-acp`) serves the same
|
||||
channel: Antigravity's models over ACP. The differences:
|
||||
|
||||
- **What runs**: Antigravity ACP downloads Google's ACP server
|
||||
(`agy_acp_server.par`, about 400 MB) and rides the Antigravity IDE's sign-in.
|
||||
This plugin downloads nothing; it runs the `agy` CLI you installed and signed
|
||||
in to yourself (`agy acp`).
|
||||
- **Sessions**: Antigravity ACP opens a new session per request and carries the
|
||||
history as context. This plugin keeps a pool of agy processes, reuses one agy
|
||||
session for one conversation, and picks it up again with `session/resume`
|
||||
after a restart; only when that fails does it replay the history, within a
|
||||
byte budget.
|
||||
- **Tool calls**: Antigravity ACP ends the turn with the call as the reply's
|
||||
`tool_calls`. This plugin feeds the client's result back into the same agy
|
||||
turn (see "Tool bridge" below).
|
||||
- **Usage**: this plugin reads agy's own `/usage` report; Antigravity ACP reads
|
||||
the quota each reply carries.
|
||||
|
||||
## Tool bridge
|
||||
|
||||
agy reaches `--ide-mcp-port` by running `nc 127.0.0.1 <port>`. The plugin puts
|
||||
a private `nc` first on agy's PATH, which connects that line to the plugin's own
|
||||
MCP server. The control port listens on loopback only, with a token per process.
|
||||
|
||||
- This rests on how agy dials, not on an interface agy promises. It was checked
|
||||
on 1.4.12 and 1.5.0. On an agy older than 1.4.12 the plugin refuses the session
|
||||
and says to update.
|
||||
- The private `nc` applies only to the agy processes the plugin starts, but for
|
||||
those it stands in for every `nc` agy runs.
|
||||
|
||||
## Features
|
||||
|
||||
- **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, and before the first session only Gemini is listed.
|
||||
Models and thinking levels can be switched mid-conversation without losing
|
||||
history.
|
||||
- **Streaming with thought summaries**: summaries come back as `thinking` blocks.
|
||||
Set `AGY_BRIDGE_THINKING=0` to turn them off.
|
||||
- **Image input**: inline base64 PNG, JPEG, GIF and WebP. This needs agy 1.5.0 or
|
||||
newer, because the ACP server has to advertise image support.
|
||||
- **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.
|
||||
- **Session resume**: each finished turn is recorded. After a Magpie or plugin
|
||||
restart, the session continues through `session/resume` as long as the history
|
||||
and instruction hashes still match. The state file stores session IDs and
|
||||
hashes, never message text.
|
||||
- **Isolation**: your global MCP configuration is never read. Every agy process
|
||||
runs with a temporary agent, and every permission request agy raises (shell,
|
||||
file edits, browser) is refused. Real actions happen on the client side.
|
||||
- **Usage visibility**: Magpie shows the agy subscription usage windows. They are
|
||||
informational only; running out of quota does not block requests automatically.
|
||||
|
||||
## Requirements
|
||||
|
||||
- The Antigravity CLI (`agy`) with the `acp` subcommand, signed in to a Google
|
||||
account at least once from an interactive terminal. Text and tool calls have
|
||||
been verified on 1.4.12 and 1.5.0; image input needs 1.5.0.
|
||||
- A Magpie build with OpenCode-style provider plugin support. Usage reporting was
|
||||
verified on Magpie 0.1.1599.
|
||||
- agy older than 1.4.12 is refused for sessions (see "Tool bridge"), and older
|
||||
than 1.1.11 for usage queries too, because those builds can treat `/usage` as
|
||||
an ordinary model prompt.
|
||||
- **Auto-update**: the agy processes the plugin starts get
|
||||
`AGY_CLI_DISABLE_AUTO_UPDATE=true` by default, so the processes in the pool
|
||||
don't update one binary under each other. agy runs you start yourself are not
|
||||
affected and update as usual. If you set `AGY_CLI_DISABLE_AUTO_UPDATE`
|
||||
yourself (`false` included), the plugin passes your value on as written. If
|
||||
you use agy only through this plugin, run `agy` in a terminal now and then so
|
||||
it updates: an old version stands out too.
|
||||
|
||||
## Install
|
||||
|
||||
From the Magpie community plugins: find "Antigravity (local agy CLI)" on
|
||||
Magpie's Plugins page and install it, or run:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/opencode-agy-cli-auth
|
||||
```
|
||||
|
||||
The provider id is `agy-cli`, so models are named `agy-cli/<model>`. The
|
||||
default concurrency is 16; change it under Concurrency on Magpie's Providers
|
||||
page (0 means no limit).
|
||||
|
||||
After installing, run `agy` once in a terminal to complete the Google sign-in.
|
||||
|
||||
## Usage
|
||||
|
||||
1. Open Magpie's Providers page, find `agy-cli`, and click Sign in. The
|
||||
plugin uses `agy models` to confirm the CLI works. Google credentials stay with
|
||||
agy; the plugin never reads or stores them.
|
||||
2. Refer to models as `agy-cli/<model>`. When agy lists separate model IDs
|
||||
for different thinking levels, they are grouped here as variants of one model,
|
||||
and each request is mapped back to the matching agy ID.
|
||||
3. Pick the model in your client as usual.
|
||||
|
||||
## Concurrency
|
||||
|
||||
- The plugin's own pool is capped by `AGY_BRIDGE_MAX_PROCS`, which defaults to 16
|
||||
agy processes.
|
||||
- Magpie's Providers page has its own Concurrency field that accepts 0 to 1000,
|
||||
where 0 means no limit. A value set there overrides the default of 16 that the
|
||||
plugin declares in `magpie.maxConcurrency`.
|
||||
- When the pool is full and no process can be evicted, the plugin answers with
|
||||
HTTP 503. Keep the two numbers aligned: if the Providers page allows more
|
||||
concurrent requests than the pool holds, the extra ones will get 503.
|
||||
|
||||
## Platforms
|
||||
|
||||
- **macOS and Linux**: supported.
|
||||
- **Native Windows**: supported for `.exe`, `.cmd` and `.bat` lookup and launch,
|
||||
silent background update checks, and `magpie quota`. So far only the command
|
||||
construction has unit tests; end-to-end runs on real Windows hardware are still
|
||||
pending.
|
||||
|
||||
## Usage quota
|
||||
|
||||
```sh
|
||||
magpie quota agy-cli --json
|
||||
magpie quota refresh agy-cli --json
|
||||
```
|
||||
|
||||
The numbers come from agy's own `/usage` report for whichever account is signed
|
||||
in to the CLI, broken down by model group. The plugin does not read or write
|
||||
Google tokens; it always reports the account agy is signed in to. A window with no
|
||||
measurable data shows "Limits not available" rather than a fake 0% or 100%.
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Name | Default value | What it does |
|
||||
|---|---|---|
|
||||
| `AGY_PATH` | PATH lookup | Path to the agy executable |
|
||||
| `AGY_BRIDGE_MAX_PROCS` | 16 | Maximum number of agy processes in the pool |
|
||||
| `AGY_BRIDGE_THINKING` | on | Set to `0` to stop forwarding thought summaries |
|
||||
| `AGY_BRIDGE_EFFORT` | unset | Force a thinking level: `minimal`, `low`, `medium`, `high`, `xhigh` or `max` |
|
||||
| `AGY_BRIDGE_MINIMAL_AGENT` | off | Set to `1` to drop agy's own prompt components; see "Minimal agent" below |
|
||||
| `AGY_BRIDGE_IDLE_MS` | 600000 | How long a process may sit idle before it is reclaimed; the session can still resume |
|
||||
| `AGY_BRIDGE_RESUME_TTL_MS` | 21600000 | How long a reclaimed session stays resumable (6 hours) |
|
||||
| `AGY_BRIDGE_STATE_FILE` | `$XDG_STATE_HOME/magpie-agy-bridge/sessions.json` | Where resumable session records are kept |
|
||||
| `AGY_BRIDGE_IDE_CALL_DEADLINE_MS` | 150000 | After this long, a still-running client tool gets a "still running" reply |
|
||||
| `AGY_BRIDGE_START_TIMEOUT_MS` / `_TURN_TIMEOUT_MS` / `_TOOL_TIMEOUT_MS` | 60 s / 5 min / 30 min | Limits for process startup, agy silence, and waiting on a client tool result |
|
||||
| `AGY_BRIDGE_DETACHED_EVICT_MS` | 30000 | How long a suspended tool turn whose client disconnected may keep its pool slot |
|
||||
| `AGY_BRIDGE_MAX_PROMPT_BYTES` | 114688 (112 KiB) | Byte budget for the replayed history prompt |
|
||||
| `AGY_BRIDGE_USAGE_TIMEOUT_MS` | 15000 | Total time budget for a usage query, capped at 18000 |
|
||||
| `AGY_BRIDGE_MCP_TRACE` | unset | Writes MCP channel traffic to the given file; for debugging only |
|
||||
| `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" |
|
||||
|
||||
## Minimal agent (`AGY_BRIDGE_MINIMAL_AGENT=1`)
|
||||
|
||||
By default agy runs every request with its own system prompt, and the
|
||||
client's system prompt is added to it: in the session when agy advertises
|
||||
`systemPrompt.append`, otherwise as `<external_system_instructions>` at the
|
||||
start of the first prompt.
|
||||
|
||||
Set to `1`, the temporary agent carries `excludeDefaultComponents: true`. The
|
||||
request that goes upstream then has none of agy's own system prompt, only
|
||||
the plugin's one-line tool note and the client's system prompt (sent in one
|
||||
of the two ways above). The original author measured about 8,400 input
|
||||
tokens per model call with agy's prompt and about 500 without. The cost is
|
||||
that upstream no longer sees agy's own request shape, which is why it is
|
||||
off unless you turn it on.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **agy cannot be found**: set `AGY_PATH` to the executable, or make sure `agy`
|
||||
is on PATH.
|
||||
- **Sign in fails, or agy reports a login problem**: run `agy` in a terminal and
|
||||
finish the Google sign-in again.
|
||||
- **HTTP 503**: the pool is full. Raise `AGY_BRIDGE_MAX_PROCS` and the Providers
|
||||
page Concurrency, or reduce the number of simultaneous sessions.
|
||||
- **Usage shows "Limits not available" or a version error**: that window has no
|
||||
measurable data. For a version error, upgrade agy to 1.1.11 or later.
|
||||
- **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
|
||||
and binary documents such as PDFs are rejected.
|
||||
- **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.
|
||||
- **HTTP 409 saying tool results do not match the history**: usually the client
|
||||
rewrote the history or tool IDs mid-conversation. When the plugin can work out
|
||||
the correct match it rebuilds the session; when it cannot, it refuses rather
|
||||
than guessing.
|
||||
- **Turning thought summaries off**: set `AGY_BRIDGE_THINKING=0`, or send
|
||||
`thinking: { "type": "disabled" }` with the request.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
bun test packages/agy-cli # from the repo root
|
||||
bun scripts/check.mjs agy-cli
|
||||
```
|
||||
|
||||
The tests run the full ACP and MCP path against a fake agy (an ACP stdio server
|
||||
under `test/`), so they never start the real agy and use no quota.
|
||||
|
||||
## License
|
||||
|
||||
MIT. Copyright notices live in [LICENSE](LICENSE); upstream provenance and the
|
||||
list of changes are in [NOTICE.md](NOTICE.md).
|
||||
@@ -0,0 +1,181 @@
|
||||
# agy-cli
|
||||
|
||||
把本机的 Antigravity CLI(`agy`)接成 Magpie 里的一个模型 provider。装好以后,
|
||||
OpenCode、Claude Code 等客户端经由 Magpie 调用 agy 向本插件开放的模型,请求实际由
|
||||
`agy` 进程完成。
|
||||
|
||||
**[English → README.en.md](README.en.md)** | 来源、版权与迁移说明见 [NOTICE.md](NOTICE.md)
|
||||
|
||||
## 这是什么
|
||||
|
||||
插件以 Magpie provider 的形式运行。客户端发来 Anthropic Messages 格式的请求,插件把它
|
||||
翻译成 ACP(Agent Client Protocol)消息,交给本机的 `agy acp` 进程处理,再把输出翻译回
|
||||
流式响应。
|
||||
|
||||
- 底层是真正的 agy CLI,走它自带的 ACP 通道。ACP 握手里的 `clientInfo` 是本插件自己的
|
||||
包名和版本(`opencode-agy-cli-auth`),不冒充 Zed 或其它编辑器;插件也不直接请求 Google
|
||||
的内部接口。
|
||||
- 客户端自己的工具(读写文件、执行命令等)通过 MCP 暴露给模型。工具由客户端执行,结果
|
||||
回传到同一轮 agy 对话里,模型看到的是原生工具调用。
|
||||
- 账号风险不由插件决定。Google 的使用政策变化时,插件无法替你保证账号不受限制。
|
||||
|
||||
## 与 Antigravity ACP 的区别
|
||||
|
||||
社区里的 Antigravity ACP(`antigravity-acp`)走的是同一个渠道:Antigravity 的模型经由 ACP。
|
||||
两者的区别:
|
||||
|
||||
- **运行的程序**:Antigravity ACP 自己下载 Google 的 ACP 服务端(`agy_acp_server.par`,
|
||||
约 400 MB),依赖 Antigravity IDE 的登录。本插件不下载任何东西,运行你自己装好、自己
|
||||
登录过的 `agy` CLI(`agy acp`)。
|
||||
- **会话**:Antigravity ACP 每个请求开一个新会话,把历史当作上下文带上。本插件维护一个
|
||||
agy 进程池,同一段对话复用同一个 agy 会话,重启后用 `session/resume` 接上;只有接不上时
|
||||
才在字节预算内重放历史。
|
||||
- **工具调用**:Antigravity ACP 把工具调用作为回复的 `tool_calls` 结束这一轮。本插件把
|
||||
客户端的结果送回同一轮 agy 对话(见下文「工具桥接」)。
|
||||
- **额度**:本插件读 agy 自己的 `/usage` 报告;Antigravity ACP 读每次回复带的配额。
|
||||
|
||||
## 工具桥接
|
||||
|
||||
agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy 的 PATH 最前面放一个
|
||||
私有的 `nc`,它把这条连接接到插件自己的 MCP 服务上;控制端口只监听本机回环地址,每个进程
|
||||
有自己的令牌。
|
||||
|
||||
- 这依赖 agy 拨号的方式,不是 agy 公开承诺的接口,已在 1.4.12 和 1.5.0 上验证。agy 低于
|
||||
1.4.12 时,插件会直接报错并提示升级。
|
||||
- 这个 `nc` 只对插件启动的 agy 进程生效,但对这些进程来说,它替换了 agy 运行的所有 `nc`。
|
||||
|
||||
## 功能
|
||||
|
||||
- **agy 开放的模型**:模型列表以 ACP 会话里 agy 给出的模型选项为准。`agy models` 列出的
|
||||
模型如果没有在会话里向本客户端开放(agy 可能只向它认可的客户端开放 Claude、GPT-OSS),
|
||||
就不会出现在列表里;第一个会话建立之前只列 Gemini。模型和思考等级可以在会话中切换,
|
||||
历史保留。
|
||||
- **流式输出与思考摘要**:思考摘要以 `thinking` 块返回,设置 `AGY_BRIDGE_THINKING=0` 可关闭。
|
||||
- **图片输入**:支持内联 base64 的 PNG、JPEG、GIF、WebP。需要 agy 1.5.0 或更新版本,
|
||||
因为图片能力要由 ACP 服务端声明。
|
||||
- **工具调用**:支持并行和连续调用。运行超过 150 秒的工具会先收到 "still running" 的
|
||||
占位响应,真正的结果送达后继续同一轮对话,每个调用只在客户端执行一次。
|
||||
- **会话续接**:每轮结束后记录会话。重启 Magpie 或插件后,只要历史和指令的哈希一致,
|
||||
就用 `session/resume` 接上上下文。状态文件只存会话 ID 与哈希,不存消息原文。
|
||||
- **隔离运行**:不读取你的全局 MCP 配置。每个 agy 进程使用临时 agent。agy 发起的权限
|
||||
请求(shell、写文件、浏览器等)一律拒绝,真正的操作都在客户端侧完成。
|
||||
- **额度查看**:在 Magpie 里查看 agy 订阅的用量窗口,仅作展示,额度耗尽时不会自动拦截请求。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Antigravity CLI(`agy`),带 `acp` 子命令,并且在终端里交互登录过一次 Google 账号。
|
||||
文本与工具调用已在 1.4.12 和 1.5.0 上验证;图片输入需要 1.5.0。
|
||||
- 支持 OpenCode 风格 provider 插件的 Magpie。额度查询已在 Magpie 0.1.1599 上验证。
|
||||
- agy 版本低于 1.4.12 时,会话会被拒绝(见「工具桥接」);低于 1.1.11 时,额度查询也会被
|
||||
拒绝,以免旧版本把 `/usage` 当成模型提示词。
|
||||
- **自动更新**:插件启动的 agy 进程默认带 `AGY_CLI_DISABLE_AUTO_UPDATE=true`,免得进程池里的
|
||||
多个进程同时更新同一个可执行文件。你自己在终端里运行的 agy 不受影响,照常更新。你自己设置了
|
||||
`AGY_CLI_DISABLE_AUTO_UPDATE`(包括设为 `false`)时,插件原样使用你的值。只通过本插件使用
|
||||
agy 的话,请定期在终端里运行一次 `agy` 让它更新:版本过旧本身也更显眼。
|
||||
|
||||
## 安装
|
||||
|
||||
从 Magpie 社区插件市场安装(推荐):在 Magpie 的 Plugins 页找到「Antigravity (local agy CLI)」点安装,或在终端运行:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/opencode-agy-cli-auth
|
||||
```
|
||||
|
||||
装好后 provider id 是 `agy-cli`,模型写成 `agy-cli/<模型>`。默认并发 16,可在 Magpie 的 Providers 页 Concurrency 里改(0 表示不限)。
|
||||
|
||||
安装完成后,先在终端运行一次 `agy` 完成 Google 登录。
|
||||
|
||||
## 使用
|
||||
|
||||
1. 在 Magpie 的 Providers 页找到 `agy-cli` 并点击 Sign in。插件会用 `agy models`
|
||||
确认 CLI 可用。Google 凭据始终由 agy 自己保管,插件不读取、不保存。
|
||||
2. 模型名写成 `agy-cli/<模型>`。agy 对同一模型不同思考等级给出的多个模型 ID,
|
||||
在这里会合并成一个模型的多个变体,请求时再映射回对应的 agy ID。
|
||||
3. 在客户端里选用这个模型即可。
|
||||
|
||||
## 并发
|
||||
|
||||
- 插件自己的进程池上限由 `AGY_BRIDGE_MAX_PROCS` 决定,默认 16 个 agy 进程。
|
||||
- Magpie 的 Providers 页有单独的 Concurrency 设置,可填 0–1000,0 表示不限制。
|
||||
你在页面里改的值会覆盖 `package.json` 里 `magpie.maxConcurrency` 的默认声明(16)。
|
||||
- 进程池已满、又找不到可以淘汰的进程时,插件返回 HTTP 503。建议两处数值保持一致:
|
||||
Providers 页的并发数超过进程池上限,多出来的请求就会得到 503。
|
||||
|
||||
## 平台
|
||||
|
||||
- **macOS、Linux**:支持。
|
||||
- **原生 Windows**:支持 `.exe`、`.cmd`、`.bat` 的查找与启动,后台更新检查不弹控制台窗口,
|
||||
并支持 `magpie quota`。目前只有命令构造的单元测试,尚未在 Windows 实机完成端到端验证。
|
||||
|
||||
## 额度
|
||||
|
||||
```sh
|
||||
magpie quota agy-cli --json
|
||||
magpie quota refresh agy-cli --json
|
||||
```
|
||||
|
||||
额度数据来自 agy 自己的 `/usage` 报告,显示的是当前 agy 登录账号的订阅窗口,按模型组
|
||||
分别列出。插件不读写 Google 令牌,查询的始终是 agy 当前登录的账号。没有可测量数据的窗口会显示
|
||||
"Limits not available",而不是 0% 或 100%。
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量 | 默认值 | 作用 |
|
||||
|---|---|---|
|
||||
| `AGY_PATH` | 按 PATH 查找 | 指定 agy 可执行文件 |
|
||||
| `AGY_BRIDGE_MAX_PROCS` | 16 | agy 进程池上限 |
|
||||
| `AGY_BRIDGE_THINKING` | 开启 | 设为 `0` 关闭思考摘要 |
|
||||
| `AGY_BRIDGE_EFFORT` | 未设置 | 强制思考等级:`minimal` / `low` / `medium` / `high` / `xhigh` / `max` |
|
||||
| `AGY_BRIDGE_MINIMAL_AGENT` | 关闭 | 设为 `1` 去掉 agy 自带的提示组件,见下文「精简 agent」 |
|
||||
| `AGY_BRIDGE_IDLE_MS` | 600000 | 进程空闲多久后回收(会话仍可续接) |
|
||||
| `AGY_BRIDGE_RESUME_TTL_MS` | 21600000 | 回收后的会话可续接的时长(6 小时) |
|
||||
| `AGY_BRIDGE_STATE_FILE` | `$XDG_STATE_HOME/magpie-agy-bridge/sessions.json` | 会话状态文件路径 |
|
||||
| `AGY_BRIDGE_IDE_CALL_DEADLINE_MS` | 150000 | 工具运行超过该时间仍未结束时,先返回 "still running" |
|
||||
| `AGY_BRIDGE_START_TIMEOUT_MS` / `_TURN_TIMEOUT_MS` / `_TOOL_TIMEOUT_MS` | 60 秒 / 5 分钟 / 30 分钟 | 进程启动、agy 无输出、等待客户端工具结果的超时 |
|
||||
| `AGY_BRIDGE_DETACHED_EVICT_MS` | 30000 | 客户端已断开的挂起工具回合,最多占用进程池槽位这么久 |
|
||||
| `AGY_BRIDGE_MAX_PROMPT_BYTES` | 114688(112 KiB) | 重放历史提示词的字节预算 |
|
||||
| `AGY_BRIDGE_USAGE_TIMEOUT_MS` | 15000 | 额度查询的总时间预算,最高 18000 |
|
||||
| `AGY_BRIDGE_MCP_TRACE` | 未设置 | 把 MCP 通道流量写入指定文件,仅用于排查 |
|
||||
| `AGY_CLI_DISABLE_AUTO_UPDATE` | 插件启动的 agy 设为 `true` | agy 自己的变量。你设置了就原样传给 agy,见「环境要求」 |
|
||||
|
||||
## 精简 agent(`AGY_BRIDGE_MINIMAL_AGENT=1`)
|
||||
|
||||
默认情况下,agy 用它自己的系统提示词跑每个请求,客户端的系统提示词附加在后面(agy 声明
|
||||
支持 `systemPrompt.append` 时放进会话,否则作为 `<external_system_instructions>` 放在
|
||||
第一条提示词开头)。
|
||||
|
||||
设为 `1` 后,临时 agent 带上 `excludeDefaultComponents: true`:发往上游的请求里不再有
|
||||
agy 自己的系统提示词,只剩插件的一行工具说明和客户端的系统提示词(同样以上面两种方式之一
|
||||
发送)。原作者实测每次模型调用的输入从约 8,400 token 降到约 500 token。代价是上游看到的
|
||||
不再是 agy 自己的请求形态,所以默认关闭,由你自行决定是否开启。
|
||||
|
||||
## 常见排查
|
||||
|
||||
- **找不到 agy**:设置 `AGY_PATH` 指向可执行文件,或确认 `agy` 在 PATH 里。
|
||||
- **Sign in 失败或 agy 报登录相关错误**:在终端运行一次 `agy`,重新完成 Google 登录。
|
||||
- **HTTP 503**:进程池满。提高 `AGY_BRIDGE_MAX_PROCS` 和 Providers 页的 Concurrency,
|
||||
或者减少同时进行的会话。
|
||||
- **额度显示 "Limits not available" 或报版本错误**:该窗口没有可测量的数据;版本错误则
|
||||
把 agy 升级到 1.1.11 以上。
|
||||
- **图片请求返回 HTTP 400**:当前 agy 没有声明图片能力(需要 1.5.0 以上)。另外只接受
|
||||
内联 base64,URL 图片和 PDF 等二进制文档都会被拒绝。
|
||||
- **回复里出现 "Agent execution terminated due to error."**:这是 agy 的错误标记。插件会
|
||||
从 agy 的日志中取出真实原因,并以错误结束本轮,不会当作正常回复输出。
|
||||
- **HTTP 409,提示工具结果与历史对不上**:通常是客户端在对话中途改写了历史或工具 ID。
|
||||
能确定对应关系时插件会重建会话;无法确定时直接拒绝,不做猜测。
|
||||
- **想关掉思考摘要**:设置 `AGY_BRIDGE_THINKING=0`,或者在请求里带上
|
||||
`thinking: { "type": "disabled" }`。
|
||||
|
||||
## 开发
|
||||
|
||||
```sh
|
||||
bun test packages/agy-cli # 在仓库根目录
|
||||
bun scripts/check.mjs agy-cli
|
||||
```
|
||||
|
||||
测试用假的 agy 进程(`test/` 下的 ACP stdio 服务)跑完整的 ACP 与 MCP 链路,不调用真实
|
||||
agy,不消耗额度。
|
||||
|
||||
## License
|
||||
|
||||
MIT。版权声明见 [LICENSE](LICENSE),上游来源与逐项变更见 [NOTICE.md](NOTICE.md)。
|
||||
@@ -0,0 +1,36 @@
|
||||
// Runs the suites in test/ (brought over from gitxm/yce-magpie-agy, MIT), each
|
||||
// in a bun process of its own: they mock node:child_process, move the clock and
|
||||
// set the bridge's environment, and smoke.mjs ends with process.exit.
|
||||
import { expect, test } from "bun:test"
|
||||
import path from "node:path"
|
||||
|
||||
const dir = path.join(import.meta.dir, "test")
|
||||
const hook = path.join(dir, "cp-hook.mjs")
|
||||
|
||||
function run(args, timeout) {
|
||||
const result = Bun.spawnSync({ cmd: [process.execPath, ...args], cwd: dir, env: { ...process.env }, stdout: "pipe", stderr: "pipe", timeout })
|
||||
const output = result.stdout.toString() + result.stderr.toString()
|
||||
if (result.exitCode !== 0) console.error(output)
|
||||
return { code: result.exitCode, output }
|
||||
}
|
||||
|
||||
for (const [name, mocks] of [
|
||||
["platform.mjs", true],
|
||||
["compat.mjs", true],
|
||||
["usage.mjs", true],
|
||||
["catalog.mjs", false],
|
||||
["usage-settlement.mjs", false],
|
||||
["repeat-batch.mjs", false],
|
||||
]) {
|
||||
test(`test/${name}`, () => {
|
||||
const { code, output } = run(["test", ...(mocks ? ["--preload", hook] : []), `./${name}`], 240_000)
|
||||
expect(output).toMatch(/\b[1-9]\d* pass\b/)
|
||||
expect(code).toBe(0)
|
||||
}, 250_000)
|
||||
}
|
||||
|
||||
test("test/smoke.mjs against a fake agy", () => {
|
||||
const { code, output } = run([path.join(dir, "smoke.mjs")], 240_000)
|
||||
expect(output).toMatch(/ALL OK \(\d+ checks\)/)
|
||||
expect(code).toBe(0)
|
||||
}, 250_000)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,400 @@
|
||||
import fs from "node:fs"
|
||||
import net from "node:net"
|
||||
|
||||
const PROTOCOL_VERSION = "2025-11-25"
|
||||
const SERVER_INFO = { name: "opencode-agy-cli-auth", version: "0.1.0" }
|
||||
// The bridge swaps tool catalogs in place and pushes list_changed over a watch channel.
|
||||
const CAPABILITIES = { tools: { listChanged: true } }
|
||||
const MAX_MESSAGE_BYTES = 16 * 1024 * 1024
|
||||
const CONTROL_PORT = Number(process.env.AGY_BRIDGE_CONTROL_PORT)
|
||||
const CONTROL_TOKEN = process.env.AGY_BRIDGE_TOKEN
|
||||
const CONTROL_CONFIGURED = Number.isInteger(CONTROL_PORT)
|
||||
&& CONTROL_PORT >= 1
|
||||
&& CONTROL_PORT <= 65535
|
||||
&& typeof CONTROL_TOKEN === "string"
|
||||
&& CONTROL_TOKEN.length > 0
|
||||
|
||||
const activeControls = new Set()
|
||||
const pendingCalls = new Map()
|
||||
let inputChunks = []
|
||||
let inputLength = 0
|
||||
let discardingInput = false
|
||||
let inputClosed = false
|
||||
|
||||
function isObject(value) {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function isValidId(value) {
|
||||
return value === null
|
||||
|| typeof value === "string"
|
||||
|| (typeof value === "number" && Number.isFinite(value))
|
||||
}
|
||||
|
||||
function internalError(message = "Internal error") {
|
||||
return { code: -32603, message }
|
||||
}
|
||||
|
||||
function closeAllControls() {
|
||||
for (const request of [...activeControls]) request.cancel()
|
||||
}
|
||||
|
||||
function closeInput() {
|
||||
if (inputClosed) return
|
||||
inputClosed = true
|
||||
inputChunks = []
|
||||
inputLength = 0
|
||||
closeAllControls()
|
||||
watchSocket?.destroy()
|
||||
}
|
||||
|
||||
function handleStdoutError(error) {
|
||||
closeInput()
|
||||
process.exit(error?.code === "EPIPE" ? 0 : 1)
|
||||
}
|
||||
|
||||
// Diagnostics only: AGY_BRIDGE_MCP_TRACE names a file that receives the MCP traffic.
|
||||
const TRACE_PATH = process.env.AGY_BRIDGE_MCP_TRACE
|
||||
function trace(direction, message) {
|
||||
if (!TRACE_PATH) return
|
||||
try {
|
||||
const summary = message?.method === "tools/list" || message?.result?.tools
|
||||
? { ...message, result: message.result?.tools ? { tools: message.result.tools.map(tool => tool.name) } : message.result }
|
||||
: message
|
||||
fs.appendFileSync(TRACE_PATH, JSON.stringify({ at: Date.now(), pid: process.pid, direction, message: summary }) + "\n", { mode: 0o600 })
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function send(message) {
|
||||
if (inputClosed) return
|
||||
trace("out", message)
|
||||
try {
|
||||
process.stdout.write(JSON.stringify(message) + "\n")
|
||||
} catch (error) {
|
||||
handleStdoutError(error)
|
||||
}
|
||||
}
|
||||
|
||||
function sendResult(id, result) {
|
||||
send({ jsonrpc: "2.0", id, result })
|
||||
}
|
||||
|
||||
function sendError(id, error) {
|
||||
send({ jsonrpc: "2.0", id, error })
|
||||
}
|
||||
|
||||
function configurationError() {
|
||||
return internalError("Bridge control channel is not configured")
|
||||
}
|
||||
|
||||
function controlRequest(payload) {
|
||||
const request = {
|
||||
socket: null,
|
||||
cancelled: false,
|
||||
settled: false,
|
||||
cancel: () => {},
|
||||
promise: null,
|
||||
}
|
||||
|
||||
request.promise = new Promise(resolve => {
|
||||
const failure = () => ({ error: internalError("Bridge control channel failure") })
|
||||
const finish = outcome => {
|
||||
if (request.settled) return
|
||||
request.settled = true
|
||||
activeControls.delete(request)
|
||||
request.socket?.destroy()
|
||||
resolve(outcome)
|
||||
}
|
||||
|
||||
request.cancel = () => {
|
||||
if (request.settled) return
|
||||
request.cancelled = true
|
||||
finish(failure())
|
||||
}
|
||||
|
||||
activeControls.add(request)
|
||||
|
||||
let socket
|
||||
try {
|
||||
socket = net.createConnection({ host: "127.0.0.1", port: CONTROL_PORT })
|
||||
} catch {
|
||||
finish(failure())
|
||||
return
|
||||
}
|
||||
|
||||
request.socket = socket
|
||||
socket.setEncoding("utf8")
|
||||
let buffer = ""
|
||||
|
||||
socket.on("connect", () => {
|
||||
try {
|
||||
socket.write(JSON.stringify(payload) + "\n")
|
||||
} catch {
|
||||
finish(failure())
|
||||
}
|
||||
})
|
||||
|
||||
socket.on("data", chunk => {
|
||||
if (request.settled) return
|
||||
buffer += chunk
|
||||
const newline = buffer.indexOf("\n")
|
||||
if (newline < 0) return
|
||||
let line = buffer.slice(0, newline)
|
||||
if (line.endsWith("\r")) line = line.slice(0, -1)
|
||||
|
||||
let response
|
||||
try {
|
||||
response = JSON.parse(line)
|
||||
} catch {
|
||||
finish(failure())
|
||||
return
|
||||
}
|
||||
|
||||
if (!isObject(response)) {
|
||||
finish(failure())
|
||||
return
|
||||
}
|
||||
|
||||
if (Object.hasOwn(response, "error")) {
|
||||
const error = response.error
|
||||
if (!isObject(error) || typeof error.code !== "number" || typeof error.message !== "string") {
|
||||
finish(failure())
|
||||
return
|
||||
}
|
||||
finish({ error })
|
||||
return
|
||||
}
|
||||
|
||||
if (!Object.hasOwn(response, "result")) {
|
||||
finish(failure())
|
||||
return
|
||||
}
|
||||
|
||||
finish({ result: response.result })
|
||||
})
|
||||
|
||||
socket.on("error", () => finish(failure()))
|
||||
socket.on("close", () => finish(failure()))
|
||||
})
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
let watchSocket = null
|
||||
|
||||
// One long-lived control connection; each line announces a changed tool catalog.
|
||||
function startWatch() {
|
||||
if (!CONTROL_CONFIGURED || watchSocket || inputClosed) return
|
||||
let socket
|
||||
try {
|
||||
socket = net.createConnection({ host: "127.0.0.1", port: CONTROL_PORT })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
watchSocket = socket
|
||||
socket.setEncoding("utf8")
|
||||
let buffer = ""
|
||||
socket.on("connect", () => {
|
||||
try { socket.write(JSON.stringify({ token: CONTROL_TOKEN, kind: "watch" }) + "\n") } catch {}
|
||||
})
|
||||
socket.on("data", chunk => {
|
||||
buffer += chunk
|
||||
if (buffer.length > MAX_MESSAGE_BYTES) {
|
||||
socket.destroy()
|
||||
return
|
||||
}
|
||||
let newline
|
||||
while ((newline = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, newline)
|
||||
buffer = buffer.slice(newline + 1)
|
||||
let event
|
||||
try { event = JSON.parse(line) } catch { continue }
|
||||
if (isObject(event) && event.event === "tools_changed") {
|
||||
send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })
|
||||
}
|
||||
}
|
||||
})
|
||||
socket.on("error", () => {})
|
||||
socket.on("close", () => {
|
||||
if (watchSocket === socket) watchSocket = null
|
||||
})
|
||||
}
|
||||
|
||||
function cancelCall(params) {
|
||||
if (!isObject(params) || !Object.hasOwn(params, "requestId")) return
|
||||
const request = pendingCalls.get(params.requestId)
|
||||
if (!request) return
|
||||
pendingCalls.delete(params.requestId)
|
||||
request.cancel()
|
||||
}
|
||||
|
||||
async function listTools(message, hasId) {
|
||||
if (!CONTROL_CONFIGURED) {
|
||||
if (hasId) sendError(message.id, configurationError())
|
||||
return
|
||||
}
|
||||
|
||||
const request = controlRequest({ token: CONTROL_TOKEN, kind: "list" })
|
||||
const outcome = await request.promise
|
||||
if (inputClosed || !hasId) return
|
||||
if (outcome.error) sendError(message.id, outcome.error)
|
||||
else sendResult(message.id, outcome.result)
|
||||
}
|
||||
|
||||
async function callTool(message, hasId) {
|
||||
const params = message.params
|
||||
if (!isObject(params)
|
||||
|| typeof params.name !== "string"
|
||||
|| params.name.length === 0
|
||||
|| (params.arguments !== undefined && !isObject(params.arguments))) {
|
||||
if (hasId) sendError(message.id, { code: -32602, message: "Invalid params" })
|
||||
return
|
||||
}
|
||||
|
||||
if (!CONTROL_CONFIGURED) {
|
||||
if (hasId) sendError(message.id, configurationError())
|
||||
return
|
||||
}
|
||||
|
||||
if (hasId && pendingCalls.has(message.id)) {
|
||||
sendError(message.id, { code: -32600, message: "Duplicate request id" })
|
||||
return
|
||||
}
|
||||
|
||||
const request = controlRequest({
|
||||
token: CONTROL_TOKEN,
|
||||
kind: "call",
|
||||
name: params.name,
|
||||
arguments: params.arguments === undefined ? {} : params.arguments,
|
||||
meta: params._meta || {},
|
||||
})
|
||||
if (hasId) pendingCalls.set(message.id, request)
|
||||
|
||||
try {
|
||||
const outcome = await request.promise
|
||||
if (inputClosed || request.cancelled || !hasId) return
|
||||
if (outcome.error) sendError(message.id, outcome.error)
|
||||
else sendResult(message.id, outcome.result)
|
||||
} finally {
|
||||
if (hasId && pendingCalls.get(message.id) === request) pendingCalls.delete(message.id)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMessage(message) {
|
||||
const hasId = Object.hasOwn(message, "id")
|
||||
|
||||
switch (message.method) {
|
||||
case "server/discover":
|
||||
// Answer as a pre-2026 server. Under 2026-07-28 agy expects notifications
|
||||
// through subscriptions/listen; the initialize flow delivers
|
||||
// notifications/tools/list_changed directly, which agy 1.4 honours.
|
||||
if (hasId) sendError(message.id, { code: -32601, message: "Method not found" })
|
||||
return
|
||||
case "initialize": {
|
||||
if (!hasId) return
|
||||
const requestedVersion = isObject(message.params) && typeof message.params.protocolVersion === "string"
|
||||
? message.params.protocolVersion
|
||||
: PROTOCOL_VERSION
|
||||
sendResult(message.id, {
|
||||
protocolVersion: requestedVersion,
|
||||
capabilities: CAPABILITIES,
|
||||
serverInfo: SERVER_INFO,
|
||||
})
|
||||
return
|
||||
}
|
||||
case "notifications/initialized":
|
||||
startWatch()
|
||||
return
|
||||
case "notifications/cancelled":
|
||||
cancelCall(message.params)
|
||||
return
|
||||
case "ping":
|
||||
if (hasId) sendResult(message.id, {})
|
||||
return
|
||||
case "tools/list":
|
||||
startWatch()
|
||||
await listTools(message, hasId)
|
||||
return
|
||||
case "tools/call":
|
||||
await callTool(message, hasId)
|
||||
return
|
||||
default:
|
||||
if (hasId) sendError(message.id, { code: -32601, message: "Method not found" })
|
||||
}
|
||||
}
|
||||
|
||||
function dispatch(message) {
|
||||
handleMessage(message).catch(() => {
|
||||
if (Object.hasOwn(message, "id")) sendError(message.id, internalError())
|
||||
})
|
||||
}
|
||||
|
||||
function handleLine(line) {
|
||||
if (line.length > 0 && line[line.length - 1] === 13) line = line.subarray(0, -1)
|
||||
if (line.length === 0) return
|
||||
|
||||
const text = line.toString("utf8")
|
||||
if (text.trim().length === 0) return
|
||||
|
||||
let message
|
||||
try {
|
||||
message = JSON.parse(text)
|
||||
} catch {
|
||||
sendError(null, { code: -32700, message: "Parse error" })
|
||||
return
|
||||
}
|
||||
|
||||
if (!isObject(message)
|
||||
|| message.jsonrpc !== "2.0"
|
||||
|| typeof message.method !== "string"
|
||||
|| (Object.hasOwn(message, "id") && !isValidId(message.id))) {
|
||||
sendError(null, { code: -32600, message: "Invalid Request" })
|
||||
return
|
||||
}
|
||||
|
||||
trace("in", message)
|
||||
dispatch(message)
|
||||
}
|
||||
|
||||
function handleInput(chunk) {
|
||||
let start = 0
|
||||
|
||||
while (start < chunk.length) {
|
||||
const newline = chunk.indexOf(10, start)
|
||||
const end = newline < 0 ? chunk.length : newline
|
||||
|
||||
if (!discardingInput && end > start) {
|
||||
const piece = chunk.subarray(start, end)
|
||||
if (inputLength + piece.length > MAX_MESSAGE_BYTES) {
|
||||
inputChunks = []
|
||||
inputLength = 0
|
||||
discardingInput = true
|
||||
sendError(null, { code: -32600, message: "Invalid Request: message exceeds 16 MiB" })
|
||||
} else {
|
||||
inputChunks.push(piece)
|
||||
inputLength += piece.length
|
||||
}
|
||||
}
|
||||
|
||||
if (newline < 0) return
|
||||
|
||||
if (!discardingInput) {
|
||||
const line = inputChunks.length === 1
|
||||
? inputChunks[0]
|
||||
: Buffer.concat(inputChunks, inputLength)
|
||||
inputChunks = []
|
||||
inputLength = 0
|
||||
handleLine(line)
|
||||
} else {
|
||||
discardingInput = false
|
||||
}
|
||||
|
||||
start = newline + 1
|
||||
}
|
||||
}
|
||||
|
||||
process.stdin.on("data", handleInput)
|
||||
process.stdin.on("end", closeInput)
|
||||
process.stdin.on("close", closeInput)
|
||||
process.stdin.on("error", closeInput)
|
||||
process.stdout.on("error", handleStdoutError)
|
||||
@@ -0,0 +1,4 @@
|
||||
// The OpenCode 1.x plugin, as OpenCode 1.x and magpie's host load it: the
|
||||
// default {id, server} from index.mjs and nothing else. OpenCode 2.x loads
|
||||
// opencode2.mjs, which runs it.
|
||||
export { default } from "./index.mjs"
|
||||
@@ -0,0 +1,597 @@
|
||||
// The OpenCode 2.x face of a package whose plugins are written for
|
||||
// OpenCode 1.x (and magpie's plugin host).
|
||||
//
|
||||
// OpenCode 2.x loads a package's `exports["."]` and wants its default to be
|
||||
// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions
|
||||
// (plugins#657). This file is that default. It runs each 1.x plugin the
|
||||
// package's opencode.mjs exports and hands 2.x what the plugin's hooks say:
|
||||
//
|
||||
// auth.methods → the integration's sign-in methods
|
||||
// config() → the provider, its package, base URL and models
|
||||
// provider.models → the signed-in account's own model list
|
||||
// auth.loader → each request's base URL, key, headers and fetch
|
||||
//
|
||||
// What 2.x has no place for is left out: chat.headers and chat.params
|
||||
// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin,
|
||||
// tools and events.
|
||||
//
|
||||
// scripts/opencode2.mjs is the one copy that is edited. Every package that
|
||||
// has it carries the same bytes as packages/<name>/opencode2.mjs, and
|
||||
// scripts/check.mjs fails when a copy differs.
|
||||
|
||||
import { readFileSync } from "node:fs"
|
||||
import * as v1 from "./opencode.mjs"
|
||||
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
|
||||
|
||||
// The key the SDK is made with: the account's own goes on each request in
|
||||
// its place (see wrapFetch), so a key read when the SDK was made can't go
|
||||
// out after the account changed.
|
||||
const PLACEHOLDER = "opencode2-v1-key"
|
||||
|
||||
// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from
|
||||
// swapping @ai-sdk/* for its native providers, which never call the sdk
|
||||
// hook below; openai-compatible's is the one 2.x ships, the others are AI
|
||||
// SDK v6's dist-tag, the line 2.x's bridge runs.
|
||||
export function packageOf(npm) {
|
||||
const name = npm || "@ai-sdk/openai-compatible"
|
||||
if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41"
|
||||
if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6`
|
||||
return `aisdk:${name}`
|
||||
}
|
||||
|
||||
// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read
|
||||
// them: a default {server} is the one plugin, else every function export
|
||||
// and every {server} object.
|
||||
export function pluginsOf(mod) {
|
||||
const d = mod?.default
|
||||
if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d))
|
||||
return typeof d.server === "function" ? [d.server] : []
|
||||
const out = []
|
||||
for (const value of Object.values(mod ?? {})) {
|
||||
const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null
|
||||
if (fn && !out.includes(fn)) out.push(fn)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const int = (n, fallback = 0) => {
|
||||
const v = Math.trunc(Number(n))
|
||||
return Number.isFinite(v) && v >= 0 ? v : fallback
|
||||
}
|
||||
const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0)
|
||||
const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {})
|
||||
const json = (v) => {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(v ?? null))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string"))
|
||||
const nonEmpty = (o) => (Object.keys(o).length ? o : undefined)
|
||||
|
||||
// connKey names a connection the way 2.x does.
|
||||
const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`)
|
||||
|
||||
// ---- sign-in ------------------------------------------------------------
|
||||
|
||||
// fields is a 1.x method's prompts as a 2.x form.
|
||||
export function fieldsOf(prompts) {
|
||||
const out = []
|
||||
for (const p of prompts ?? []) {
|
||||
if (!p?.key) continue
|
||||
const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) }
|
||||
if (p.placeholder) f.placeholder = String(p.placeholder)
|
||||
if (p.type === "select" && Array.isArray(p.options))
|
||||
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
|
||||
// a prompt shown only when another answer says so can't be required
|
||||
// a prompt shown only when another answer says so can't be required, and
|
||||
// neither can one whose own validate() accepts an empty answer (the
|
||||
// browser sign-in's optional API key)
|
||||
if (!p.condition && p.required !== false) f.required = true
|
||||
out.push(f)
|
||||
}
|
||||
return out.length ? out : undefined
|
||||
}
|
||||
|
||||
// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes
|
||||
// auth.json: the result without its type and provider.
|
||||
function v1Saved(r) {
|
||||
const { type: _t, provider: _p, ...rest } = r
|
||||
if ("key" in r) return { type: "api", ...rest }
|
||||
return { type: "oauth", ...rest }
|
||||
}
|
||||
|
||||
// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for
|
||||
// both kinds, the 1.x auth kept whole in its metadata. No refresh is
|
||||
// registered, so 2.x hands the credential over as it is and the plugin's
|
||||
// own loader renews it, as it does on 1.x.
|
||||
export function credentialOf(methodID, r) {
|
||||
if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed")
|
||||
const saved = json(v1Saved(r))
|
||||
if (saved.type === "api")
|
||||
return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } }
|
||||
return {
|
||||
type: "oauth",
|
||||
methodID,
|
||||
access: String(saved.access ?? ""),
|
||||
refresh: String(saved.refresh ?? ""),
|
||||
expires: int(saved.expires),
|
||||
metadata: { v1: saved },
|
||||
}
|
||||
}
|
||||
|
||||
// authOfValue is the 1.x auth a 2.x credential stands for.
|
||||
export function authOfValue(value) {
|
||||
if (!value) return null
|
||||
if (value.type === "oauth") {
|
||||
const v1 = record(value.metadata).v1
|
||||
if (v1 && typeof v1 === "object") return v1
|
||||
return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires }
|
||||
}
|
||||
if (value.type === "key") {
|
||||
const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {}
|
||||
return { type: "api", key: value.key, ...meta }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""])
|
||||
|
||||
// ---- models -------------------------------------------------------------
|
||||
|
||||
const MODALITIES = ["text", "audio", "image", "video", "pdf"]
|
||||
|
||||
// internalOf is a config model as 1.x hands it to provider.models: what
|
||||
// fromModelsDevModel makes of it, with the config's own variants.
|
||||
export function internalOf(providerID, conf, key, m) {
|
||||
const mods = record(m.modalities)
|
||||
const has = (list, k) => Array.isArray(list) && list.includes(k)
|
||||
const cost = record(m.cost)
|
||||
return {
|
||||
...m,
|
||||
id: key,
|
||||
providerID,
|
||||
name: m.name ?? key,
|
||||
api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" },
|
||||
status: m.status ?? "active",
|
||||
headers: m.headers ?? {},
|
||||
options: m.options ?? {},
|
||||
cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } },
|
||||
limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) },
|
||||
capabilities: {
|
||||
temperature: m.temperature ?? false,
|
||||
reasoning: m.reasoning ?? false,
|
||||
attachment: m.attachment ?? false,
|
||||
toolcall: m.tool_call ?? true,
|
||||
input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])),
|
||||
output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])),
|
||||
interleaved: m.interleaved ?? false,
|
||||
},
|
||||
release_date: m.release_date ?? "",
|
||||
variants: record(m.variants),
|
||||
}
|
||||
}
|
||||
|
||||
// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info.
|
||||
export function modelOf(providerID, provider, key, m) {
|
||||
const caps = record(m.capabilities)
|
||||
const listFrom = (obj, list) => {
|
||||
if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k])
|
||||
if (Array.isArray(list)) return list.map(String)
|
||||
return ["text"]
|
||||
}
|
||||
const input = listFrom(caps.input, m.modalities?.input)
|
||||
const output = listFrom(caps.output, m.modalities?.output)
|
||||
const c = record(m.cost)
|
||||
const cache = record(c.cache)
|
||||
const npm = m.api?.npm ?? m.provider?.npm
|
||||
const url = m.api?.url ?? m.provider?.api
|
||||
const settings = { ...record(json(m.options)) }
|
||||
if (url && url !== provider.baseURL) settings.baseURL = url
|
||||
const variants = Object.entries(record(m.variants))
|
||||
.filter(([, v]) => !record(v).disabled)
|
||||
.map(([id, v]) => {
|
||||
const { disabled: _d, ...rest } = record(json(v))
|
||||
return nonEmpty(rest) ? { id, settings: rest } : { id }
|
||||
})
|
||||
const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active"
|
||||
const out = {
|
||||
id: key,
|
||||
modelID: String(m.api?.id ?? m.id ?? key),
|
||||
providerID,
|
||||
name: String(m.name ?? key),
|
||||
capabilities: {
|
||||
tools: caps.toolcall ?? m.tool_call ?? true,
|
||||
input: input.length ? input : ["text"],
|
||||
output: output.length ? output : ["text"],
|
||||
...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}),
|
||||
},
|
||||
variants,
|
||||
time: { released: Date.parse(m.release_date ?? "") || 0 },
|
||||
cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }],
|
||||
status,
|
||||
enabled: true,
|
||||
limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 },
|
||||
}
|
||||
if (m.limit?.input) out.limit.input = int(m.limit.input)
|
||||
if (npm && npm !== provider.npm) out.package = packageOf(npm)
|
||||
if (nonEmpty(settings)) out.settings = settings
|
||||
const headers = strings(m.headers)
|
||||
if (nonEmpty(headers)) out.headers = headers
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- requests -----------------------------------------------------------
|
||||
|
||||
const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input))
|
||||
|
||||
// wrapFetch sends a request the SDK made from the provider's settings the
|
||||
// way 1.x would have sent it with the loader's options: the loader's base
|
||||
// URL in place of the configured one, the account's key in place of the
|
||||
// placeholder, the loader's headers added, through the loader's fetch.
|
||||
export function wrapFetch(next, base, options) {
|
||||
return async (input, init = {}) => {
|
||||
const o = await options()
|
||||
let url = urlOf(input)
|
||||
const from = String(base ?? "").replace(/\/+$/, "")
|
||||
const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : ""
|
||||
if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length)
|
||||
const req = input instanceof Request ? input : null
|
||||
const headers = new Headers(init.headers ?? req?.headers ?? undefined)
|
||||
for (const [k, v] of [...headers.entries()]) {
|
||||
if (!v.includes(PLACEHOLDER)) continue
|
||||
if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key))
|
||||
else headers.delete(k)
|
||||
}
|
||||
for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v)
|
||||
const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch
|
||||
if (req && init.body === undefined) {
|
||||
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text()
|
||||
return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal })
|
||||
}
|
||||
return send(url, { ...init, headers })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- one plugin ---------------------------------------------------------
|
||||
|
||||
async function setupPlugin(ctx, fn, live) {
|
||||
const directory = ctx?.location?.directory ?? process.cwd()
|
||||
// the active account each provider was last read for, and the renewed
|
||||
// auth a plugin saved for it (2.x has no way for a plugin to write a
|
||||
// credential back, so it is kept in the plugin's storage, under the
|
||||
// credential it renews and the token it was renewed from)
|
||||
const current = new Map()
|
||||
const saved = new Map()
|
||||
const signingIn = new Map()
|
||||
const storeKey = (id, key) => `v1auth/${id}/${key}`
|
||||
|
||||
const client = {
|
||||
auth: {
|
||||
async set(arg) {
|
||||
const id = arg?.path?.id
|
||||
const body = json(arg?.body)
|
||||
const cur = id && current.get(id)
|
||||
// a sign-in's own saves belong to the credential it is about to
|
||||
// make, not the one that was active when it started
|
||||
if (!cur || !body || signingIn.get(id) > 0) return { data: true }
|
||||
const entry = { fp: cur.fp, auth: body }
|
||||
saved.set(storeKey(id, cur.key), entry)
|
||||
await Promise.resolve()
|
||||
.then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry))
|
||||
.catch(() => {})
|
||||
return { data: true }
|
||||
},
|
||||
async get() {
|
||||
return { data: undefined }
|
||||
},
|
||||
},
|
||||
app: { log: async () => ({ data: true }) },
|
||||
}
|
||||
|
||||
const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {}
|
||||
const cfg = { provider: {} }
|
||||
try {
|
||||
await hooks.config?.(cfg)
|
||||
} catch {}
|
||||
const auth = hooks.auth
|
||||
const authID = auth?.provider ? String(auth.provider) : undefined
|
||||
const providers = record(cfg.provider)
|
||||
|
||||
// getAuth reads the active account: the credential 2.x holds, or what the
|
||||
// plugin last saved renewing it.
|
||||
const getAuth = async (id) => {
|
||||
const connection = await ctx.integration.connection.active(id).catch(() => undefined)
|
||||
if (!connection) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const value = await ctx.integration.connection.resolve(connection).catch(() => undefined)
|
||||
const base = authOfValue(value)
|
||||
if (!base) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const key = connKey(connection)
|
||||
const fp = fingerprint(base)
|
||||
// ours: a credential one of this plugin's own sign-ins made
|
||||
const ours = value?.type === "oauth" && !!record(value.metadata).v1
|
||||
current.set(id, { key, fp, ours })
|
||||
const sk = storeKey(id, key)
|
||||
let entry = saved.get(sk)
|
||||
if (!entry) {
|
||||
entry = await Promise.resolve()
|
||||
.then(() => ctx.storage?.get?.(sk))
|
||||
.catch(() => undefined)
|
||||
if (entry) saved.set(sk, entry)
|
||||
}
|
||||
return entry && entry.fp === fp && entry.auth ? entry.auth : base
|
||||
}
|
||||
|
||||
// the sign-in methods
|
||||
if (authID && Array.isArray(auth.methods) && auth.methods.length) {
|
||||
const label = (c) => {
|
||||
const a = authOfValue(c)
|
||||
const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account
|
||||
return typeof name === "string" && name ? name : undefined
|
||||
}
|
||||
const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1)
|
||||
const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1))
|
||||
const title = record(providers[authID]).name
|
||||
// 2.x runs a transform again on every reload, from nothing
|
||||
await ctx.integration.transform((editor) => {
|
||||
let keyed = false
|
||||
// the integration 2.x makes for an id it doesn't know is named by the
|
||||
// id; the provider's own name reads better in the sign-in list
|
||||
if (typeof title === "string" && title)
|
||||
try {
|
||||
editor.update?.(authID, (i) => {
|
||||
if (i && (!i.name || i.name === authID)) i.name = title
|
||||
})
|
||||
} catch {}
|
||||
auth.methods.forEach((m, i) => {
|
||||
if (!m) return
|
||||
const methodID = `v1-${i}`
|
||||
const form = fieldsOf(m.prompts)
|
||||
if (m.type === "api" && typeof m.authorize !== "function") {
|
||||
if (keyed) return
|
||||
keyed = true
|
||||
editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } })
|
||||
return
|
||||
}
|
||||
if (typeof m.authorize !== "function") return
|
||||
editor.method.update({
|
||||
integrationID: authID,
|
||||
method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) },
|
||||
async authorize(answer) {
|
||||
begin()
|
||||
let ended = false
|
||||
const done = () => {
|
||||
if (!ended) end()
|
||||
ended = true
|
||||
}
|
||||
try {
|
||||
const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)]))
|
||||
const r = await m.authorize(inputs)
|
||||
if (m.type === "api") {
|
||||
done()
|
||||
return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) }
|
||||
}
|
||||
if (r?.method === "code")
|
||||
return {
|
||||
url: String(r.url ?? ""),
|
||||
instructions: String(r.instructions ?? ""),
|
||||
mode: "code",
|
||||
callback: async (code) => {
|
||||
try {
|
||||
return credentialOf(methodID, await r.callback(code))
|
||||
} finally {
|
||||
done()
|
||||
}
|
||||
},
|
||||
}
|
||||
const callback = Promise.resolve()
|
||||
.then(() => r.callback())
|
||||
.then((res) => credentialOf(methodID, res))
|
||||
.finally(done)
|
||||
callback.catch(() => {})
|
||||
return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback }
|
||||
} catch (e) {
|
||||
done()
|
||||
throw e
|
||||
}
|
||||
},
|
||||
label,
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// the loader's options for the account signed in now, read again when
|
||||
// the account changes
|
||||
let loaded = null
|
||||
const loaderOptions = async (id) => {
|
||||
if (id !== authID || typeof auth?.loader !== "function") {
|
||||
const a = authID === id ? await getAuth(id) : undefined
|
||||
return { key: a?.type === "api" ? a.key : undefined }
|
||||
}
|
||||
const a = await getAuth(id)
|
||||
if (!a) return {}
|
||||
const fp = current.get(id)?.key + "\0" + fingerprint(a)
|
||||
if (loaded?.fp !== fp) {
|
||||
const p = Promise.resolve()
|
||||
.then(() => auth.loader(() => getAuth(id), providerOf(id)))
|
||||
.then((o) => record(o))
|
||||
loaded = { fp, p }
|
||||
p.catch(() => {
|
||||
if (loaded?.fp === fp) loaded = null
|
||||
})
|
||||
}
|
||||
const o = await loaded.p
|
||||
const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined
|
||||
return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch }
|
||||
}
|
||||
|
||||
// the providers, with the list the account's own read last gave each
|
||||
const source = new Map()
|
||||
// providerOf is a provider as 1.x hands it to provider.models and
|
||||
// auth.loader
|
||||
const providerOf = (id) => {
|
||||
const conf = record(providers[id])
|
||||
const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))]))
|
||||
return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models }
|
||||
}
|
||||
const listed = new Set()
|
||||
for (const [id, conf0] of Object.entries(providers)) {
|
||||
const conf = record(conf0)
|
||||
// a provider entry that only names the sign-in (no package, no models)
|
||||
// is not a provider of models
|
||||
if (!conf.npm && !Object.keys(record(conf.models)).length) continue
|
||||
const options = record(conf.options)
|
||||
const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options
|
||||
// with no base URL the config leaves it to the loader: a name that
|
||||
// can't resolve stands in for it, and each request swaps in the
|
||||
// loader's (wrapFetch)
|
||||
const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid`
|
||||
const npm = conf.npm ?? "@ai-sdk/openai-compatible"
|
||||
const info = {
|
||||
id,
|
||||
...(id === authID ? { integrationID: id } : {}),
|
||||
name: String(conf.name ?? id),
|
||||
activation: "auto",
|
||||
package: packageOf(npm),
|
||||
settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) },
|
||||
}
|
||||
const headers = { ...strings(conf.headers), ...strings(optHeaders) }
|
||||
if (nonEmpty(headers)) info.headers = headers
|
||||
const prov = { baseURL, npm }
|
||||
const fromConfig = () =>
|
||||
Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m))))
|
||||
listed.add(id)
|
||||
await ctx.provider.transform((editor) => {
|
||||
const s = source.get(id)
|
||||
editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection })
|
||||
})
|
||||
source.set(id, { conf, prov, models: null, connection: undefined })
|
||||
}
|
||||
|
||||
// each request: the placeholder key, and the fetch that swaps in the
|
||||
// account's. A provider the package doesn't list (one 2.x has built in
|
||||
// that the plugin only signs in to) is left to 2.x unless the plugin's
|
||||
// loader serves it and one of the plugin's own sign-ins is active.
|
||||
const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : []
|
||||
for (const id of new Set([...listed, ...own])) {
|
||||
const base = source.get(id)?.prov.baseURL
|
||||
await ctx.aisdk.hook(
|
||||
"sdk",
|
||||
async (evt) => {
|
||||
const opts = evt.options
|
||||
if (!opts || opts.__opencode2) return
|
||||
if (!listed.has(id)) {
|
||||
await getAuth(id)
|
||||
if (!current.get(id)?.ours) return
|
||||
}
|
||||
opts.__opencode2 = true
|
||||
opts.apiKey = PLACEHOLDER
|
||||
opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id))
|
||||
},
|
||||
{ providerID: id },
|
||||
)
|
||||
}
|
||||
|
||||
// refresh reads the account's own list after a sign-in or a switch
|
||||
const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined
|
||||
let refreshing = null
|
||||
let again = false
|
||||
// the account the list was last read for: a credential.updated that
|
||||
// leaves it as it was reads nothing again
|
||||
let readFor = null
|
||||
const stateOf = async () => {
|
||||
const c = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = c ? await getAuth(authID) : undefined
|
||||
return connKey(c) + "\0" + (a ? fingerprint(a) : "")
|
||||
}
|
||||
const refresh = () => {
|
||||
if (refreshing) {
|
||||
again = true
|
||||
return refreshing
|
||||
}
|
||||
refreshing = (async () => {
|
||||
try {
|
||||
if (!authID || !source.has(authID)) return
|
||||
const s = source.get(authID)
|
||||
const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = connection ? await getAuth(authID) : undefined
|
||||
readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
|
||||
if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
|
||||
if (s.connection || s.models) {
|
||||
s.connection = undefined
|
||||
s.models = null
|
||||
await ctx.provider.reload()
|
||||
}
|
||||
return
|
||||
}
|
||||
const provider = providerOf(authID)
|
||||
let got
|
||||
try {
|
||||
got = await hooks.provider.models(provider, { auth: a })
|
||||
} catch {
|
||||
got = null
|
||||
}
|
||||
if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) {
|
||||
again = true
|
||||
return
|
||||
}
|
||||
s.connection = connection
|
||||
s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
|
||||
await ctx.provider.reload()
|
||||
await ctx.model?.reload?.()
|
||||
} finally {
|
||||
refreshing = null
|
||||
if (again && live.on) {
|
||||
again = false
|
||||
void refresh()
|
||||
}
|
||||
}
|
||||
})()
|
||||
return refreshing
|
||||
}
|
||||
|
||||
if (authID && ctx.event?.subscribe)
|
||||
void (async () => {
|
||||
try {
|
||||
// a switch names the integration; an update (a sign-in, a removal)
|
||||
// names nothing, so it reads again only when this account changed
|
||||
const types = ["credential.switched", "credential.updated"]
|
||||
for await (const event of ctx.event.subscribe({ types })) {
|
||||
if (!live.on) return
|
||||
if (event?.type === "credential.switched" && event?.data?.integrationID === authID) {
|
||||
loaded = null
|
||||
await refresh()
|
||||
} else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) {
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
})()
|
||||
void refresh()
|
||||
}
|
||||
|
||||
export async function setup(ctx, mod = v1) {
|
||||
const live = { on: true }
|
||||
for (const fn of pluginsOf(mod)) {
|
||||
try {
|
||||
await setupPlugin(ctx, fn, live)
|
||||
} catch (e) {
|
||||
// one plugin failing to start leaves the package's others working
|
||||
console.error(`${pkg.name}: ${e?.message ?? e}`)
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
live.on = false
|
||||
}
|
||||
}
|
||||
|
||||
export default { id: pkg.name, setup: (ctx) => setup(ctx) }
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
||||
"version": "0.1.0",
|
||||
"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",
|
||||
"exports": {
|
||||
".": "./opencode2.mjs"
|
||||
},
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"opencode.mjs",
|
||||
"opencode2.mjs",
|
||||
"platform.mjs",
|
||||
"mcp-server.mjs",
|
||||
"usage.mjs",
|
||||
"README.md",
|
||||
"README.en.md",
|
||||
"LICENSE",
|
||||
"NOTICE.md"
|
||||
],
|
||||
"keywords": [
|
||||
"magpie",
|
||||
"magpie-plugin",
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"antigravity",
|
||||
"agy",
|
||||
"acp"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/agy-cli"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test"
|
||||
},
|
||||
"magpie": {
|
||||
"maxConcurrency": 16
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import path from "node:path"
|
||||
|
||||
export function agyCandidates(env, home, platform = process.platform) {
|
||||
const windows = platform === "win32"
|
||||
const paths = windows ? path.win32 : path.posix
|
||||
const names = windows ? ["agy.exe", "agy.cmd", "agy.bat"] : ["agy"]
|
||||
const searchPath = env.PATH || (windows ? env.Path : "") || ""
|
||||
const candidates = env.AGY_PATH ? [env.AGY_PATH] : []
|
||||
for (const directory of searchPath.split(windows ? ";" : ":")) {
|
||||
if (directory) candidates.push(...names.map(name => paths.join(directory.replace(/^"|"$/g, ""), name)))
|
||||
}
|
||||
const directories = windows ? [
|
||||
paths.join(env.LOCALAPPDATA || paths.join(home, "AppData", "Local"), "agy", "bin"),
|
||||
paths.join(env.LOCALAPPDATA || paths.join(home, "AppData", "Local"), "Programs", "Antigravity", "bin"),
|
||||
paths.join(home, ".local", "bin"),
|
||||
paths.join(home, ".gemini", "bin"),
|
||||
] : [paths.join(home, ".local", "bin"), paths.join(home, ".gemini", "bin"), "/usr/local/bin", "/opt/homebrew/bin"]
|
||||
for (const directory of directories) candidates.push(...names.map(name => paths.join(directory, name)))
|
||||
return candidates
|
||||
}
|
||||
|
||||
// The cmd.exe escaping algorithm is adapted from node-cross-spawn:
|
||||
// https://github.com/moxystudio/node-cross-spawn/blob/master/lib/util/escape.js
|
||||
// Copyright (c) 2018 Made With MOXY Lda
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
const cmdMeta = /([()\][%!^"`<>&|;, *?])/g
|
||||
|
||||
function cmdArgument(value, doubleEscape) {
|
||||
let argument = String(value)
|
||||
if (/[\0\r\n]/.test(argument)) throw new Error("a Windows command argument contains a line break or NUL")
|
||||
argument = argument.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
|
||||
argument = argument.replace(/(?=(\\+?)?)\1$/, "$1$1")
|
||||
argument = `"${argument}"`.replace(cmdMeta, "^$1")
|
||||
// npm's cmd-shim adds a second cmd expansion pass when forwarding %*.
|
||||
return doubleEscape ? argument.replace(cmdMeta, "^$1") : argument
|
||||
}
|
||||
|
||||
export function agySpawnSpec(file, args, platform = process.platform, env = process.env) {
|
||||
if (platform !== "win32" || !/\.(?:cmd|bat)$/i.test(file)) return { file, args, options: {} }
|
||||
if (/[\0\r\n]/.test(file)) throw new Error("a Windows command path contains a line break or NUL")
|
||||
const doubleEscape = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file)
|
||||
const command = [path.win32.normalize(file).replace(cmdMeta, "^$1"), ...args.map(arg => cmdArgument(arg, doubleEscape))].join(" ")
|
||||
return {
|
||||
file: env.ComSpec || env.COMSPEC || env.comspec || "cmd.exe",
|
||||
args: ["/d", "/v:off", "/s", "/c", `"${command}"`],
|
||||
options: { windowsVerbatimArguments: true, windowsHide: true },
|
||||
}
|
||||
}
|
||||
|
||||
// The environment an agy child runs with. A value the user set for
|
||||
// AGY_CLI_DISABLE_AUTO_UPDATE (in the parent's environment or the caller's)
|
||||
// is kept as written. Only when nobody set it do the plugin's children run
|
||||
// with auto-update off, so a pool of ACP processes doesn't update the binary
|
||||
// under each other; the user's own `agy` runs keep updating.
|
||||
export function childEnv(parent = process.env, extra = {}, platform = process.platform) {
|
||||
const env = {}
|
||||
const names = new Map()
|
||||
for (const source of [parent, extra]) {
|
||||
for (const [key, value] of Object.entries(source || {})) {
|
||||
if (value === undefined) continue
|
||||
// Windows treats env names case-insensitively; keep the caller's PATH.
|
||||
const name = platform === "win32" ? key.toUpperCase() : key
|
||||
if (names.has(name)) delete env[names.get(name)]
|
||||
names.set(name, key)
|
||||
env[key] = value
|
||||
}
|
||||
}
|
||||
if (![...names.keys()].some(name => name.toUpperCase() === "AGY_CLI_DISABLE_AUTO_UPDATE")) {
|
||||
env.AGY_CLI_DISABLE_AUTO_UPDATE = "true"
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
export function spawnAgy(file, args, options = {}) {
|
||||
const command = agySpawnSpec(file, args)
|
||||
const env = childEnv(process.env, options?.env)
|
||||
return spawn(command.file, command.args, { ...options, ...command.options, windowsHide: true, env })
|
||||
}
|
||||
|
||||
export function windowsMcpShim(executable, server) {
|
||||
const quote = value => {
|
||||
if (/["\0\r\n]/.test(value)) throw new Error("invalid Windows MCP shim path")
|
||||
return `"${value.replace(/%/g, "%%")}"`
|
||||
}
|
||||
return `@echo off\r\nsetlocal DisableDelayedExpansion\r\n${quote(executable)} ${quote(server)}\r\n`
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
// magpie-agy 模型目录回归(源自 configs 仓 test_agy_bridge_catalog.mjs):目录刷新不得拖过 Magpie 的 2 秒 provider.models 超时,
|
||||
// 失败不得冲掉已有动态目录,limit 元数据按家族给出,型号别名与 [1m] 剥除保持可用。
|
||||
//
|
||||
// 运行:bun test ./catalog.mjs(或在包目录 bun test)
|
||||
// 全部经真实仓内 index.mjs 的 plugin.provider.models() / fetch 入口,边界替身见 testkit.mjs。
|
||||
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import {
|
||||
BASE_MODEL_ROWS, CATALOG_TTL_MS, baseBody, createBridgeKit, modelsOutput, readSse, sleep, tick,
|
||||
} from "./testkit.mjs"
|
||||
|
||||
const FAST_BUDGET_MS = 750 // 计划给的调度容差;补丁内部等待预算是 500ms,远低于 Magpie 的 2s。
|
||||
// 会话报出 agy 向本客户端开放的型号之前,只列 Gemini。
|
||||
const FALLBACK_IDS = ["gemini-4-argon", "gemini-3.8-flash"]
|
||||
const OFFERED_ALL = [
|
||||
["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["gemini-4-argon-low", "Gemini 4 Argon (Low)"],
|
||||
["claude-sonnet-5-5-high", "Claude Sonnet 5.5 (High)"], ["claude-sonnet-5-5-low", "Claude Sonnet 5.5 (Low)"],
|
||||
["gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"],
|
||||
]
|
||||
const NOT_YET_OFFERED = ["claude-opus-5-5", "claude-sonnet-5-5", "gpt-oss-120b", "gpt-oss-120b-medium", "mystery-model"]
|
||||
const DYNAMIC_ROWS = [...BASE_MODEL_ROWS, ["gemini-9-test-high", "Gemini 9 Test (High)"], ["gemini-9-test-low", "Gemini 9 Test (Low)"], ["mystery-model", "Mystery Model"]]
|
||||
const DYNAMIC_OK = { stdout: modelsOutput(DYNAMIC_ROWS) }
|
||||
|
||||
async function withKit(options, fn) {
|
||||
const kit = await createBridgeKit(options)
|
||||
try {
|
||||
return await fn(kit)
|
||||
} finally {
|
||||
await kit.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
async function timed(fn) {
|
||||
const started = performance.now()
|
||||
const value = await fn()
|
||||
return { value, ms: performance.now() - started }
|
||||
}
|
||||
|
||||
function ids(models) {
|
||||
return Object.keys(models).sort()
|
||||
}
|
||||
|
||||
function assertFallbackPresent(models) {
|
||||
for (const id of FALLBACK_IDS) assert.ok(models[id], `目录缺少 ${id}`)
|
||||
for (const id of NOT_YET_OFFERED) assert.equal(models[id], undefined, `没有会话开放就列出了 ${id}`)
|
||||
}
|
||||
|
||||
// 后台刷新结束(假子进程已关)且模块自己的定时器都已清掉。
|
||||
async function settle(kit) {
|
||||
for (let i = 0; i < 20 && kit.children.size; i++) await sleep(10)
|
||||
await tick()
|
||||
await tick()
|
||||
}
|
||||
|
||||
test("没有 agy 时直接给静态目录,不起子进程", async () => {
|
||||
await withKit({ agyPath: null }, async (kit) => {
|
||||
const { value, ms } = await timed(() => kit.models())
|
||||
assertFallbackPresent(value)
|
||||
assert.equal(kit.modelsSpawns.length, 0)
|
||||
assert.ok(ms < FAST_BUDGET_MS, `耗时 ${ms}ms`)
|
||||
})
|
||||
})
|
||||
|
||||
test("首次 agy models 卡死时 750ms 内返回非空静态目录", async () => {
|
||||
await withKit({ modelsBehavior: { hang: true } }, async (kit) => {
|
||||
const { value, ms } = await timed(() => kit.models())
|
||||
assert.ok(ms < FAST_BUDGET_MS, `首次目录耗时 ${Math.round(ms)}ms,超过 ${FAST_BUDGET_MS}ms`)
|
||||
assertFallbackPresent(value)
|
||||
assert.equal(kit.modelsSpawns.length, 1)
|
||||
assert.equal(kit.timers.refed().length, 0, "agy models 卡死期间不应有挂住 Node 退出的模块定时器")
|
||||
await kit.finishChildren()
|
||||
assert.equal(kit.timers.refed().length, 0, "子进程结束后不应残留挂住退出的定时器")
|
||||
})
|
||||
})
|
||||
|
||||
test("首次快速成功时直接拿到动态目录", async () => {
|
||||
await withKit({ modelsBehavior: DYNAMIC_OK }, async (kit) => {
|
||||
const models = await kit.models()
|
||||
assert.ok(models["gemini-9-test"], "动态独有家族未出现在目录")
|
||||
assert.deepEqual(models["gemini-9-test"].variants && Object.keys(models["gemini-9-test"].variants).sort(), ["high", "low"])
|
||||
assert.equal(models["mystery-model"], undefined, "没有会话开放的非 Gemini 型号不应列出")
|
||||
})
|
||||
})
|
||||
|
||||
test("会话开放的型号才列出:Claude、GPT-OSS 和 agy models 没列的型号随会话出现", async () => {
|
||||
await withKit({ modelsBehavior: DYNAMIC_OK, 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) => {
|
||||
const before = await kit.models()
|
||||
assert.equal(before["claude-opus-5-5"], undefined)
|
||||
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 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 })
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(after["gpt-oss-120b"]?.limit ?? null)), { context: 131072, output: 32768 })
|
||||
assert.ok(after["offered-only"], "会话开放而 agy models 没列的型号应列出")
|
||||
assert.equal(after["claude-sonnet-5-5"], undefined, "agy models 列出但会话没开放的型号不应列出")
|
||||
assert.equal(after["gemini-3.8-flash"], undefined, "会话没开放的 Gemini 也不应列出")
|
||||
assert.equal(after["mystery-model"], undefined)
|
||||
assert.ok(after["gemini-4-argon"])
|
||||
})
|
||||
})
|
||||
|
||||
test("握手报出的 agy 版本低于 1.4.12 时拒绝会话并说明原因", async () => {
|
||||
await withKit({ agentVersion: "1.4.11" }, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const response = await kit.request(baseBody({ model: "agy-cli/gemini-4-argon", tools: [], messages: [{ role: "user", content: "hi" }] }))
|
||||
const text = response.status === 200 ? JSON.stringify((await readSse(response)).error) : await response.text()
|
||||
assert.match(text, /agy 1\.4\.11 is older than 1\.4\.12/)
|
||||
assert.equal(kit.acpLog.filter(entry => entry.method === "session/new").length, 0, "旧版本不应开会话")
|
||||
})
|
||||
})
|
||||
|
||||
test("新鲜缓存不再等待也不再 spawn", async () => {
|
||||
await withKit({ modelsBehavior: DYNAMIC_OK }, async (kit) => {
|
||||
await kit.models()
|
||||
await settle(kit)
|
||||
kit.modelsBehavior = { hang: true }
|
||||
const { value, ms } = await timed(() => kit.models())
|
||||
assert.ok(ms < 100, `热缓存耗时 ${Math.round(ms)}ms`)
|
||||
assert.ok(value["gemini-9-test"])
|
||||
assert.equal(kit.modelsSpawns.length, 1)
|
||||
})
|
||||
})
|
||||
|
||||
test("TTL 边界:差 1ms 不刷新,到点后台刷新且过期期间仍 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)
|
||||
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"], "过期刷新卡住时丢了上次的动态目录")
|
||||
})
|
||||
})
|
||||
|
||||
test("50 个并发 models() 只 spawn 一次且结果一致", async () => {
|
||||
await withKit({ modelsBehavior: { ...DYNAMIC_OK, delayMs: 120 } }, async (kit) => {
|
||||
const { value: results, ms } = await timed(() => Promise.all(Array.from({ length: 50 }, () => kit.models())))
|
||||
assert.equal(kit.modelsSpawns.length, 1)
|
||||
assert.ok(ms < FAST_BUDGET_MS, `并发耗时 ${Math.round(ms)}ms`)
|
||||
const first = JSON.stringify(results[0])
|
||||
for (const item of results) assert.equal(JSON.stringify(item), first)
|
||||
assert.ok(results[0]["gemini-9-test"])
|
||||
})
|
||||
})
|
||||
|
||||
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: "" }],
|
||||
["不可解析输出", { code: 0, stdout: "garbage\n\n \n" }],
|
||||
]
|
||||
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())
|
||||
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()
|
||||
assert.ok(recovered["gemini-10-new"], "恢复成功后没有换成新目录")
|
||||
assert.equal(recovered["gemini-9-test"], undefined, "成功刷新应整体替换为新目录")
|
||||
})
|
||||
})
|
||||
|
||||
test("失败后的立即重试被限流,不形成请求风暴;隔一段时间后仍会再试", async () => {
|
||||
await withKit({ modelsBehavior: { code: 1, stdout: "" } }, async (kit) => {
|
||||
await kit.models()
|
||||
await settle(kit)
|
||||
for (let i = 0; i < 20; i++) await kit.models()
|
||||
await settle(kit)
|
||||
assert.ok(kit.modelsSpawns.length <= 2, `20 次立即重试起了 ${kit.modelsSpawns.length} 个 agy models`)
|
||||
const before = kit.modelsSpawns.length
|
||||
kit.clock.advance(CATALOG_TTL_MS)
|
||||
kit.modelsBehavior = DYNAMIC_OK
|
||||
const models = await kit.models()
|
||||
assert.equal(kit.modelsSpawns.length, before + 1, "间隔足够后没有再次尝试")
|
||||
assert.ok(models["gemini-9-test"])
|
||||
})
|
||||
})
|
||||
|
||||
test("agyPath 变化后不复用旧可执行文件的动态目录", async () => {
|
||||
await withKit({ modelsBehavior: { stdout: modelsOutput([...BASE_MODEL_ROWS, ["gemini-only-on-a", "Gemini Only On A"]]) } }, async (kit) => {
|
||||
assert.ok((await kit.models())["gemini-only-on-a"])
|
||||
await settle(kit)
|
||||
kit.env.AGY_PATH = kit.makeFakeAgy("agy-b")
|
||||
kit.modelsBehavior = { hang: true }
|
||||
const { value, ms } = await timed(() => kit.models())
|
||||
assert.ok(ms < FAST_BUDGET_MS)
|
||||
assert.equal(value["gemini-only-on-a"], undefined, "换了 agy 仍在用旧 agy 的动态型号")
|
||||
assertFallbackPresent(value)
|
||||
assert.equal(kit.modelsSpawns.at(-1).file, kit.env.AGY_PATH)
|
||||
})
|
||||
})
|
||||
|
||||
test("各家族 limit 正确,未知动态型号不猜成 1M", async () => {
|
||||
const expected = {
|
||||
"gemini-4-argon": { context: 1048576, output: 65536 },
|
||||
"gemini-3.8-flash": { context: 1048576, output: 65536 },
|
||||
}
|
||||
for (const [label, options] of [["静态目录", { agyPath: null }], ["动态目录", { modelsBehavior: DYNAMIC_OK }]]) {
|
||||
await withKit(options, async (kit) => {
|
||||
const models = await kit.models()
|
||||
for (const [id, limit] of Object.entries(expected)) {
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(models[id]?.limit ?? null)), limit, `${label} ${id} 的 limit 不对`)
|
||||
}
|
||||
if (models["mystery-model"]) {
|
||||
const context = models["mystery-model"].limit?.context
|
||||
assert.ok(!(context >= 1_000_000), `未知型号被猜成 ${context}`)
|
||||
}
|
||||
if (models["gemini-9-test"]) {
|
||||
const context = models["gemini-9-test"].limit?.context
|
||||
assert.ok(!(context >= 1_000_000), `未证实家族被猜成 ${context}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("gpt-oss-120b 裸名映射到 medium,请求型号尾部 [1m] 被剥除", async () => {
|
||||
const cases = [
|
||||
["agy-cli/gpt-oss-120b", "gpt-oss-120b-medium", "gpt-oss-120b"],
|
||||
["agy-cli/gpt-oss-120b[1m]", "gpt-oss-120b-medium", "gpt-oss-120b"],
|
||||
["agy-cli/gpt-oss-120b-medium", "gpt-oss-120b-medium", "gpt-oss-120b-medium"],
|
||||
["agy-cli/gemini-4-argon[1m]", "gemini-4-argon-high", "gemini-4-argon"],
|
||||
["agy-cli/claude-sonnet-5-5[1M]", "claude-sonnet-5-5-high", "claude-sonnet-5-5"],
|
||||
]
|
||||
for (const [requested, agyModel, echoed] of cases) {
|
||||
await withKit({ agyPath: undefined, 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: requested, tools: [], messages: [{ role: "user", content: `hi ${requested}` }] })))
|
||||
assert.equal(parsed.error, null, JSON.stringify(parsed.error))
|
||||
assert.deepEqual([...kit.setModels], [agyModel], `${requested} 实际选到 ${kit.setModels}`)
|
||||
assert.equal(parsed.model, echoed)
|
||||
assert.ok(!kit.setModels.some((item) => /\[1m\]/i.test(item)))
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("后台刷新抛异常不产生 unhandledRejection,模块定时器随结果一起清掉", async () => {
|
||||
const rejections = []
|
||||
const onRejection = (reason) => rejections.push(reason)
|
||||
process.on("unhandledRejection", onRejection)
|
||||
try {
|
||||
for (const behavior of [{ brokenChild: true }, { throwSync: true }, { error: true }, { code: 2 }]) {
|
||||
await withKit({ modelsBehavior: behavior }, async (kit) => {
|
||||
const models = await kit.models()
|
||||
assertFallbackPresent(models)
|
||||
await settle(kit)
|
||||
await sleep(20)
|
||||
assert.equal(kit.timers.refed().length, 0, `${JSON.stringify(behavior)} 残留定时器`)
|
||||
})
|
||||
}
|
||||
await sleep(50)
|
||||
assert.deepEqual(rejections.map(String), [])
|
||||
} finally {
|
||||
process.off("unhandledRejection", onRejection)
|
||||
}
|
||||
})
|
||||
|
||||
test("慢刷新与失败刷新都不会挂住 Node 退出(独立子进程实测)", () => {
|
||||
// 探针不调用 dispose:只靠事件循环自然排空退出;临时目录在 exit 钩子里同步清掉。
|
||||
const probe = `
|
||||
import fs from "node:fs"
|
||||
const tk = await import(${JSON.stringify(new URL("./testkit.mjs", import.meta.url).href)})
|
||||
process.on("unhandledRejection", (reason) => { console.error("UNHANDLED", reason); process.exitCode = 3 })
|
||||
const slow = await tk.createBridgeKit({ modelsBehavior: { stdout: tk.modelsOutput(tk.BASE_MODEL_ROWS), delayMs: 900 } })
|
||||
const failing = await tk.createBridgeKit({ modelsBehavior: { error: true } })
|
||||
process.on("exit", () => { for (const kit of [slow, failing]) fs.rmSync(kit.tmp, { recursive: true, force: true }) })
|
||||
const started = performance.now()
|
||||
const a = await slow.models()
|
||||
const b = await failing.models()
|
||||
const elapsed = performance.now() - started
|
||||
console.log(JSON.stringify({ elapsed, a: Object.keys(a).length, b: Object.keys(b).length }))
|
||||
`
|
||||
const started = Date.now()
|
||||
const result = spawnSync(process.execPath, ["--experimental-vm-modules", "--no-warnings", "--input-type=module", "-e", probe], {
|
||||
encoding: "utf8",
|
||||
timeout: 20_000,
|
||||
})
|
||||
const wall = Date.now() - started
|
||||
assert.equal(result.error, undefined, String(result.error))
|
||||
assert.equal(result.status, 0, `探针退出码 ${result.status}\nstdout:${result.stdout}\nstderr:${result.stderr}`)
|
||||
const report = JSON.parse(result.stdout.trim().split("\n").at(-1))
|
||||
assert.ok(report.elapsed < 2 * FAST_BUDGET_MS, `两次 models() 共耗时 ${Math.round(report.elapsed)}ms`)
|
||||
assert.ok(report.a > 0 && report.b > 0)
|
||||
assert.ok(wall < 8_000, `子进程 ${wall}ms 才退出,疑似被定时器挂住`)
|
||||
})
|
||||
@@ -0,0 +1,202 @@
|
||||
import assert from "node:assert/strict"
|
||||
import childProcess from "node:child_process"
|
||||
import { EventEmitter } from "node:events"
|
||||
import { syncBuiltinESMExports } from "node:module"
|
||||
import { PassThrough } from "node:stream"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { after, test } from "node:test"
|
||||
|
||||
// Expose private seams from an isolated copy, without adding production exports.
|
||||
// The smoke suite covers the fetch/ACP/MCP path; these cases cover batched
|
||||
// client payloads that the sequential fake ACP server cannot emit itself.
|
||||
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "agy-compat-test-"))
|
||||
const entry = new URL("../index.mjs", import.meta.url)
|
||||
let source = fs.readFileSync(entry, "utf8")
|
||||
source = source.replace(/from "(\.\/[^"\n]+)"/g, (_, target) => `from ${JSON.stringify(new URL(target, entry).href)}`)
|
||||
fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, withStateLock, execOnce };\n")
|
||||
const { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, withStateLock, execOnce } = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href)
|
||||
after(() => fs.rmSync(workspace, { recursive: true, force: true }))
|
||||
|
||||
const image = { type: "image", source: { type: "base64", media_type: "image/png", data: "aW1hZ2VB" } }
|
||||
const result = (id, name, text) => ({
|
||||
block: { type: "tool_result", tool_use_id: id, content: text },
|
||||
call: { id, name },
|
||||
result: { content: [{ type: "text", text }], isError: false },
|
||||
})
|
||||
const bodyFor = content => ({ messages: [{ role: "assistant", content: [] }, { role: "user", content }] })
|
||||
|
||||
test("images and dimension notes belong to their preceding result in a batch", () => {
|
||||
const a = result("call_a", "Read", "first")
|
||||
const b = result("call_b", "Read", "second")
|
||||
const body = bodyFor([a.block, image, { type: "text", text: "[Image: first screenshot]" }, b.block])
|
||||
const { results } = inspectToolTurn([a, b], body)
|
||||
assert.deepEqual(results[0].result.content.map(part => part.type), ["text", "image", "text"])
|
||||
assert.equal(results[0].result.content[1].data, image.source.data)
|
||||
assert.deepEqual(results[1].result.content, [{ type: "text", text: "second" }])
|
||||
})
|
||||
|
||||
test("a companion cannot attach to a different preceding tool", () => {
|
||||
const skill = result("call_skill", "Skill", "Launching skill: review")
|
||||
const read = result("call_read", "Read", "file text")
|
||||
for (const text of ["ARGUMENTS: review", "Tool loaded.", "[Image: screenshot]"]) {
|
||||
assert.throws(() => inspectToolTurn([skill, read], bodyFor([skill.block, read.block, { type: "text", text }])), /text beside a live tool_result/)
|
||||
}
|
||||
})
|
||||
|
||||
test("a partial ID rename maps by full history without discarding the live ID anchor", () => {
|
||||
const original = [
|
||||
{ type: "tool_use", id: "original_a", name: "Read", input: { path: "a" } },
|
||||
{ type: "tool_use", id: "original_b", name: "Read", input: { path: "b" } },
|
||||
]
|
||||
const expectedMessages = [{ role: "user", content: "read both" }, { role: "assistant", content: original }]
|
||||
const history = structuredClone(expectedMessages)
|
||||
history[1].content[1].id = "renamed_b"
|
||||
const turn = { finalized: false }
|
||||
const proc = { turn, expectedMessages, matchesHistory: value => historyKey(value) === historyKey(expectedMessages) }
|
||||
const calls = original.map(call => ({ ...call, mcpResponded: false }))
|
||||
allProcs.add(proc)
|
||||
calls.forEach(call => toolCalls.set(call.id, { proc, turn, call }))
|
||||
try {
|
||||
const blocks = ["original_a", "renamed_b"].map(id => ({ type: "tool_result", tool_use_id: id, content: "done" }))
|
||||
const matched = matchToolResults({ messages: [...history, { role: "user", content: blocks }] }, blocks)
|
||||
assert.deepEqual(matched.map(item => item.match?.call?.id), ["original_a", "original_b"])
|
||||
} finally {
|
||||
allProcs.delete(proc)
|
||||
calls.forEach(call => toolCalls.delete(call.id))
|
||||
}
|
||||
})
|
||||
|
||||
test("history replay keeps image bytes between their original surrounding text", () => {
|
||||
const parts = renderInitialPromptParts({ messages: [
|
||||
{ role: "user", content: [{ type: "text", text: "before first image" }, image, { type: "text", text: "after first image" }] },
|
||||
{ role: "assistant", content: "old reply" },
|
||||
{ role: "user", content: "current question" },
|
||||
] }, null, true)
|
||||
assert.deepEqual(parts.map(part => part.type), ["text", "image", "text"])
|
||||
assert.ok(parts[0].text.endsWith("Human: before first image"))
|
||||
assert.ok(parts[2].text.startsWith("after first image\nAssistant: old reply"))
|
||||
assert.ok(parts[2].text.endsWith("<current_turn>\ncurrent question\n</current_turn>"))
|
||||
})
|
||||
|
||||
test("state lock recovers a stale lock only after its owning process has exited", () => {
|
||||
const file = path.join(workspace, "dead-owner-state.json")
|
||||
fs.writeFileSync(file + ".lock", JSON.stringify({ pid: 2147483647 }))
|
||||
const old = new Date(Date.now() - 10_000)
|
||||
fs.utimesSync(file + ".lock", old, old)
|
||||
let wrote = false
|
||||
withStateLock(file, () => { wrote = true })
|
||||
assert.equal(wrote, true)
|
||||
assert.equal(fs.existsSync(file + ".lock"), false)
|
||||
})
|
||||
|
||||
async function captureExec(callback, mode = "close") {
|
||||
const originalSpawn = childProcess.spawn
|
||||
const originalEnv = process.env
|
||||
const originalSetTimeout = globalThis.setTimeout
|
||||
const calls = []
|
||||
const delays = []
|
||||
const inherited = { PATH: "parent-path", AGY_CLI_DISABLE_AUTO_UPDATE: "false" }
|
||||
try {
|
||||
process.env = inherited
|
||||
globalThis.setTimeout = (callback, delay, ...args) => {
|
||||
delays.push(delay)
|
||||
return originalSetTimeout(callback, mode === "timeout" ? 0 : delay, ...args)
|
||||
}
|
||||
childProcess.spawn = (file, args, options) => {
|
||||
calls.push({ file, args, options })
|
||||
if (mode === "throw") throw new Error("fixture spawn failure")
|
||||
const child = new EventEmitter()
|
||||
child.stdout = new PassThrough()
|
||||
child.stderr = new PassThrough()
|
||||
child.kill = signal => {
|
||||
calls.at(-1).signal = signal
|
||||
queueMicrotask(() => child.emit("close", null))
|
||||
}
|
||||
queueMicrotask(() => {
|
||||
child.stdout.write("fixture output")
|
||||
child.stderr.write("fixture error output")
|
||||
if (mode === "close") child.emit("close", 7)
|
||||
if (mode === "error") child.emit("error", new Error("fixture async failure"))
|
||||
})
|
||||
return child
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
await callback(calls, delays, inherited)
|
||||
assert.equal(inherited.AGY_CLI_DISABLE_AUTO_UPDATE, "false")
|
||||
} finally {
|
||||
childProcess.spawn = originalSpawn
|
||||
syncBuiltinESMExports()
|
||||
process.env = originalEnv
|
||||
globalThis.setTimeout = originalSetTimeout
|
||||
}
|
||||
}
|
||||
|
||||
test("execOnce agy branch forces hidden windows and keeps a user-set update value without mutating options", async () => {
|
||||
await captureExec(async (calls, delays) => {
|
||||
const env = Object.freeze({ CALLER_ONLY: "kept", AGY_CLI_DISABLE_AUTO_UPDATE: "false" })
|
||||
const opts = Object.freeze({ env, windowsHide: false, cwd: "workspace", timeoutMs: 1234 })
|
||||
const args = Object.freeze(["models"])
|
||||
const result = await execOnce("agy", args, opts)
|
||||
assert.deepEqual(result, { err: null, stdout: "fixture output", stderr: "fixture error output", code: 7, timedOut: false })
|
||||
assert.equal(calls[0].file, "agy")
|
||||
assert.equal(calls[0].args, args)
|
||||
assert.equal(calls[0].options.windowsHide, true)
|
||||
assert.equal(calls[0].options.env.AGY_CLI_DISABLE_AUTO_UPDATE, "false")
|
||||
assert.equal(calls[0].options.env.CALLER_ONLY, "kept")
|
||||
assert.equal(calls[0].options.env.PATH, "parent-path")
|
||||
assert.equal(calls[0].options.cwd, "workspace")
|
||||
assert.deepEqual(calls[0].options.stdio, ["ignore", "pipe", "pipe"])
|
||||
assert.deepEqual(delays, [1234])
|
||||
assert.equal(env.AGY_CLI_DISABLE_AUTO_UPDATE, "false")
|
||||
assert.equal(opts.windowsHide, false)
|
||||
})
|
||||
})
|
||||
|
||||
test("execOnce taskkill uses generic spawn, keeps caller env and cannot expose a window", async () => {
|
||||
await captureExec(async (calls, delays) => {
|
||||
const args = Object.freeze(["/T", "/F", "/PID", "12345"])
|
||||
for (const env of [Object.freeze({ CALLER_ONLY: "kept" }), Object.freeze({ AGY_CLI_DISABLE_AUTO_UPDATE: "false" })]) {
|
||||
const opts = Object.freeze({ env, windowsHide: false, timeoutMs: 3000 })
|
||||
const result = await execOnce("taskkill", args, opts)
|
||||
const actual = calls.at(-1)
|
||||
assert.equal(actual.file, "taskkill")
|
||||
assert.equal(actual.args, args)
|
||||
assert.equal(actual.options.windowsHide, true, "taskkill must remain hidden after caller overrides")
|
||||
assert.equal(actual.options.env, env, "taskkill must use generic spawn without agy env injection")
|
||||
assert.deepEqual(actual.options.env, env)
|
||||
assert.equal(opts.windowsHide, false)
|
||||
assert.equal(result.code, 7)
|
||||
assert.equal(result.stdout, "fixture output")
|
||||
assert.equal(result.stderr, "fixture error output")
|
||||
assert.equal(result.timedOut, false)
|
||||
}
|
||||
await execOnce("taskkill", args)
|
||||
assert.equal(calls.at(-1).options.env, undefined, "taskkill without caller env must inherit the parent environment")
|
||||
assert.deepEqual(delays, [3000, 3000, 30000])
|
||||
})
|
||||
})
|
||||
|
||||
test("execOnce taskkill retains its three-second deadline and kills only its child", async () => {
|
||||
await captureExec(async (calls, delays) => {
|
||||
const result = await execOnce("taskkill", ["/T", "/F", "/PID", "12345"], { timeoutMs: 3000 })
|
||||
assert.deepEqual(delays, [3000])
|
||||
assert.equal(calls[0].signal, "SIGKILL")
|
||||
assert.equal(result.timedOut, true)
|
||||
assert.equal(result.code, null)
|
||||
assert.equal(result.stdout, "fixture output")
|
||||
}, "timeout")
|
||||
})
|
||||
|
||||
test("execOnce still collects synchronous and asynchronous spawn failures", async () => {
|
||||
for (const mode of ["throw", "error"]) {
|
||||
await captureExec(async () => {
|
||||
const result = await execOnce("taskkill", [])
|
||||
assert.match(result.err.message, /fixture/)
|
||||
assert.equal(result.code, null)
|
||||
assert.equal(result.timedOut, false)
|
||||
}, mode)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
// Preloaded for test/platform.mjs, test/compat.mjs and test/usage.mjs under bun.
|
||||
// Those tests replace childProcess.spawn and call syncBuiltinESMExports(), which
|
||||
// Node uses to push the change into named imports. Bun has no such step, so
|
||||
// node:child_process is mocked once here: its default export is a plain object
|
||||
// the tests write to, and every named export calls through that object. Each
|
||||
// file runs in its own bun process (see ../agy-cli.test.mjs), so the mock never
|
||||
// reaches another package's tests.
|
||||
import { mock } from "bun:test"
|
||||
import * as real from "node:child_process"
|
||||
|
||||
const live = { ...real }
|
||||
const named = {}
|
||||
for (const [key, value] of Object.entries(real)) {
|
||||
if (key === "default") continue
|
||||
named[key] = typeof value === "function" ? (...args) => live[key](...args) : value
|
||||
}
|
||||
mock.module("node:child_process", () => ({ ...named, default: live }))
|
||||
@@ -0,0 +1,164 @@
|
||||
import assert from "node:assert/strict"
|
||||
import childProcess from "node:child_process"
|
||||
import { syncBuiltinESMExports } from "node:module"
|
||||
import { test } from "node:test"
|
||||
import { agyCandidates, agySpawnSpec, childEnv, spawnAgy, windowsMcpShim } from "../platform.mjs"
|
||||
|
||||
test("Windows discovery considers exe/cmd/bat, Path and LOCALAPPDATA", () => {
|
||||
const candidates = agyCandidates({ Path: 'C:\\Program Files\\agy;D:\\tools', LOCALAPPDATA: 'C:\\Users\\Test\\AppData\\Local' }, 'C:\\Users\\Test', 'win32')
|
||||
assert.deepEqual(candidates.slice(0, 3), ['C:\\Program Files\\agy\\agy.exe', 'C:\\Program Files\\agy\\agy.cmd', 'C:\\Program Files\\agy\\agy.bat'])
|
||||
assert.ok(candidates.includes('D:\\tools\\agy.cmd'))
|
||||
assert.ok(candidates.includes('C:\\Users\\Test\\AppData\\Local\\agy\\bin\\agy.exe'))
|
||||
assert.equal(agyCandidates({ AGY_PATH: 'C:\\custom\\agy.bat' }, 'C:\\Users\\Test', 'win32')[0], 'C:\\custom\\agy.bat')
|
||||
})
|
||||
|
||||
test("POSIX discovery and direct executable arguments do not use a shell", () => {
|
||||
assert.deepEqual(agyCandidates({ PATH: '/usr/bin:/opt/bin' }, '/home/test', 'linux').slice(0, 2), ['/usr/bin/agy', '/opt/bin/agy'])
|
||||
for (const [file, platform] of [['/opt/agy', 'linux'], ['C:\\agy.exe', 'win32'], ['/opt/agy.cmd', 'linux']]) {
|
||||
const args = ['acp', '--add-dir', 'space & percent% quote"']
|
||||
assert.deepEqual(agySpawnSpec(file, args, platform), { file, args, options: {} })
|
||||
}
|
||||
})
|
||||
|
||||
test("Windows batch wrappers use cmd explicitly and escape shell metacharacters", () => {
|
||||
for (const extension of ['cmd', 'bat', 'CMD']) {
|
||||
const spec = agySpawnSpec(`C:\\Program Files\\agy.${extension}`, ['acp', '--add-dir', 'C:\\a & b\\%NAME%!\\'], 'win32', { ComSpec: 'C:\\Windows\\System32\\cmd.exe' })
|
||||
assert.equal(spec.file, 'C:\\Windows\\System32\\cmd.exe')
|
||||
assert.deepEqual(spec.args.slice(0, 4), ['/d', '/v:off', '/s', '/c'])
|
||||
assert.equal(spec.options.windowsVerbatimArguments, true)
|
||||
assert.equal(spec.options.windowsHide, true)
|
||||
const command = spec.args.at(-1)
|
||||
assert.ok(command.includes('Program^ Files'))
|
||||
for (const character of ['&', '%', '!']) assert.ok(command.includes('^' + character), command)
|
||||
assert.ok(command.includes('b\\^%NAME^%^!\\\\'), command)
|
||||
}
|
||||
})
|
||||
|
||||
test("batch invocation rejects command line breaks", () => {
|
||||
for (const value of ['bad\npath', 'bad\rpath', 'bad\0path']) {
|
||||
assert.throws(() => agySpawnSpec('agy.cmd', ['--add-dir', value], 'win32'), /line break or NUL/)
|
||||
assert.throws(() => agySpawnSpec(value + '.cmd', [], 'win32'), /line break or NUL/)
|
||||
}
|
||||
})
|
||||
|
||||
test("nc.cmd quotes paths, escapes percent expansion and disables delayed expansion", () => {
|
||||
const script = windowsMcpShim('C:\\Program Files\\node.exe', 'C:\\user%name%!\\mcp-server.mjs')
|
||||
assert.equal(script, '@echo off\r\nsetlocal DisableDelayedExpansion\r\n"C:\\Program Files\\node.exe" "C:\\user%%name%%!\\mcp-server.mjs"\r\n')
|
||||
assert.throws(() => windowsMcpShim('node.exe', 'bad"path'), /invalid Windows MCP shim path/)
|
||||
})
|
||||
|
||||
test("npm cmd-shims escape metacharacters for the second expansion pass", () => {
|
||||
const spec = agySpawnSpec('C:\\project\\node_modules\\.bin\\agy.cmd', ['a & %NAME%!'], 'win32', {})
|
||||
for (const character of ['&', '%', '!']) assert.ok(spec.args.at(-1).includes('^^^' + character))
|
||||
})
|
||||
|
||||
function captureSpawn(platform, inherited, callback) {
|
||||
const originalSpawn = childProcess.spawn
|
||||
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform")
|
||||
const originalEnv = process.env
|
||||
const calls = []
|
||||
const child = {}
|
||||
try {
|
||||
Object.defineProperty(process, "platform", { ...platformDescriptor, value: platform })
|
||||
process.env = inherited
|
||||
childProcess.spawn = (file, args, options) => {
|
||||
calls.push({ file, args, options })
|
||||
return child
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
callback(calls, child)
|
||||
} finally {
|
||||
childProcess.spawn = originalSpawn
|
||||
syncBuiltinESMExports()
|
||||
process.env = originalEnv
|
||||
Object.defineProperty(process, "platform", platformDescriptor)
|
||||
}
|
||||
}
|
||||
|
||||
for (const platform of ["win32", "linux", "darwin"]) {
|
||||
test(`spawnAgy hides windows and keeps a user-set update value on ${platform}`, () => {
|
||||
const parent = Object.freeze({ PATH: "parent-path", PARENT_ONLY: "kept", AGY_CLI_DISABLE_AUTO_UPDATE: "false" })
|
||||
captureSpawn(platform, parent, (calls, child) => {
|
||||
const file = platform === "win32" ? "C:\\Program Files\\Antigravity\\agy.exe" : "/opt/agy"
|
||||
const args = Object.freeze(["models", "space & percent% quote\""])
|
||||
const signal = new AbortController().signal
|
||||
const env = Object.freeze({ PATH: "caller-path", CALLER_ONLY: "kept", AGY_CLI_DISABLE_AUTO_UPDATE: "false" })
|
||||
const options = Object.freeze({ env, cwd: "workspace", stdio: ["ignore", "pipe", "pipe"], detached: true, windowsHide: false, signal })
|
||||
const before = structuredClone({ parent, env, args, options: { ...options, signal: undefined } })
|
||||
for (const supplied of [undefined, {}, { env: {} }, options]) {
|
||||
assert.equal(spawnAgy(file, args, supplied), child)
|
||||
const actual = calls.at(-1)
|
||||
assert.equal(actual.file, file)
|
||||
assert.equal(actual.args, args)
|
||||
assert.equal(actual.options.windowsHide, true, "spawnAgy must hide every child window")
|
||||
assert.equal(actual.options.env.AGY_CLI_DISABLE_AUTO_UPDATE, "false", "a value the user set is passed on as written")
|
||||
assert.equal(actual.options.env.PARENT_ONLY, "kept")
|
||||
assert.notEqual(actual.options.env, parent)
|
||||
assert.notEqual(actual.options.env, supplied?.env)
|
||||
}
|
||||
const actual = calls.at(-1).options
|
||||
for (const key of ["cwd", "stdio", "detached", "signal"]) assert.equal(actual[key], options[key])
|
||||
assert.equal(actual.env.PATH, "caller-path")
|
||||
assert.equal(actual.env.CALLER_ONLY, "kept")
|
||||
assert.deepEqual({ parent, env, args, options: { ...options, signal: undefined } }, before)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
test("spawnAgy deduplicates Windows env aliases without losing caller PATH or MCP settings", () => {
|
||||
const parent = Object.freeze({ Path: "parent-path", path: "duplicate-parent", agy_cli_disable_auto_update: "false", PARENT_ONLY: "kept", Mixed: "parent" })
|
||||
const env = Object.freeze({ PATH: "shim;caller-path", AGY_CLI_DISABLE_AUTO_UPDATE: "false", Agy_Cli_Disable_Auto_Update: "false", MIXED: "caller", AGY_BRIDGE_CONTROL_PORT: "12345", AGY_BRIDGE_TOKEN: "fixture" })
|
||||
captureSpawn("win32", parent, calls => {
|
||||
spawnAgy("C:\\Program Files\\Antigravity\\agy.exe", [], { env, windowsHide: false })
|
||||
const actual = calls[0].options.env
|
||||
assert.deepEqual(Object.keys(actual).filter(key => /^path$/i.test(key)), ["PATH"])
|
||||
assert.equal(actual.PATH, "shim;caller-path")
|
||||
const update = Object.keys(actual).filter(key => /^agy_cli_disable_auto_update$/i.test(key))
|
||||
assert.equal(update.length, 1)
|
||||
assert.equal(actual[update[0]], "false")
|
||||
assert.equal(actual.MIXED, "caller")
|
||||
assert.equal(actual.Mixed, undefined)
|
||||
for (const key of ["AGY_BRIDGE_CONTROL_PORT", "AGY_BRIDGE_TOKEN"]) assert.equal(actual[key], env[key])
|
||||
assert.equal(parent.Path, "parent-path")
|
||||
assert.equal(parent.agy_cli_disable_auto_update, "false")
|
||||
assert.equal(env.Agy_Cli_Disable_Auto_Update, "false")
|
||||
})
|
||||
})
|
||||
|
||||
for (const extension of ["cmd", "bat"]) {
|
||||
test(`spawnAgy preserves Windows .${extension} escaping and hides the window`, () => {
|
||||
const parent = Object.freeze({ ComSpec: "C:\\Windows\\System32\\cmd.exe", AGY_CLI_DISABLE_AUTO_UPDATE: "false" })
|
||||
captureSpawn("win32", parent, calls => {
|
||||
const file = `C:\\Program Files\\Antigravity & Tools\\agy.${extension}`
|
||||
const args = ["acp", "--add-dir", "C:\\space & percent% !\\"]
|
||||
const expected = agySpawnSpec(file, args, "win32", parent)
|
||||
spawnAgy(file, args, { windowsHide: false, windowsVerbatimArguments: false, env: { AGY_CLI_DISABLE_AUTO_UPDATE: "false" } })
|
||||
assert.equal(calls[0].file, expected.file)
|
||||
assert.deepEqual(calls[0].args, expected.args)
|
||||
assert.equal(calls[0].options.windowsVerbatimArguments, true)
|
||||
assert.equal(calls[0].options.windowsHide, true)
|
||||
assert.equal(calls[0].options.env.AGY_CLI_DISABLE_AUTO_UPDATE, "false")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
test("with nothing set, the plugin's agy children run with auto-update off", () => {
|
||||
for (const platform of ["win32", "linux", "darwin"]) {
|
||||
captureSpawn(platform, Object.freeze({ PATH: "parent-path" }), calls => {
|
||||
spawnAgy(platform === "win32" ? "C:\\agy.exe" : "/opt/agy", [], { env: { CALLER_ONLY: "kept" } })
|
||||
assert.equal(calls[0].options.env.AGY_CLI_DISABLE_AUTO_UPDATE, "true")
|
||||
assert.equal(calls[0].options.env.CALLER_ONLY, "kept")
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("childEnv keeps any user-set update value, in any case, from the parent or the caller", () => {
|
||||
for (const value of ["false", "0", "", "true"]) {
|
||||
assert.equal(childEnv({ AGY_CLI_DISABLE_AUTO_UPDATE: value }, {}, "linux").AGY_CLI_DISABLE_AUTO_UPDATE, value)
|
||||
assert.equal(childEnv({}, { AGY_CLI_DISABLE_AUTO_UPDATE: value }, "linux").AGY_CLI_DISABLE_AUTO_UPDATE, value)
|
||||
}
|
||||
const windows = childEnv({ agy_cli_disable_auto_update: "false" }, {}, "win32")
|
||||
assert.deepEqual(Object.keys(windows).filter(key => /^agy_cli_disable_auto_update$/i.test(key)), ["agy_cli_disable_auto_update"])
|
||||
assert.equal(childEnv({ PATH: "p" }, { X: undefined }, "linux").AGY_CLI_DISABLE_AUTO_UPDATE, "true")
|
||||
assert.equal("X" in childEnv({ PATH: "p" }, { X: undefined }, "linux"), false)
|
||||
})
|
||||
@@ -0,0 +1,417 @@
|
||||
// magpie-agy regressions for the fixes merged on top of PR #8 that the
|
||||
// upstream suites do not cover: execOnce timeouts (A3), model limits (A5),
|
||||
// agy re-discovery (A6), the no-progress repeat limit (A7), the 30 ms tool
|
||||
// batch (A9), layout_flip diagnostics (A11), pool pressure on detached tool
|
||||
// turns and compaction forks (A15), and the 112 KiB initial prompt budget (A16).
|
||||
//
|
||||
// Run: node --experimental-vm-modules --test test-repeat-batch.mjs
|
||||
// Everything goes through the real index.mjs entry points; see testkit.mjs.
|
||||
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import {
|
||||
baseBody, continueWithToolResults, createBridgeKit, readSse, sleep, tick,
|
||||
} from "./testkit.mjs"
|
||||
|
||||
async function withKit(options, fn) {
|
||||
const kit = await createBridgeKit(options)
|
||||
try {
|
||||
return await fn(kit)
|
||||
} finally {
|
||||
await kit.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function promptText(params) {
|
||||
return (params?.prompt || []).map((part) => (part.type === "text" ? part.text : "")).join("")
|
||||
}
|
||||
|
||||
function prompts(kit) {
|
||||
return kit.acpLog.filter((entry) => entry.method === "session/prompt").map((entry) => promptText(entry.params))
|
||||
}
|
||||
|
||||
function captureStderr() {
|
||||
const lines = []
|
||||
const original = process.stderr.write
|
||||
process.stderr.write = function write(chunk, ...rest) {
|
||||
const text = String(chunk)
|
||||
if (text.startsWith("[agy-bridge] ")) {
|
||||
lines.push(JSON.parse(text.slice("[agy-bridge] ".length)))
|
||||
return true
|
||||
}
|
||||
return original.call(this, chunk, ...rest)
|
||||
}
|
||||
return { lines, restore: () => { process.stderr.write = original } }
|
||||
}
|
||||
|
||||
// A prompt script keyed by the text the bridge sent: "TOOL" asks for one Read
|
||||
// and waits for its MCP reply; everything else answers with plain text.
|
||||
function scriptedAgent(kit, replies = {}) {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
const text = promptText({ prompt: agent.prompt })
|
||||
for (const [marker, reply] of Object.entries(replies)) {
|
||||
if (text.includes(marker)) {
|
||||
await agent.text(reply)
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
}
|
||||
const current = text.includes("<current_turn>") ? text.slice(text.lastIndexOf("<current_turn>")) : text
|
||||
if (current.includes("TOOL")) {
|
||||
await agent.tool("Read", { path: `/repo/${agent.index}.txt` })
|
||||
await agent.text("after tool")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
await agent.text(`answer ${agent.index}`)
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
}
|
||||
|
||||
async function errorOf(response) {
|
||||
return { status: response.status, retry: response.headers.get("x-should-retry"), body: await response.json() }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- A3 execOnce
|
||||
|
||||
test("A3: execOnce resolves on its deadline even when the killed child never closes", async () => {
|
||||
await withKit({ modelsBehavior: { hang: true } }, async (kit) => {
|
||||
const execOnce = kit.module.__agyTestExecOnce
|
||||
const started = performance.now()
|
||||
const pending = execOnce(kit.agyPath, ["models"], { timeoutMs: 50 })
|
||||
// A grandchild keeps the pipes open: the kill does not produce "close".
|
||||
for (const child of kit.children) child.kill = () => true
|
||||
// Bound the wait ourselves: the old defect leaves this promise pending forever.
|
||||
let guard
|
||||
const result = await Promise.race([pending, new Promise((resolve) => {
|
||||
guard = setTimeout(() => resolve({ hung: true }), 2_000)
|
||||
})])
|
||||
clearTimeout(guard)
|
||||
assert.notEqual(result.hung, true, "execOnce never resolved after its deadline")
|
||||
const elapsed = performance.now() - started
|
||||
assert.equal(result.timedOut, true)
|
||||
assert.equal(result.code, null)
|
||||
assert.equal(result.err, null)
|
||||
assert.ok(elapsed < 1_000, `execOnce took ${Math.round(elapsed)}ms after a 50ms deadline`)
|
||||
})
|
||||
})
|
||||
|
||||
// ------------------------------------------------------------------ A5 limit
|
||||
|
||||
test("A5: models() reports per-family limits next to the upstream image capabilities", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const models = await kit.models()
|
||||
assert.deepEqual(models["gemini-4-argon"].limit, { context: 1048576, output: 65536 })
|
||||
assert.deepEqual(models["gemini-3.8-flash"].limit, { context: 1048576, output: 65536 })
|
||||
// Claude and GPT-OSS limits are checked once a session offers them (catalog.mjs).
|
||||
assert.equal(models["claude-opus-5-5"], undefined, "no session has offered Claude yet")
|
||||
assert.equal(models["gemini-4-argon"].capabilities?.input?.image, true, "acb image capability must stay")
|
||||
assert.equal(models["gemini-4-argon"].reasoning, true)
|
||||
})
|
||||
})
|
||||
|
||||
// ------------------------------------------------------- A6 agy re-discovery
|
||||
|
||||
test("A6: findAgy searches again when PATH changes instead of keeping the first hit", async () => {
|
||||
await withKit({ agyPath: null }, async (kit) => {
|
||||
const findAgy = kit.module.__agyTestFindAgy
|
||||
assert.equal(findAgy(), null)
|
||||
const first = kit.makeFakeAgy("first")
|
||||
// agyCandidates on win32 only matches agy.exe/.cmd/.bat names.
|
||||
assert.equal(path.basename(first), process.platform === "win32" ? "agy.exe" : "agy")
|
||||
kit.env.PATH = path.dirname(first)
|
||||
assert.equal(findAgy(), first)
|
||||
const second = kit.makeFakeAgy("second")
|
||||
kit.env.PATH = path.dirname(second)
|
||||
assert.equal(findAgy(), second, "a cached path from the old PATH was reused")
|
||||
fs.rmSync(second)
|
||||
kit.env.PATH = path.dirname(first)
|
||||
assert.equal(findAgy(), first)
|
||||
})
|
||||
})
|
||||
|
||||
// ------------------------------------------------ A7 no-progress repeat limit
|
||||
|
||||
async function pendingToolTurn(kit, body) {
|
||||
const parsed = await readSse(await kit.request(body))
|
||||
assert.equal(parsed.stopReason, "tool_use")
|
||||
return parsed
|
||||
}
|
||||
|
||||
function unmatchedRound(body, { answerId = "toolu_unmatched", callId = "toolu_unmatched" } = {}) {
|
||||
return {
|
||||
...body,
|
||||
messages: [
|
||||
...body.messages,
|
||||
{ role: "assistant", content: [{ type: "text", text: "a different recorded response" },
|
||||
{ type: "tool_use", id: callId, name: "Read", input: { path: "/elsewhere" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: answerId, content: "UNMATCHED RESULT" }] },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
test("A7: the third unmatched repeat against a quiet turn replays the request's own tool round", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit, { "UNMATCHED RESULT": "replayed from history" })
|
||||
const body = baseBody({ metadata: { user_id: "repeat-replay" }, messages: [{ role: "user", content: "TOOL start" }] })
|
||||
await pendingToolTurn(kit, body)
|
||||
const unmatched = unmatchedRound(body)
|
||||
for (const attempt of [1, 2]) {
|
||||
const response = await kit.request(unmatched)
|
||||
assert.equal(response.status, 409, `attempt ${attempt} must stay 409`)
|
||||
assert.equal(response.headers.get("x-should-retry"), null)
|
||||
await response.text()
|
||||
}
|
||||
assert.equal(kit.acpSpawns.length, 1, "the first two attempts must not start a process")
|
||||
const third = await readSse(await kit.request(unmatched))
|
||||
assert.equal(third.stopReason, "end_turn")
|
||||
assert.equal(third.content.find((block) => block.type === "text")?.text, "replayed from history")
|
||||
assert.equal(kit.acpSpawns.length, 2, "the replay runs on a fresh process")
|
||||
assert.ok(prompts(kit).at(-1).includes("UNMATCHED RESULT"))
|
||||
})
|
||||
})
|
||||
|
||||
test("A7: a third repeat that cannot be replayed ends in a terminal 400 with attempts and turn_id", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const body = baseBody({ metadata: { user_id: "repeat-terminal" }, messages: [{ role: "user", content: "TOOL start" }] })
|
||||
await pendingToolTurn(kit, body)
|
||||
// The result answers an ID that its own assistant message never issued.
|
||||
const broken = unmatchedRound(body, { answerId: "toolu_answer", callId: "toolu_other" })
|
||||
const statuses = []
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const response = await kit.request(broken)
|
||||
statuses.push(response.status)
|
||||
await response.text()
|
||||
}
|
||||
assert.deepEqual(statuses, [409, 409])
|
||||
const terminal = await errorOf(await kit.request(broken))
|
||||
assert.equal(terminal.status, 400)
|
||||
assert.equal(terminal.retry, "false")
|
||||
assert.equal(terminal.body.error.code, "tool_history_incomplete")
|
||||
assert.equal(terminal.body.error.attempts, 3)
|
||||
assert.match(terminal.body.error.turn_id, /^turn_[0-9a-f]+$/)
|
||||
assert.equal(kit.acpSpawns.length, 1, "an unreplayable round never starts a process")
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------- A9 30 ms batch
|
||||
|
||||
test("A9: tool calls agy issues across adjacent event-loop turns leave in one response", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.toolsAcrossTicks([["Read", { path: "/a" }], ["Read", { path: "/b" }], ["Read", { path: "/c" }]])
|
||||
await agent.text("done")
|
||||
return { stopReason: "end_turn" }
|
||||
})
|
||||
const body = baseBody({ metadata: { user_id: "batch" } })
|
||||
const first = await readSse(await kit.request(body))
|
||||
assert.equal(first.stopReason, "tool_use")
|
||||
assert.deepEqual(first.content.filter((block) => block.type === "tool_use").map((block) => block.input.path), ["/a", "/b", "/c"])
|
||||
const final = await readSse(await kit.request(continueWithToolResults(body, first)))
|
||||
assert.equal(final.stopReason, "end_turn")
|
||||
})
|
||||
})
|
||||
|
||||
// ------------------------------------------------- A10 canonical system rule
|
||||
|
||||
test("A10: only the opening system prefix is lifted, so a trailing system context keeps the key across turns", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const canonicalBody = kit.module.__agyTestCanonicalBody
|
||||
const conversationKey = kit.module.__agyTestConversationKey
|
||||
const inline = { system: "base", messages: [{ role: "system", content: [{ type: "text", text: "opening" }] },
|
||||
{ role: "user", content: "hi" }] }
|
||||
const lifted = canonicalBody(inline)
|
||||
assert.equal(lifted.system, "base\n\nopening")
|
||||
assert.deepEqual(lifted.messages, [{ role: "user", content: "hi" }])
|
||||
assert.equal(canonicalBody(lifted), lifted, "canonicalBody is idempotent")
|
||||
const hoisted = { system: "base\nopening", messages: [{ role: "user", content: "hi" }] }
|
||||
assert.equal(conversationKey(inline), conversationKey(hoisted), "both layouts share one key")
|
||||
// Claude Code: a trailing SessionStart context on turn one, an assistant on turn two.
|
||||
const turn1 = { system: "S", messages: [{ role: "user", content: "one" }, { role: "system", content: "SessionStart ctx" }] }
|
||||
const turn2 = { ...turn1, messages: [...turn1.messages, { role: "assistant", content: "reply" },
|
||||
{ role: "user", content: "two" }, { role: "system", content: "prompt ctx" }] }
|
||||
assert.equal(canonicalBody(turn1), turn1)
|
||||
assert.equal(canonicalBody(turn2), turn2, "a system message after the first user stays turn content")
|
||||
assert.equal(conversationKey(turn1), conversationKey(turn2))
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------- A11 layout_flip
|
||||
|
||||
async function flipLayouts(kit) {
|
||||
scriptedAgent(kit)
|
||||
const hook = "Opening hook context."
|
||||
const inline = baseBody({ metadata: { user_id: "layout" }, system: "base system",
|
||||
messages: [{ role: "system", content: hook }, { role: "user", content: "hello" }] })
|
||||
const first = await readSse(await kit.request(inline))
|
||||
const hoisted = { ...inline, system: `base system\n${hook}`, messages: [
|
||||
{ role: "user", content: "hello" },
|
||||
{ role: "assistant", content: first.content.map((block) => ({ type: "text", text: block.text })) },
|
||||
{ role: "user", content: "again" },
|
||||
] }
|
||||
const second = await readSse(await kit.request(hoisted))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
assert.equal(kit.acpSpawns.length, 1, "both layouts belong to one conversation")
|
||||
}
|
||||
|
||||
test("A11: layout_flip stays silent by default", async () => {
|
||||
const stderr = captureStderr()
|
||||
try {
|
||||
await withKit({}, flipLayouts)
|
||||
} finally {
|
||||
stderr.restore()
|
||||
}
|
||||
assert.equal(stderr.lines.filter((row) => row.action === "layout_flip").length, 0)
|
||||
})
|
||||
|
||||
test("A11: AGY_BRIDGE_EVENTS=verbose reports layout_flip with a req_id and no content", async () => {
|
||||
const stderr = captureStderr()
|
||||
try {
|
||||
await withKit({ env: { AGY_BRIDGE_EVENTS: "verbose" } }, flipLayouts)
|
||||
} finally {
|
||||
stderr.restore()
|
||||
}
|
||||
const flips = stderr.lines.filter((row) => row.action === "layout_flip")
|
||||
assert.equal(flips.length, 1)
|
||||
assert.equal(flips[0].layout, "hoisted")
|
||||
assert.match(flips[0].req_id, /^req_[0-9a-f]{8}$/)
|
||||
assert.ok(!JSON.stringify(flips).includes("hello") && !JSON.stringify(flips).includes("Opening hook"))
|
||||
})
|
||||
|
||||
// ------------------------------------------------------- A15 pool pressure
|
||||
|
||||
test("A15: a full pool evicts the oldest long-detached tool turn instead of answering 503, and that conversation replays later", async () => {
|
||||
const env = { AGY_BRIDGE_MAX_PROCS: "2", AGY_BRIDGE_DETACHED_EVICT_MS: "30000" }
|
||||
const stderr = captureStderr()
|
||||
try {
|
||||
await withKit({ env }, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const convA = baseBody({ metadata: { user_id: "pool-a" }, messages: [{ role: "user", content: "TOOL a" }] })
|
||||
const convB = baseBody({ metadata: { user_id: "pool-b" }, messages: [{ role: "user", content: "TOOL b" }] })
|
||||
const convC = baseBody({ metadata: { user_id: "pool-c" }, messages: [{ role: "user", content: "plain c" }] })
|
||||
const pendingA = await pendingToolTurn(kit, convA)
|
||||
kit.clock.advance(1_000)
|
||||
await pendingToolTurn(kit, convB)
|
||||
|
||||
// Both turns detached only moments ago: the pool is genuinely busy.
|
||||
const busy = await errorOf(await kit.request(convC))
|
||||
assert.equal(busy.status, 503)
|
||||
assert.match(busy.body.error.message, /2 agy processes are running/)
|
||||
|
||||
kit.clock.advance(30_000)
|
||||
const served = await readSse(await kit.request(convC))
|
||||
assert.equal(served.stopReason, "end_turn", "pool pressure must evict instead of 503")
|
||||
const evicted = stderr.lines.filter((row) => row.action === "evicted" && row.reason === "pool_pressure_detached")
|
||||
assert.equal(evicted.length, 1)
|
||||
|
||||
// A's client returns with its real result: replayed on a new process.
|
||||
const spawnsBefore = kit.acpSpawns.length
|
||||
const resumed = await readSse(await kit.request(continueWithToolResults(convA, pendingA, () => "RESULT FOR A")))
|
||||
assert.equal(resumed.stopReason, "end_turn")
|
||||
assert.equal(kit.acpSpawns.length, spawnsBefore + 1)
|
||||
assert.ok(prompts(kit).at(-1).includes("RESULT FOR A"))
|
||||
assert.ok(prompts(kit).at(-1).includes("<conversation_history>"))
|
||||
})
|
||||
} finally {
|
||||
stderr.restore()
|
||||
}
|
||||
})
|
||||
|
||||
test("A15: a compacted or shortened history of the same conversation forks the detached tool turn instead of 503", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const opening = { role: "user", content: "start D" }
|
||||
const body = baseBody({ metadata: { user_id: "compact" }, messages: [opening] })
|
||||
const first = await readSse(await kit.request(body))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const withTool = { ...body, messages: [opening,
|
||||
{ role: "assistant", content: [{ type: "text", text: first.content[0].text }] },
|
||||
{ role: "user", content: "TOOL second" }] }
|
||||
await pendingToolTurn(kit, withTool)
|
||||
|
||||
// Compaction rewrote the assistant prefix; same length, different content.
|
||||
const compacted = { ...body, messages: [opening,
|
||||
{ role: "assistant", content: "summary of the earlier work" },
|
||||
{ role: "user", content: "continue after compaction" }] }
|
||||
const forked = await readSse(await kit.request(compacted))
|
||||
assert.equal(forked.stopReason, "end_turn")
|
||||
|
||||
// Then a shorter history than the turn's base: still a fork, never a 503.
|
||||
await pendingToolTurn(kit, { ...compacted, messages: [...compacted.messages,
|
||||
{ role: "assistant", content: forked.content.map((block) => ({ type: "text", text: block.text })) },
|
||||
{ role: "user", content: "TOOL third" }] })
|
||||
const shorter = await kit.request({ ...body, messages: [opening, { role: "user", content: "only this" }] })
|
||||
assert.equal(shorter.status, 200, await shorter.clone().text())
|
||||
assert.equal((await readSse(shorter)).stopReason, "end_turn")
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------- A16 112 KiB prompt budget
|
||||
|
||||
function bytes(text) {
|
||||
return Buffer.byteLength(text, "utf8")
|
||||
}
|
||||
|
||||
test("A16: a replay of more than 128 KiB of history stays within 112 KiB and keeps its closing tags", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const big = (label) => `${label} head ` + "history filler line with some words. ".repeat(500) + ` ${label} tail`
|
||||
const messages = [{ role: "user", content: "ANCHOR opening request" }]
|
||||
// 20 blocks of about 19 KiB: still about 165 KiB after each is clipped to 8 KiB.
|
||||
for (let index = 0; index < 20; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "text", text: big(`assistant-${index}`) }] })
|
||||
messages.push({ role: "user", content: `user follow-up ${index}` })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "text", text: "NEWEST assistant reply" }] })
|
||||
messages.push({ role: "user", content: "LATEST INSTRUCTION: summarize everything" })
|
||||
const body = baseBody({ metadata: { user_id: "budget" }, messages })
|
||||
assert.ok(bytes(JSON.stringify(messages)) > 128 * 1024, "fixture must exceed agy's 128 KiB cut")
|
||||
const parsed = await readSse(await kit.request(body))
|
||||
assert.equal(parsed.stopReason, "end_turn")
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`)
|
||||
assert.ok(prompt.includes("</conversation_history>\n\n<current_turn>\nLATEST INSTRUCTION: summarize everything\n</current_turn>"))
|
||||
assert.ok(prompt.endsWith("</current_turn>"))
|
||||
assert.ok(prompt.includes("ANCHOR opening request"), "the anchor message is kept")
|
||||
assert.ok(prompt.includes("NEWEST assistant reply"), "the newest history is kept")
|
||||
assert.ok(prompt.includes("[... earlier conversation history omitted to fit ACP 112 KiB prompt budget ...]"))
|
||||
assert.ok(prompt.includes("bytes of this history block omitted"), "oversized history blocks keep only head and tail")
|
||||
assert.ok(prompt.includes('Never output "[tool call ...]" text'))
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: an oversized current tool result keeps its head and tail and the frame stays intact", async () => {
|
||||
await withKit({ env: { AGY_BRIDGE_MAX_PROMPT_BYTES: String(64 * 1024) } }, async (kit) => {
|
||||
scriptedAgent(kit, { "RESULT HEAD": "handled" })
|
||||
const huge = "RESULT HEAD " + "x".repeat(200 * 1024) + " RESULT TAIL"
|
||||
const body = baseBody({ metadata: { user_id: "budget-current" }, messages: [
|
||||
{ role: "user", content: "TOOL read it" },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_big", name: "Read", input: { path: "/big" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_big", content: huge }] },
|
||||
] })
|
||||
const parsed = await readSse(await kit.request(body))
|
||||
assert.equal(parsed.stopReason, "end_turn")
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(bytes(prompt) <= 64 * 1024, `initial prompt is ${bytes(prompt)} bytes`)
|
||||
assert.ok(prompt.includes("RESULT HEAD") && prompt.includes("RESULT TAIL"))
|
||||
assert.ok(prompt.includes("</conversation_history>") && prompt.endsWith("\n</current_turn>"))
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: a short replay is rendered unchanged", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const body = baseBody({ metadata: { user_id: "budget-small" }, messages: [
|
||||
{ role: "user", content: "first" },
|
||||
{ role: "assistant", content: "reply" },
|
||||
{ role: "user", content: "second" },
|
||||
] })
|
||||
await readSse(await kit.request(body))
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(prompt.includes("<conversation_history>\nHuman: first\nAssistant: reply\n"))
|
||||
assert.ok(!prompt.includes("omitted"))
|
||||
await tick()
|
||||
await sleep(0)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,646 @@
|
||||
// magpie-agy 插件的受控加载夹具(仅供仓内 test-catalog / test-usage-settlement /
|
||||
// test-repeat-batch 使用)。源自 configs 仓 scripts/continuity/tests/agy_bridge_testkit.mjs。
|
||||
//
|
||||
// 用 vm.SourceTextModule 在当前上下文里加载**真实**仓内 index.mjs,相对的 ./usage.mjs
|
||||
// 与 ./platform.mjs 链接到同目录的真实文件;生产文件只读,不落盘任何副本。
|
||||
// 边界替身:
|
||||
// - node:child_process 的 spawn:`agy models` 与 `agy acp` 都换成进程内假子进程,
|
||||
// 后者讲真实 ACP JSON-RPC(initialize / session/new / set_model / prompt / cancel)。
|
||||
// index.mjs 与 platform.mjs(spawnAgy)共用同一个假 spawn。
|
||||
// - node:net 的 createServer:控制通道换成进程内假 socket,假 agy 经它走真实
|
||||
// handleControlConnection → acceptMcpCall 发起 MCP 工具调用(并行调用可同步投递)。
|
||||
// - node:os 的 homedir/tmpdir 与 process.env:全部指向本实例的临时目录。
|
||||
// - Date 与 setTimeout 系列:模块顶部插入一行 import 遮蔽全局名,Date 由受控时钟
|
||||
// 驱动(不真睡 5 分钟),定时器照常真实计时但被登记,便于检查有没有挂住退出。
|
||||
// 需要观察内部状态时只在内存副本末尾追加测试导出(Turn、allProcs),不改生产导出。
|
||||
// 运行要求:node --experimental-vm-modules。
|
||||
|
||||
import vm from "node:vm"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { EventEmitter } from "node:events"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { createRequire } from "node:module"
|
||||
import { fileURLToPath, pathToFileURL } from "node:url"
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
export const REPO_DIR = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
||||
// AGY_BRIDGE_TEST_INDEX 只用于反向验证(让同一套用例跑修复前的旧副本,确认能抓到旧缺陷)。
|
||||
export const INDEX_FILE = process.env.AGY_BRIDGE_TEST_INDEX || path.join(REPO_DIR, "index.mjs")
|
||||
export const USAGE_FILE = path.join(REPO_DIR, "usage.mjs")
|
||||
export const PLATFORM_FILE = path.join(REPO_DIR, "platform.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
|
||||
|
||||
const RUNTIME_SPECIFIER = "agy-testkit:runtime"
|
||||
const RUNTIME_NAMES = ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval", "process"]
|
||||
const RUNTIME_PRELUDE = `import { ${RUNTIME_NAMES.join(", ")} } from ${JSON.stringify(RUNTIME_SPECIFIER)};\n`
|
||||
const TEST_EXPORTS = "\nexport { Turn as __agyTestTurn, allProcs as __agyTestAllProcs, pool as __agyTestPool, " +
|
||||
"execOnce as __agyTestExecOnce, findAgy as __agyTestFindAgy, canonicalBody as __agyTestCanonicalBody, " +
|
||||
"conversationKey as __agyTestConversationKey, renderInitialPromptParts as __agyTestRenderInitialPromptParts };\n"
|
||||
const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/
|
||||
|
||||
if (typeof vm.SourceTextModule !== "function" || typeof vm.SyntheticModule !== "function") {
|
||||
// Keep the documented plain `node test_*.mjs` entry point usable too.
|
||||
const child = spawnSync(process.execPath, [...process.execArgv, "--experimental-vm-modules", ...process.argv.slice(1)], { stdio: "inherit" })
|
||||
if (child.error) throw child.error
|
||||
process.exit(child.status ?? 1)
|
||||
}
|
||||
process.setMaxListeners(Math.max(process.getMaxListeners(), 200))
|
||||
|
||||
let instanceSerial = 0
|
||||
|
||||
export const tick = () => new Promise((resolve) => setImmediate(resolve))
|
||||
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
export function modelsOutput(rows) {
|
||||
return rows.map(([id, name]) => `${id} ${name}`).join("\n") + "\n"
|
||||
}
|
||||
|
||||
// 与 index.mjs 里 FALLBACK_MODELS 同形状的 agy models 输出,外加只在动态目录里出现的型号。
|
||||
export const BASE_MODEL_ROWS = [
|
||||
["gemini-4-argon-high", "Gemini 4 Argon (High)"],
|
||||
["gemini-4-argon-medium", "Gemini 4 Argon (Medium)"],
|
||||
["gemini-4-argon-low", "Gemini 4 Argon (Low)"],
|
||||
["gemini-3.8-flash-high", "Gemini 3.8 Flash (High)"],
|
||||
["gemini-3.8-flash-low", "Gemini 3.8 Flash (Low)"],
|
||||
["claude-opus-5-5-high", "Claude Opus 5.5 (High)"],
|
||||
["claude-opus-5-5-low", "Claude Opus 5.5 (Low)"],
|
||||
["claude-sonnet-5-5-high", "Claude Sonnet 5.5 (High)"],
|
||||
["claude-sonnet-5-5-low", "Claude Sonnet 5.5 (Low)"],
|
||||
["gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"],
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------- 受控时钟与定时器
|
||||
|
||||
function createClock(start) {
|
||||
const RealDate = Date
|
||||
const state = { now: start }
|
||||
class FakeDate extends RealDate {
|
||||
constructor(...args) {
|
||||
if (args.length) super(...args)
|
||||
else super(state.now)
|
||||
}
|
||||
static now() { return state.now }
|
||||
}
|
||||
return {
|
||||
Date: FakeDate,
|
||||
now: () => state.now,
|
||||
advance(ms) { state.now += ms },
|
||||
}
|
||||
}
|
||||
|
||||
function createTimers() {
|
||||
const live = new Set()
|
||||
return {
|
||||
setTimeout(fn, ms, ...args) {
|
||||
const handle = globalThis.setTimeout((...inner) => { live.delete(handle); fn(...inner) }, ms, ...args)
|
||||
live.add(handle)
|
||||
return handle
|
||||
},
|
||||
clearTimeout(handle) {
|
||||
live.delete(handle)
|
||||
globalThis.clearTimeout(handle)
|
||||
},
|
||||
setInterval(fn, ms, ...args) {
|
||||
const handle = globalThis.setInterval(fn, ms, ...args)
|
||||
live.add(handle)
|
||||
return handle
|
||||
},
|
||||
clearInterval(handle) {
|
||||
live.delete(handle)
|
||||
globalThis.clearInterval(handle)
|
||||
},
|
||||
// 仍然持有事件循环引用、会挂住进程退出的模块定时器。
|
||||
refed() { return [...live].filter((handle) => typeof handle.hasRef !== "function" || handle.hasRef()) },
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 假子进程
|
||||
|
||||
class FakeStream extends EventEmitter {
|
||||
setEncoding() { return this }
|
||||
}
|
||||
|
||||
class FakeChild extends EventEmitter {
|
||||
constructor(kit, file, args) {
|
||||
super()
|
||||
this.kit = kit
|
||||
this.file = file
|
||||
this.args = args
|
||||
this.pid = undefined
|
||||
this.exitCode = null
|
||||
this.signalCode = null
|
||||
this.closed = false
|
||||
this.stdout = new FakeStream()
|
||||
this.stderr = new FakeStream()
|
||||
this.stdin = {
|
||||
writable: true,
|
||||
write: (chunk) => { this.onStdin?.(String(chunk)); return true },
|
||||
end: () => { this.stdin.writable = false },
|
||||
on: () => this.stdin,
|
||||
once: () => this.stdin,
|
||||
}
|
||||
kit.children.add(this)
|
||||
}
|
||||
|
||||
finish(code, signal = null) {
|
||||
if (this.closed) return
|
||||
this.closed = true
|
||||
this.exitCode = code
|
||||
this.signalCode = signal
|
||||
this.stdin.writable = false
|
||||
this.kit.children.delete(this)
|
||||
setImmediate(() => this.emit("close", code, signal))
|
||||
}
|
||||
|
||||
kill(signal = "SIGTERM") {
|
||||
this.onKill?.(signal)
|
||||
this.finish(null, signal)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
function spawnModels(kit, file, args) {
|
||||
kit.modelsSpawns.push({ file, at: kit.clock.now() })
|
||||
const raw = typeof kit.modelsBehavior === "function"
|
||||
? kit.modelsBehavior({ file, count: kit.modelsSpawns.length })
|
||||
: kit.modelsBehavior
|
||||
const behavior = raw || { hang: true }
|
||||
if (behavior.throwSync) throw Object.assign(new Error("spawn EACCES (test)"), { code: "EACCES" })
|
||||
if (behavior.brokenChild) return { stdout: null, stderr: null, on() {}, kill() {} }
|
||||
const child = new FakeChild(kit, file, args)
|
||||
const deliver = () => {
|
||||
if (child.closed) return
|
||||
if (behavior.error) {
|
||||
child.closed = true
|
||||
kit.children.delete(child)
|
||||
child.emit("error", Object.assign(new Error("spawn agy ENOENT (test)"), { code: "ENOENT" }))
|
||||
return
|
||||
}
|
||||
if (behavior.killed) {
|
||||
child.finish(null, "SIGKILL")
|
||||
return
|
||||
}
|
||||
if (behavior.stdout) child.stdout.emit("data", behavior.stdout)
|
||||
child.finish(behavior.code ?? 0)
|
||||
}
|
||||
if (!behavior.hang) {
|
||||
if (behavior.delayMs) setTimeout(deliver, behavior.delayMs)
|
||||
else setImmediate(deliver)
|
||||
}
|
||||
return child
|
||||
}
|
||||
|
||||
// 进程内的假 agy:讲 ACP JSON-RPC,工具调用经真实控制通道处理函数进入补丁。
|
||||
class FakeAgy {
|
||||
constructor(kit, child, opts) {
|
||||
this.kit = kit
|
||||
this.child = child
|
||||
this.env = opts?.env || {}
|
||||
this.token = this.env.AGY_BRIDGE_TOKEN
|
||||
this.sessionId = null
|
||||
this.buffer = ""
|
||||
this.cancelWaiters = []
|
||||
this.cancelPending = false
|
||||
child.onStdin = (chunk) => this.onStdin(chunk)
|
||||
child.onKill = () => {
|
||||
for (const waiter of this.cancelWaiters.splice(0)) waiter()
|
||||
}
|
||||
}
|
||||
|
||||
onStdin(chunk) {
|
||||
this.buffer += chunk
|
||||
for (;;) {
|
||||
const newline = this.buffer.indexOf("\n")
|
||||
if (newline < 0) return
|
||||
const line = this.buffer.slice(0, newline)
|
||||
this.buffer = this.buffer.slice(newline + 1)
|
||||
if (!line.trim()) continue
|
||||
const message = JSON.parse(line)
|
||||
if (typeof message.method === "string") this.onMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
send(message) {
|
||||
if (this.child.closed) return
|
||||
this.child.stdout.emit("data", JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n")
|
||||
}
|
||||
|
||||
respond(id, result) { this.send({ id, result }) }
|
||||
|
||||
onMessage(message) {
|
||||
const { id, method, params } = message
|
||||
this.kit.acpLog.push({ method, params, sessionId: this.sessionId })
|
||||
if (method === "initialize") {
|
||||
this.respond(id, { protocolVersion: 1, agentInfo: { name: "fake-agy", version: this.kit.agentVersion }, agentCapabilities: {} })
|
||||
} else if (method === "session/new") {
|
||||
this.sessionId = `fake-session-${++this.kit.sessionSerial}`
|
||||
this.control({ kind: "list" })
|
||||
const models = { currentModelId: this.kit.initialAgyModel }
|
||||
// What agy offers this client in the session; unset, the session names none.
|
||||
if (this.kit.offeredModels) models.availableModels = this.kit.offeredModels.map(([modelId, name]) => ({ modelId, name }))
|
||||
this.respond(id, { sessionId: this.sessionId, models })
|
||||
} else if (method === "session/set_model") {
|
||||
this.kit.setModels.push(params.modelId)
|
||||
this.respond(id, {})
|
||||
} else if (method === "session/prompt") {
|
||||
this.runPrompt(id, params)
|
||||
} else if (method === "session/cancel") {
|
||||
// 取消可能先于脚本进入等待到达,记下来,避免丢失。
|
||||
this.cancelPending = true
|
||||
for (const waiter of this.cancelWaiters.splice(0)) waiter()
|
||||
} else if (id !== undefined) {
|
||||
this.send({ id, error: { code: -32601, message: `fake agy does not serve ${method}` } })
|
||||
}
|
||||
}
|
||||
|
||||
async runPrompt(id, params) {
|
||||
const index = this.kit.promptSerial++
|
||||
this.cancelPending = false
|
||||
const handler = this.kit.prompts[index] ?? this.kit.defaultPrompt
|
||||
if (typeof handler !== "function") {
|
||||
this.send({ id, error: { code: -32603, message: `fake agy has no script for prompt #${index + 1}` } })
|
||||
return
|
||||
}
|
||||
const agent = this.agentApi(params, index)
|
||||
try {
|
||||
const result = await handler(agent)
|
||||
await tick()
|
||||
this.respond(id, result ?? { stopReason: "end_turn" })
|
||||
} catch (error) {
|
||||
this.send({ id, error: { code: -32603, message: String(error?.message ?? error) } })
|
||||
}
|
||||
}
|
||||
|
||||
update(update) {
|
||||
this.send({ method: "session/update", params: { sessionId: this.sessionId, update } })
|
||||
}
|
||||
|
||||
control(message) {
|
||||
const socket = new FakeSocket()
|
||||
this.kit.controlHandler(socket)
|
||||
socket.emit("data", JSON.stringify({ token: this.token, ...message }) + "\n")
|
||||
return socket.reply
|
||||
}
|
||||
|
||||
agentApi(params, index) {
|
||||
const self = this
|
||||
return {
|
||||
index,
|
||||
prompt: params.prompt,
|
||||
sessionId: this.sessionId,
|
||||
async text(text) { self.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); await tick() },
|
||||
async thought(text) { self.update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text } }); await tick() },
|
||||
// 同一批调用在同一个同步块里投递,等价于 agy 并行发起;返回各自的 MCP 回包。
|
||||
tools(calls) {
|
||||
const replies = calls.map(([name, args]) => self.control({ kind: "call", name, arguments: args }))
|
||||
return Promise.all(replies)
|
||||
},
|
||||
async toolsAcrossTicks(calls) {
|
||||
const replies = []
|
||||
for (const [name, args] of calls) {
|
||||
await tick()
|
||||
replies.push(self.control({ kind: "call", name, arguments: args }))
|
||||
}
|
||||
return Promise.all(replies)
|
||||
},
|
||||
async tool(name, args) { return (await this.tools([[name, args]]))[0] },
|
||||
waitCancel() {
|
||||
if (self.cancelPending) return Promise.resolve()
|
||||
return new Promise((resolve) => self.cancelWaiters.push(resolve))
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FakeSocket extends EventEmitter {
|
||||
constructor() {
|
||||
super()
|
||||
this.writable = true
|
||||
this.closed = false
|
||||
this.written = ""
|
||||
this.reply = new Promise((resolve) => { this.resolveReply = resolve })
|
||||
}
|
||||
|
||||
setEncoding() { return this }
|
||||
write(data) { this.written += data; return true }
|
||||
|
||||
end(data) {
|
||||
if (data) this.written += data
|
||||
this.writable = false
|
||||
const line = this.written.split("\n").find((item) => item.trim())
|
||||
this.resolveReply(line ? JSON.parse(line) : null)
|
||||
this.close()
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.writable = false
|
||||
this.resolveReply(null)
|
||||
this.close()
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.closed) return
|
||||
this.closed = true
|
||||
setImmediate(() => this.emit("close"))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 模块装载
|
||||
|
||||
function builtinModule(name, overrides) {
|
||||
const real = require(name)
|
||||
const exported = overrides ? { ...real, ...overrides } : real
|
||||
const names = [...new Set([...Object.keys(exported).filter((key) => IDENTIFIER_RE.test(key)), "default"])]
|
||||
return new vm.SyntheticModule(names, function init() {
|
||||
for (const key of names) this.setExport(key, key === "default" ? exported : exported[key])
|
||||
}, { identifier: `${name}?agy-testkit` })
|
||||
}
|
||||
|
||||
function sourceModule(file, extraSource, url, transform) {
|
||||
const original = fs.readFileSync(file, "utf8")
|
||||
const source = RUNTIME_PRELUDE + (transform ? transform(original) : original) + (extraSource || "")
|
||||
return new vm.SourceTextModule(source, {
|
||||
identifier: `${pathToFileURL(file).href}?agy-testkit=${++instanceSerial}`,
|
||||
initializeImportMeta(meta) { meta.url = url },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建一个隔离的补丁模块实例。每个实例有自己的模块级状态(目录缓存、进程池)、
|
||||
* 自己的临时目录、受控时钟与假 agy。用完必须 await kit.dispose()。
|
||||
*/
|
||||
export async function createBridgeKit(options = {}) {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "agy-bridge-test-"))
|
||||
const home = path.join(tmp, "home")
|
||||
const bin = path.join(tmp, "empty-bin")
|
||||
fs.mkdirSync(home, { recursive: true })
|
||||
fs.mkdirSync(bin, { recursive: true })
|
||||
const clock = createClock(options.clockStart ?? Date.UTC(2026, 10, 4, 12, 0, 0))
|
||||
const timers = createTimers()
|
||||
const kit = {
|
||||
tmp,
|
||||
home,
|
||||
clock,
|
||||
timers,
|
||||
children: new Set(),
|
||||
modelsSpawns: [],
|
||||
acpSpawns: [],
|
||||
modelsBehavior: options.modelsBehavior ?? { stdout: modelsOutput(BASE_MODEL_ROWS) },
|
||||
prompts: [],
|
||||
promptSerial: 0,
|
||||
defaultPrompt: null,
|
||||
sessionSerial: 0,
|
||||
initialAgyModel: options.initialAgyModel ?? "gemini-3.8-flash-low",
|
||||
offeredModels: options.offeredModels ?? null,
|
||||
agentVersion: options.agentVersion ?? "1.5.0",
|
||||
setModels: [],
|
||||
acpLog: [],
|
||||
controlHandler: null,
|
||||
turns: [],
|
||||
env: null,
|
||||
module: null,
|
||||
}
|
||||
kit.agyPath = makeFakeAgy(tmp, "agy-a")
|
||||
kit.makeFakeAgy = (name) => makeFakeAgy(tmp, name)
|
||||
kit.env = {
|
||||
PATH: bin,
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
LOCALAPPDATA: path.join(tmp, "localappdata"),
|
||||
XDG_STATE_HOME: path.join(tmp, "state"),
|
||||
AGY_PATH: options.agyPath === undefined ? kit.agyPath : options.agyPath,
|
||||
...(options.env || {}),
|
||||
}
|
||||
for (const [key, value] of Object.entries(kit.env)) {
|
||||
if (value === undefined || value === null) delete kit.env[key]
|
||||
}
|
||||
const fakeProcess = new Proxy(process, {
|
||||
get(target, property) {
|
||||
if (property === "env") return kit.env
|
||||
const value = Reflect.get(target, property, target)
|
||||
return typeof value === "function" ? value.bind(target) : value
|
||||
},
|
||||
})
|
||||
const spawn = (file, args = [], opts = {}) => {
|
||||
if (args[0] === "models") return spawnModels(kit, file, args)
|
||||
if (args[0] === "acp") {
|
||||
const child = new FakeChild(kit, file, args)
|
||||
kit.acpSpawns.push({ file, args, env: opts.env })
|
||||
new FakeAgy(kit, child, opts)
|
||||
return child
|
||||
}
|
||||
const child = new FakeChild(kit, file, args)
|
||||
child.finish(0)
|
||||
return child
|
||||
}
|
||||
const fakeServer = {
|
||||
once() { return fakeServer },
|
||||
on() { return fakeServer },
|
||||
listen(_port, _host, callback) { setImmediate(callback); return fakeServer },
|
||||
unref() { return fakeServer },
|
||||
close() {},
|
||||
address() { return { address: "127.0.0.1", family: "IPv4", port: 45999 } },
|
||||
}
|
||||
const overrides = {
|
||||
"node:child_process": { spawn },
|
||||
"node:net": {
|
||||
createServer(handler) {
|
||||
kit.controlHandler = handler
|
||||
return fakeServer
|
||||
},
|
||||
},
|
||||
"node:os": { homedir: () => home, tmpdir: () => tmp },
|
||||
}
|
||||
const runtime = new vm.SyntheticModule(RUNTIME_NAMES, function init() {
|
||||
this.setExport("Date", clock.Date)
|
||||
this.setExport("setTimeout", timers.setTimeout)
|
||||
this.setExport("clearTimeout", timers.clearTimeout)
|
||||
this.setExport("setInterval", timers.setInterval)
|
||||
this.setExport("clearInterval", timers.clearInterval)
|
||||
this.setExport("process", fakeProcess)
|
||||
}, { identifier: RUNTIME_SPECIFIER })
|
||||
const cache = new Map([[RUNTIME_SPECIFIER, runtime]])
|
||||
const indexUrl = pathToFileURL(path.join(REPO_DIR, "index.mjs")).href
|
||||
const usageUrl = pathToFileURL(USAGE_FILE).href
|
||||
const platformUrl = pathToFileURL(PLATFORM_FILE).href
|
||||
const linker = (specifier) => {
|
||||
const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER
|
||||
? specifier
|
||||
: `node:${specifier}`
|
||||
if (cache.has(key)) return cache.get(key)
|
||||
let module
|
||||
if (key === "./usage.mjs") module = sourceModule(USAGE_FILE, "", usageUrl)
|
||||
else if (key === "./platform.mjs") module = sourceModule(PLATFORM_FILE, "", platformUrl)
|
||||
else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])
|
||||
else throw new Error(`testkit: 未登记的依赖 ${specifier}`)
|
||||
cache.set(key, module)
|
||||
return module
|
||||
}
|
||||
const root = sourceModule(options.indexPath || INDEX_FILE, TEST_EXPORTS, indexUrl, options.indexTransform)
|
||||
await root.link(linker)
|
||||
await root.evaluate()
|
||||
const ns = root.namespace
|
||||
kit.module = ns
|
||||
// 只做观察:记下每个真实 Turn 实例,便于核对原始 ACP 累计对象,不改其行为。
|
||||
const Turn = ns.__agyTestTurn
|
||||
const originalRegister = Turn.prototype.registerResponse
|
||||
Turn.prototype.registerResponse = function registerResponseSpy(...args) {
|
||||
if (!kit.turns.includes(this)) kit.turns.push(this)
|
||||
return originalRegister.apply(this, args)
|
||||
}
|
||||
kit.plugin = await ns.AntigravityBridgePlugin()
|
||||
kit.loaded = await kit.plugin.auth.loader()
|
||||
|
||||
kit.models = () => kit.plugin.provider.models()
|
||||
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) => {
|
||||
const response = await kit.fetch(COUNT_TOKENS_URL, { method: "POST", body: JSON.stringify(body) })
|
||||
if (response.status !== 200) throw new Error(`count_tokens ${response.status}: ${await response.text()}`)
|
||||
return (await response.json()).input_tokens
|
||||
}
|
||||
kit.finishChildren = async () => {
|
||||
for (const child of [...kit.children]) child.kill("SIGKILL")
|
||||
await tick()
|
||||
await tick()
|
||||
}
|
||||
kit.dispose = async () => {
|
||||
Turn.prototype.registerResponse = originalRegister
|
||||
for (const proc of [...(ns.__agyTestAllProcs || [])]) {
|
||||
await proc.stop().catch(() => {})
|
||||
}
|
||||
await kit.finishChildren()
|
||||
fs.rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
return kit
|
||||
}
|
||||
|
||||
function makeFakeAgy(tmp, name) {
|
||||
const dir = path.join(tmp, "agy-bin", name)
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
// Windows discovery (platform.mjs agyCandidates) only considers agy.exe/.cmd/.bat;
|
||||
// the fake spawn never executes the file, so its content does not matter.
|
||||
const file = path.join(dir, process.platform === "win32" ? "agy.exe" : "agy")
|
||||
fs.writeFileSync(file, "#!/bin/sh\nexit 99\n", { mode: 0o755 })
|
||||
return file
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 客户端侧
|
||||
|
||||
/** 解析一次 SSE 响应:内容块、最终 usage、stop_reason 与原始事件。 */
|
||||
export async function readSse(response) {
|
||||
if (response.status !== 200) throw new Error(`HTTP ${response.status}: ${await response.text()}`)
|
||||
const text = await response.text()
|
||||
const events = []
|
||||
for (const frame of text.split("\n\n")) {
|
||||
if (!frame.trim()) continue
|
||||
let event = ""
|
||||
let data = ""
|
||||
for (const line of frame.split("\n")) {
|
||||
if (line.startsWith("event:")) event = line.slice(6).trim()
|
||||
else if (line.startsWith("data:")) data += line.slice(5).trim()
|
||||
}
|
||||
if (data) events.push({ event, data: JSON.parse(data) })
|
||||
}
|
||||
const blocks = new Map()
|
||||
const content = []
|
||||
let usage = null
|
||||
let stopReason = null
|
||||
let model = null
|
||||
let error = null
|
||||
for (const { event, data } of events) {
|
||||
if (event === "message_start") model = data.message?.model ?? null
|
||||
else if (event === "content_block_start") blocks.set(data.index, { ...data.content_block, json: "" })
|
||||
else if (event === "content_block_delta") {
|
||||
const block = blocks.get(data.index)
|
||||
if (data.delta.type === "text_delta") block.text += data.delta.text
|
||||
else if (data.delta.type === "thinking_delta") block.thinking += data.delta.thinking
|
||||
else if (data.delta.type === "signature_delta") block.signature = data.delta.signature
|
||||
else if (data.delta.type === "input_json_delta") block.json += data.delta.partial_json
|
||||
} 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) : {}
|
||||
delete block.json
|
||||
content.push(block)
|
||||
} else if (event === "message_delta") {
|
||||
usage = data.usage ?? null
|
||||
stopReason = data.delta?.stop_reason ?? null
|
||||
} else if (event === "error") {
|
||||
error = data.error
|
||||
}
|
||||
}
|
||||
return { events, content, usage, stopReason, model, error }
|
||||
}
|
||||
|
||||
/** stream:false 的 JSON 响应,整理成与 readSse 相同的形状。 */
|
||||
export async function readJson(response) {
|
||||
if (response.status !== 200) throw new Error(`HTTP ${response.status}: ${await response.text()}`)
|
||||
const message = await response.json()
|
||||
return { content: message.content, usage: message.usage, stopReason: message.stop_reason, model: message.model, error: null }
|
||||
}
|
||||
|
||||
export function usageTotal(usage) {
|
||||
return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
|
||||
}
|
||||
|
||||
/** 把一次响应接成下一轮请求:追加 assistant 原样内容与对应的 tool_result。 */
|
||||
export function continueWithToolResults(body, parsed, resultFor = (block, index) => `result ${index} for ${block.name}`) {
|
||||
const toolUses = parsed.content.filter((block) => block.type === "tool_use")
|
||||
const assistant = parsed.content.map((block) => block.type === "tool_use"
|
||||
? { type: "tool_use", id: block.id, name: block.name, input: block.input }
|
||||
: block.type === "thinking"
|
||||
? { type: "thinking", thinking: block.thinking, signature: block.signature }
|
||||
: { type: "text", text: block.text })
|
||||
return {
|
||||
...body,
|
||||
messages: [
|
||||
...body.messages,
|
||||
{ role: "assistant", content: assistant },
|
||||
{
|
||||
role: "user",
|
||||
content: toolUses.map((block, index) => ({
|
||||
type: "tool_result",
|
||||
tool_use_id: block.id,
|
||||
content: resultFor(block, index),
|
||||
})),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export const READ_TOOL = {
|
||||
name: "Read",
|
||||
description: "Read a file from the local filesystem.",
|
||||
input_schema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] },
|
||||
}
|
||||
|
||||
export function baseBody(overrides = {}) {
|
||||
return {
|
||||
model: "agy-cli/gemini-4-argon[1m]",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: "start the task" }],
|
||||
tools: [READ_TOOL],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** 调整 system 长度,使真实 estimateInputTokens(body)(经 count_tokens 入口)等于目标值。 */
|
||||
export async function padBodyToTokens(kit, body, target) {
|
||||
const base = await kit.countTokens({ ...body, system: "" })
|
||||
if (base >= target) throw new Error(`夹具基础体积 ${base} 已超过目标 ${target}`)
|
||||
const unit = "context padding line for the agy bridge usage fixture. "
|
||||
const needed = (target - base) * 4
|
||||
const system = unit.repeat(Math.ceil(needed / unit.length)).slice(0, needed)
|
||||
const padded = { ...body, system }
|
||||
const actual = await kit.countTokens(padded)
|
||||
if (actual !== target) throw new Error(`夹具估算 ${actual} 未命中目标 ${target}`)
|
||||
return padded
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
// magpie-agy 单次窗口 usage 回归(源自 configs 仓 test_agy_bridge_usage.mjs,去掉依赖 OCX 源码的交叉验证):
|
||||
// ACP 一次 session/prompt 的多步累计用量不能被当成单条 /v1/messages 的窗口占用(4,775,934 → 4.8m 跳变)。
|
||||
// 用 OCX 真实预算判据交叉验证「不误报超阈」的用例留在 configs 仓,那里有 OCX 源码。
|
||||
//
|
||||
// 运行:node --experimental-vm-modules --test test-usage-settlement.mjs
|
||||
// 全部经真实仓内 index.mjs 的 fetch → Proc → ACP → 流生成/消费路径,假 agy 见 testkit.mjs。
|
||||
// 口径(主控已拍板):单步精确透传;多步为有界估算,原始 ACP 累计对象原样保留,
|
||||
// 不承诺各响应 usage 求和精确等于上游累计(下面专门有数值反例)。
|
||||
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import {
|
||||
baseBody, continueWithToolResults, createBridgeKit, padBodyToTokens, readJson, readSse, sleep,
|
||||
usageTotal,
|
||||
} from "./testkit.mjs"
|
||||
|
||||
const FIXTURE_ESTIMATE = 198_654
|
||||
const FIXTURE_RAW = Object.freeze({
|
||||
inputTokens: 4_775_934, cachedReadTokens: 4_775_934, cachedWriteTokens: 0, outputTokens: 60_000, thoughtTokens: 1_234,
|
||||
})
|
||||
|
||||
async function withKit(options, fn) {
|
||||
const kit = await createBridgeKit(options)
|
||||
try {
|
||||
return await fn(kit)
|
||||
} finally {
|
||||
await kit.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
const plain = (value) => JSON.parse(JSON.stringify(value))
|
||||
|
||||
function assertCleanUsage(usage, label) {
|
||||
for (const key of ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]) {
|
||||
assert.ok(Number.isSafeInteger(usage?.[key]) && usage[key] >= 0, `${label}: ${key}=${usage?.[key]} 不是非负有限整数`)
|
||||
}
|
||||
const thinking = usage.output_tokens_details?.thinking_tokens
|
||||
if (thinking !== undefined) {
|
||||
assert.ok(Number.isSafeInteger(thinking) && thinking >= 0, `${label}: thinking_tokens=${thinking}`)
|
||||
assert.ok(thinking <= usage.output_tokens, `${label}: thinking ${thinking} 超过 output ${usage.output_tokens}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 驱动一整轮:遇到 tool_use 就把 tool_result 接回去,直到收尾。返回每次 HTTP 的估算与解析结果。 */
|
||||
async function runTurn(kit, body, { stream = true, resultFor } = {}) {
|
||||
const responses = []
|
||||
const estimates = []
|
||||
const bodies = []
|
||||
let current = stream ? body : { ...body, stream: false }
|
||||
for (let guard = 0; guard < 64; guard++) {
|
||||
bodies.push(current)
|
||||
estimates.push(await kit.countTokens(current))
|
||||
const response = await kit.request(current)
|
||||
const parsed = stream ? await readSse(response) : await readJson(response)
|
||||
assert.equal(parsed.error, null, JSON.stringify(parsed.error))
|
||||
responses.push(parsed)
|
||||
if (parsed.stopReason !== "tool_use") return { responses, estimates, bodies }
|
||||
current = continueWithToolResults(current, parsed, resultFor)
|
||||
}
|
||||
throw new Error("工具回合超过 64 次仍未收尾")
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------- 单步
|
||||
|
||||
test("单步回合精确透传 ACP usage 并原样保留原始对象", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const raw = { inputTokens: 1000, cachedReadTokens: 400, cachedWriteTokens: 50, outputTokens: 30, thoughtTokens: 5 }
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.thought("considering")
|
||||
await agent.text("single step answer")
|
||||
return { stopReason: "end_turn", usage: raw }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
assert.equal(responses.length, 1)
|
||||
assert.deepEqual(plain(responses[0].usage), {
|
||||
input_tokens: 600, output_tokens: 35, cache_read_input_tokens: 400, cache_creation_input_tokens: 50,
|
||||
output_tokens_details: { thinking_tokens: 5 },
|
||||
})
|
||||
const start = responses[0].events.find((item) => item.event === "message_start")
|
||||
assert.deepEqual(plain(start.data.message.usage), { input_tokens: 0, output_tokens: 0 })
|
||||
const [turn] = kit.turns
|
||||
assert.deepEqual(plain(turn.rawUsage), raw)
|
||||
assert.equal(turn.rawAcpUsages.length, 1)
|
||||
})
|
||||
})
|
||||
|
||||
// ------------------------------------------------------------------ 25 步固定案例
|
||||
|
||||
test("25 步/74 工具/累计 4,775,934:各步窗口有界、原始累计保留、求和不守恒反例", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const rounds = Array.from({ length: 24 }, (_unused, index) => (index < 22 ? 3 : 4))
|
||||
assert.equal(rounds.reduce((sum, value) => sum + value, 0), 74)
|
||||
let agentSawResults = 0
|
||||
kit.prompts.push(async (agent) => {
|
||||
for (const [round, count] of rounds.entries()) {
|
||||
const replies = await agent.tools(Array.from({ length: count }, (_unused, index) => ["Read", { path: `/repo/src/module-${round}-${index}.ts` }]))
|
||||
agentSawResults += replies.filter((reply) => reply?.result).length
|
||||
}
|
||||
await agent.thought("All modules inspected; summarizing.")
|
||||
await agent.text("Task complete after inspecting 74 files.")
|
||||
return { stopReason: "end_turn", usage: { ...FIXTURE_RAW } }
|
||||
})
|
||||
const body = await padBodyToTokens(kit, baseBody(), FIXTURE_ESTIMATE)
|
||||
const { responses, estimates } = await runTurn(kit, body)
|
||||
|
||||
assert.equal(responses.length, 25, "应为 24 个工具响应 + 1 个收尾响应")
|
||||
assert.equal(agentSawResults, 74)
|
||||
assert.equal(estimates[0], FIXTURE_ESTIMATE)
|
||||
for (const estimate of estimates) {
|
||||
assert.ok(estimate >= FIXTURE_ESTIMATE && estimate < FIXTURE_ESTIMATE * 1.05, `估算 ${estimate} 偏离夹具量级`)
|
||||
}
|
||||
const toolResponses = responses.slice(0, 24)
|
||||
const final = responses[24]
|
||||
for (const [index, parsed] of toolResponses.entries()) {
|
||||
const label = `工具响应 #${index + 1}`
|
||||
assert.equal(parsed.stopReason, "tool_use")
|
||||
assert.equal(parsed.content.filter((block) => block.type === "tool_use").length, rounds[index], `${label} 并行调用没有合并`)
|
||||
assert.equal(parsed.events.filter((item) => item.event === "message_delta").length, 1)
|
||||
assertCleanUsage(parsed.usage, label)
|
||||
const total = usageTotal(parsed.usage)
|
||||
assert.ok(total > 0, `${label} 窗口读数为 0(旧缺陷:中间工具步恒报 0)`)
|
||||
assert.ok(total <= Math.round(estimates[index] * 1.5), `${label} ${total} 超过 1.5 倍估算`)
|
||||
assert.ok(parsed.usage.output_tokens >= 1, `${label} output_tokens 为 0`)
|
||||
}
|
||||
assert.equal(final.stopReason, "end_turn")
|
||||
assertCleanUsage(final.usage, "收尾响应")
|
||||
const finalTotal = usageTotal(final.usage)
|
||||
assert.notEqual(finalTotal, FIXTURE_RAW.inputTokens, "收尾响应仍在吐整轮累计(4.8m 跳变)")
|
||||
assert.ok(finalTotal <= Math.round(estimates[24] * 1.5), `收尾 ${finalTotal} 超过 1.5 倍估算 ${estimates[24]}`)
|
||||
assert.ok(finalTotal > 150_000 && finalTotal < 300_000, `收尾窗口 ${finalTotal} 不在约 198k 的量级`)
|
||||
assert.ok(final.usage.cache_read_input_tokens >= finalTotal - 1, "本轮全部命中读缓存,拆分应保持该占比")
|
||||
assert.ok(final.usage.output_tokens >= 1)
|
||||
|
||||
// 原始 ACP 累计对象原样保留、只计一次。
|
||||
const [turn] = kit.turns
|
||||
assert.equal(kit.turns.length, 1)
|
||||
assert.deepEqual(plain(turn.rawUsage), { ...FIXTURE_RAW })
|
||||
assert.equal(turn.rawAcpUsages.length, 1)
|
||||
|
||||
// 守恒反例:一般多步估算的求和不等于上游累计,也不能把残差塞回末步。
|
||||
const fixtureSum24 = 24 * FIXTURE_ESTIMATE
|
||||
assert.equal(fixtureSum24, 4_767_696)
|
||||
const fixtureLast = Math.round(FIXTURE_RAW.inputTokens / 25)
|
||||
assert.equal(fixtureLast, 191_037)
|
||||
assert.notEqual(fixtureSum24 + fixtureLast, FIXTURE_RAW.inputTokens)
|
||||
const reportedSum = responses.reduce((sum, parsed) => sum + usageTotal(parsed.usage), 0)
|
||||
const residual = FIXTURE_RAW.inputTokens - toolResponses.reduce((sum, parsed) => sum + usageTotal(parsed.usage), 0)
|
||||
assert.notEqual(reportedSum, FIXTURE_RAW.inputTokens, "估算求和恰好守恒,与口径假设不符,需重新核对夹具")
|
||||
assert.notEqual(finalTotal, residual, "末步被用累计残差补平,不是单次窗口")
|
||||
const errorRatio = (reportedSum - FIXTURE_RAW.inputTokens) / FIXTURE_RAW.inputTokens
|
||||
assert.ok(Math.abs(errorRatio) < 0.1, `估算总误差 ${(errorRatio * 100).toFixed(2)}% 超出量级`)
|
||||
console.log(`# 25 步估算求和 ${reportedSum},上游累计 ${FIXTURE_RAW.inputTokens},误差 ${(errorRatio * 100).toFixed(2)}%(不承诺守恒)`)
|
||||
|
||||
})
|
||||
})
|
||||
|
||||
// -------------------------------------------------------------------- 写缓存上限
|
||||
|
||||
test("末步输入三字段之和(含写缓存)受 1.5 倍估算上限约束", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.tool("Read", { path: "/a" })
|
||||
await agent.tool("Read", { path: "/b" })
|
||||
await agent.text("done")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 900_000, cachedReadTokens: 100_000, cachedWriteTokens: 5_000_000, outputTokens: 10 } }
|
||||
})
|
||||
const body = await padBodyToTokens(kit, baseBody(), 20_000)
|
||||
const { responses, estimates } = await runTurn(kit, body)
|
||||
const final = responses.at(-1)
|
||||
assertCleanUsage(final.usage, "收尾响应")
|
||||
const cap = Math.round(estimates.at(-1) * 1.5)
|
||||
assert.ok(usageTotal(final.usage) <= cap, `含写缓存的窗口 ${usageTotal(final.usage)} 超过上限 ${cap}`)
|
||||
assert.ok(final.usage.cache_creation_input_tokens > 0, "写缓存被整体丢弃,没有计入窗口")
|
||||
assert.ok(final.usage.cache_creation_input_tokens <= cap)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------- 输出口径与合并
|
||||
|
||||
test("输出估算覆盖 text、thinking 与 tool_use JSON", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const longText = "Reasoned answer sentence. ".repeat(40)
|
||||
const longThought = "Thinking about which file to read next. ".repeat(40)
|
||||
const hugePath = `/repo/${"deep/".repeat(800)}file.ts`
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.thought(longThought)
|
||||
await agent.text(longText)
|
||||
await agent.tool("Read", { path: "/small" })
|
||||
await agent.tool("Read", { path: hugePath })
|
||||
await agent.tool("Read", { path: "/small2" })
|
||||
await agent.text("done")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 3000, outputTokens: 20 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
const [withProse, withHugeArgs, bare] = responses
|
||||
for (const parsed of responses) assertCleanUsage(parsed.usage, "响应")
|
||||
assert.ok(withProse.content.some((block) => block.type === "thinking"))
|
||||
assert.ok(withProse.usage.output_tokens_details?.thinking_tokens > 0, "转发的 thinking 没计入输出")
|
||||
assert.ok(withProse.usage.output_tokens > bare.usage.output_tokens + 400, "text/thinking 没计入输出估算")
|
||||
assert.ok(withHugeArgs.usage.output_tokens > bare.usage.output_tokens + 800, "tool_use JSON 没计入输出估算")
|
||||
assert.ok(!(bare.usage.output_tokens_details?.thinking_tokens > 0))
|
||||
})
|
||||
})
|
||||
|
||||
test("并行工具调用合并为一次响应,只结算一次", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
let replies = null
|
||||
kit.prompts.push(async (agent) => {
|
||||
replies = await agent.tools([["Read", { path: "/x" }], ["Read", { path: "/y" }], ["Read", { path: "/z" }]])
|
||||
await agent.text("merged")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 5000, cachedReadTokens: 1000, outputTokens: 40 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody(), { resultFor: (block) => `content of ${block.input.path}` })
|
||||
assert.equal(responses.length, 2)
|
||||
const [merged] = responses
|
||||
assert.deepEqual(merged.content.filter((block) => block.type === "tool_use").map((block) => block.input.path), ["/x", "/y", "/z"])
|
||||
assert.equal(merged.events.filter((item) => item.event === "message_delta").length, 1)
|
||||
assert.deepEqual(replies.map((reply) => reply.result.content?.[0]?.text ?? JSON.stringify(reply.result)),
|
||||
["content of /x", "content of /y", "content of /z"])
|
||||
const [turn] = kit.turns
|
||||
assert.equal(turn.responseSteps.length, 2)
|
||||
assert.equal(turn.emittedOutputTokens, merged.usage.output_tokens + responses[1].usage.output_tokens)
|
||||
})
|
||||
})
|
||||
|
||||
test("跨事件循环的 13 个并行 MCP 调用合并:旧版 14 次 HTTP,新版 2 次", async () => {
|
||||
const observe = async (legacy, stream) => withKit({
|
||||
...(legacy ? { indexTransform: (source) => {
|
||||
const pattern = / const emittedIds = new Set\(\[event.call.id\]\)[\s\S]*?(?= stopMessage\("tool_use")/
|
||||
assert.match(source, pattern, "旧版对照必须只恢复原来的即时队列排空逻辑")
|
||||
return source.replace(pattern, ' while (turn.events[0]?.type === "tool") emitToolUse(turn.events.shift().call)\n')
|
||||
} } : {}),
|
||||
}, async (kit) => {
|
||||
let replies
|
||||
kit.prompts.push(async (agent) => {
|
||||
replies = await agent.toolsAcrossTicks(Array.from({ length: 13 }, (_, i) => ["Read", { path: `/parallel-${i}` }]))
|
||||
await agent.text("all thirteen finished")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 900_000, cachedReadTokens: 600_000, outputTokens: 90 } }
|
||||
})
|
||||
const { responses, estimates } = await runTurn(kit, baseBody(), { stream })
|
||||
assert.equal(replies.length, 13)
|
||||
for (const [i, response] of responses.entries()) {
|
||||
assertCleanUsage(response.usage, `batch step ${i}`)
|
||||
assert.ok(usageTotal(response.usage) <= Math.round(estimates[i] * 1.5), "累计用量不能作为本次窗口")
|
||||
}
|
||||
return { requests: responses.length, tools: responses.map((response) => response.content.filter((b) => b.type === "tool_use").length) }
|
||||
})
|
||||
const before = await observe(true, true)
|
||||
assert.equal(before.requests, 14)
|
||||
assert.deepEqual(before.tools.slice(0, 13), Array(13).fill(1))
|
||||
for (const stream of [true, false]) {
|
||||
const after = await observe(false, stream)
|
||||
assert.equal(after.requests, 2)
|
||||
assert.deepEqual(after.tools, [13, 0])
|
||||
console.log(`# cross-tick stream=${stream}: HTTP ${before.requests} -> ${after.requests}; tool_use ${before.tools.slice(0, 13).join('+')} -> 13`)
|
||||
}
|
||||
})
|
||||
|
||||
test("晚到工具超过微批上限后单独响应,同参数的独立调用不去重", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
const first = agent.tool("Read", { path: "/same" })
|
||||
await sleep(70)
|
||||
const second = agent.tool("Read", { path: "/same" })
|
||||
await Promise.all([first, second])
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 5000, outputTokens: 10 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
assert.equal(responses.length, 3)
|
||||
const calls = responses.flatMap((r) => r.content.filter((b) => b.type === "tool_use"))
|
||||
assert.equal(calls.length, 2)
|
||||
assert.notEqual(calls[0].id, calls[1].id)
|
||||
assert.equal(kit.turns[0].waiters.length, 0)
|
||||
})
|
||||
})
|
||||
|
||||
test("文本插入立即截断微批并保留文本及后续工具的顺序", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
const first = agent.tool("Read", { path: "/first" })
|
||||
await agent.text("between calls")
|
||||
const second = agent.tool("Read", { path: "/second" })
|
||||
await Promise.all([first, second])
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 4000, outputTokens: 10 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
assert.equal(responses.length, 3)
|
||||
assert.deepEqual(responses[0].content.map((b) => b.type), ["tool_use"])
|
||||
assert.deepEqual(responses[1].content.map((b) => b.type), ["text", "tool_use"])
|
||||
assert.equal(responses[1].content[0].text, "between calls")
|
||||
})
|
||||
})
|
||||
|
||||
test("微批等待可取消,不遗留等待者或计时器", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.tool("Read", { path: "/cancel-batch" })
|
||||
return { stopReason: "end_turn" }
|
||||
})
|
||||
const controller = new AbortController()
|
||||
const response = await kit.request(baseBody(), { signal: controller.signal })
|
||||
const reader = response.body.getReader()
|
||||
let text = ""
|
||||
while (!text.includes('"type":"tool_use"')) {
|
||||
const part = await reader.read()
|
||||
assert.equal(part.done, false)
|
||||
text += new TextDecoder().decode(part.value)
|
||||
}
|
||||
const turn = kit.turns[0]
|
||||
controller.abort()
|
||||
await assert.rejects(reader.read())
|
||||
assert.equal(turn.waiters.length, 0)
|
||||
assert.equal(turn.responseSteps[0].settled, false)
|
||||
})
|
||||
})
|
||||
|
||||
test("turn 完成事件截断微批,收尾事件仍由下一响应消费", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
// ACP can end a prompt before a client returns its outstanding result.
|
||||
agent.tool("Read", { path: "/last" })
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 8000, outputTokens: 10 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
assert.equal(responses.length, 2)
|
||||
assert.equal(responses[0].stopReason, "tool_use")
|
||||
assert.equal(responses[1].stopReason, "end_turn")
|
||||
assert.equal(kit.turns[0].waiters.length, 0)
|
||||
assert.equal(kit.turns[0].finalized, true)
|
||||
})
|
||||
})
|
||||
|
||||
test("同一工具事件重复送达只发一个 tool_use,MCP 仍接收一次结果", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const prototype = kit.module.__agyTestTurn.prototype
|
||||
const push = prototype.push
|
||||
prototype.push = function (event) {
|
||||
push.call(this, event)
|
||||
if (event.type === "tool") push.call(this, event)
|
||||
}
|
||||
try {
|
||||
let reply
|
||||
kit.prompts.push(async (agent) => {
|
||||
reply = await agent.tool("Read", { path: "/duplicate-event" })
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 8000, outputTokens: 10 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
assert.equal(responses.length, 2)
|
||||
assert.equal(responses[0].content.filter((block) => block.type === "tool_use").length, 1)
|
||||
assert.ok(reply.result)
|
||||
assert.equal(kit.turns[0].calls.length, 1)
|
||||
} finally {
|
||||
prototype.push = push
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------- late 续发
|
||||
|
||||
test("late 工具结果触发同一响应内第二次 prompt:两次 ACP usage 各计一次,窗口有界", async () => {
|
||||
await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "40" } }, async (kit) => {
|
||||
const u1 = { inputTokens: 50_000, cachedReadTokens: 10_000, cachedWriteTokens: 300, outputTokens: 100 }
|
||||
const u2 = { inputTokens: 60_000, cachedReadTokens: 30_000, cachedWriteTokens: 200, outputTokens: 50, thoughtTokens: 7 }
|
||||
let firstPromptDone = false
|
||||
let deferredReply = null
|
||||
let latePromptText = ""
|
||||
kit.prompts.push(async (agent) => {
|
||||
deferredReply = await agent.tool("Read", { path: "/slow" })
|
||||
firstPromptDone = true
|
||||
return { stopReason: "end_turn", usage: u1 }
|
||||
})
|
||||
kit.prompts.push(async (agent) => {
|
||||
latePromptText = JSON.stringify(agent.prompt)
|
||||
await agent.text("final answer after the late result")
|
||||
return { stopReason: "end_turn", usage: u2 }
|
||||
})
|
||||
const body = baseBody()
|
||||
const first = await readSse(await kit.request(body))
|
||||
assert.equal(first.stopReason, "tool_use")
|
||||
for (let i = 0; i < 200 && !firstPromptDone; i++) await sleep(5)
|
||||
assert.ok(firstPromptDone, "工具调用没有被延期,late 路径未触发")
|
||||
assert.match(JSON.stringify(deferredReply), /still running|running/i)
|
||||
await sleep(20)
|
||||
const next = continueWithToolResults(body, first, () => "LATE-RESULT-PAYLOAD")
|
||||
const final = await readSse(await kit.request(next))
|
||||
assert.equal(final.stopReason, "end_turn")
|
||||
assert.match(latePromptText, /LATE-RESULT-PAYLOAD/)
|
||||
const sessionPrompts = kit.acpLog.filter((item) => item.method === "session/prompt")
|
||||
assert.equal(sessionPrompts.length, 2)
|
||||
assert.equal(new Set(sessionPrompts.map((item) => item.params.sessionId)).size, 1)
|
||||
|
||||
const [turn] = kit.turns
|
||||
assert.equal(turn.promptCount, 2)
|
||||
assert.equal(turn.rawAcpUsages.length, 2)
|
||||
assert.deepEqual(plain(turn.rawUsage), {
|
||||
inputTokens: 110_000, cachedReadTokens: 40_000, cachedWriteTokens: 500, outputTokens: 150, thoughtTokens: 7,
|
||||
})
|
||||
for (const parsed of [first, final]) assertCleanUsage(parsed.usage, "late 回合响应")
|
||||
assert.ok(usageTotal(first.usage) > 0)
|
||||
const step = turn.responseSteps.at(-1)
|
||||
const estimate = turn.stepInputEstimates[step.estimateIndex]
|
||||
assert.ok(usageTotal(final.usage) <= Math.round(estimate * 1.5), `late 收尾 ${usageTotal(final.usage)} 超过 1.5 倍估算 ${estimate}`)
|
||||
assert.ok(usageTotal(final.usage) < 110_000, "late 收尾吐了两次 prompt 的累计")
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------- 异常与缺失字段
|
||||
|
||||
test("缺失、非数值、无穷、负数 usage 字段被清理成非负有限整数", async () => {
|
||||
const garbage = [
|
||||
undefined,
|
||||
null,
|
||||
{ inputTokens: "abc", cachedReadTokens: -5, cachedWriteTokens: "Infinity", outputTokens: "NaN", thoughtTokens: -1 },
|
||||
{ inputTokens: -100, cachedReadTokens: 999, cachedWriteTokens: null, outputTokens: {}, thoughtTokens: [] },
|
||||
{ inputTokens: "1e400", cachedReadTokens: "-Infinity", outputTokens: 12.7 },
|
||||
]
|
||||
for (const usage of garbage) {
|
||||
for (const multiStep of [false, true]) {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
if (multiStep) await agent.tool("Read", { path: "/f" })
|
||||
await agent.text("answer")
|
||||
return usage === undefined ? { stopReason: "end_turn" } : { stopReason: "end_turn", usage }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
assert.equal(responses.length, multiStep ? 2 : 1)
|
||||
for (const parsed of responses) assertCleanUsage(parsed.usage, `usage=${JSON.stringify(usage)} multi=${multiStep}`)
|
||||
if (multiStep) assert.ok(usageTotal(responses[0].usage) > 0, "工具步读数为 0")
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// ------------------------------------------------------------------ 取消与重试
|
||||
|
||||
test("取消后重试:被取消回合的 usage 不并入重试响应", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const cancelled = { inputTokens: 777_777, cachedReadTokens: 0, outputTokens: 3 }
|
||||
const retry = { inputTokens: 1200, cachedReadTokens: 200, outputTokens: 7 }
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.text("partial answer")
|
||||
await agent.waitCancel()
|
||||
return { stopReason: "cancelled", usage: cancelled }
|
||||
})
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.text("complete answer")
|
||||
return { stopReason: "end_turn", usage: retry }
|
||||
})
|
||||
const body = baseBody({ tools: [] })
|
||||
const controller = new AbortController()
|
||||
const response = await kit.request(body, { signal: controller.signal })
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let seen = ""
|
||||
while (!seen.includes("text_delta")) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
seen += decoder.decode(value, { stream: true })
|
||||
}
|
||||
controller.abort()
|
||||
await reader.read().then(() => {}, () => {})
|
||||
for (let i = 0; i < 200 && !kit.turns[0]?.finalized; i++) await sleep(5)
|
||||
assert.ok(kit.acpLog.some((item) => item.method === "session/cancel"), "取消没有通知 agy")
|
||||
assert.ok(kit.turns[0].finalized)
|
||||
|
||||
const { responses } = await runTurn(kit, body)
|
||||
assert.deepEqual(plain(responses[0].usage), {
|
||||
input_tokens: 1000, output_tokens: 7, cache_read_input_tokens: 200, cache_creation_input_tokens: 0,
|
||||
})
|
||||
assert.equal(kit.turns.length, 2)
|
||||
assert.deepEqual(plain(kit.turns[0].rawUsage), cancelled)
|
||||
assert.deepEqual(plain(kit.turns[1].rawUsage), retry)
|
||||
assert.equal(kit.turns[1].rawAcpUsages.length, 1)
|
||||
})
|
||||
})
|
||||
|
||||
test("同一 HTTP 步骤不会被重复结算", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.tool("Read", { path: "/once" })
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 4000, outputTokens: 9 } }
|
||||
})
|
||||
const { responses } = await runTurn(kit, baseBody())
|
||||
const [turn] = kit.turns
|
||||
const emitted = responses.reduce((sum, parsed) => sum + parsed.usage.output_tokens, 0)
|
||||
assert.equal(turn.emittedOutputTokens, emitted)
|
||||
const step = turn.responseSteps[0]
|
||||
const before = plain(step.usage)
|
||||
turn.recordResponseUsage(step, { input_tokens: 9, cache_read_input_tokens: 9, cache_creation_input_tokens: 9, output_tokens: 999 }, false)
|
||||
assert.deepEqual(plain(step.usage), before)
|
||||
assert.equal(turn.emittedOutputTokens, emitted)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------- 校准与 Proc 隔离
|
||||
|
||||
test("单步校准系数与缓存占比只在同一 Proc 内沿用,不同 Proc 互不影响", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const base = await padBodyToTokens(kit, baseBody({ messages: [{ role: "user", content: "conversation A" }] }), 4000)
|
||||
const estimateA1 = await kit.countTokens(base)
|
||||
const calibrated = Math.round(estimateA1 * 1.2)
|
||||
const cachedA = Math.round(calibrated * 0.25)
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.text("A first answer")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: calibrated, cachedReadTokens: cachedA, outputTokens: 5 } }
|
||||
})
|
||||
const first = await runTurn(kit, base)
|
||||
assert.equal(usageTotal(first.responses[0].usage), calibrated)
|
||||
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.tool("Read", { path: "/a" })
|
||||
await agent.text("A second answer")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 9000, outputTokens: 5 } }
|
||||
})
|
||||
const followUp = {
|
||||
...base,
|
||||
messages: [...base.messages, { role: "assistant", content: plain(first.responses[0].content) }, { role: "user", content: "next question" }],
|
||||
}
|
||||
const second = await runTurn(kit, followUp)
|
||||
assert.equal(kit.acpSpawns.length, 1, "同一会话没有复用 Proc,校准沿用无从验证")
|
||||
const toolStep = second.responses[0].usage
|
||||
const expectedTotal = second.estimates[0] * 1.2
|
||||
assert.ok(Math.abs(usageTotal(toolStep) - expectedTotal) <= 2, `同 Proc 工具步 ${usageTotal(toolStep)},期望约 ${expectedTotal}`)
|
||||
assert.ok(Math.abs(toolStep.cache_read_input_tokens - usageTotal(toolStep) * 0.25) <= 2, "缓存占比没有沿用")
|
||||
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.tool("Read", { path: "/b" })
|
||||
await agent.text("B answer")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 9000, outputTokens: 5 } }
|
||||
})
|
||||
const other = await padBodyToTokens(kit, baseBody({ messages: [{ role: "user", content: "conversation B" }] }), 4000)
|
||||
const third = await runTurn(kit, other)
|
||||
assert.equal(kit.acpSpawns.length, 2, "不同会话应使用不同 Proc")
|
||||
const isolated = third.responses[0].usage
|
||||
assert.ok(Math.abs(usageTotal(isolated) - third.estimates[0]) <= 1, `跨 Proc 工具步 ${usageTotal(isolated)} 带上了别的会话的系数`)
|
||||
assert.equal(isolated.cache_read_input_tokens, 0)
|
||||
})
|
||||
})
|
||||
|
||||
test("校准系数被夹在 [0.5, 1.5]", async () => {
|
||||
for (const [factor, clamped] of [[3, 1.5], [0.1, 0.5]]) {
|
||||
await withKit({}, async (kit) => {
|
||||
const base = await padBodyToTokens(kit, baseBody({ messages: [{ role: "user", content: `clamp ${factor}` }] }), 4000)
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.text("first")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: Math.round(4000 * factor), outputTokens: 1 } }
|
||||
})
|
||||
const first = await runTurn(kit, base)
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.tool("Read", { path: "/c" })
|
||||
await agent.text("second")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 100, outputTokens: 1 } }
|
||||
})
|
||||
const followUp = {
|
||||
...base,
|
||||
messages: [...base.messages, { role: "assistant", content: plain(first.responses[0].content) }, { role: "user", content: "again" }],
|
||||
}
|
||||
const second = await runTurn(kit, followUp)
|
||||
const total = usageTotal(second.responses[0].usage)
|
||||
assert.ok(Math.abs(total - second.estimates[0] * clamped) <= 2, `系数 ${factor} 应夹到 ${clamped},实际 ${total / second.estimates[0]}`)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// ------------------------------------------------------------ SSE 与 JSON 一致性
|
||||
|
||||
test("SSE 与 stream:false 经同一流生成/消费路径得到相同内容与 usage", async () => {
|
||||
const scenario = (kit) => {
|
||||
kit.prompts.push(async (agent) => {
|
||||
await agent.thought("plan the read")
|
||||
await agent.text("Reading the file now.")
|
||||
await agent.tools([["Read", { path: "/p1" }], ["Read", { path: "/p2" }]])
|
||||
await agent.thought("summarize")
|
||||
await agent.text("Both files read.")
|
||||
return { stopReason: "end_turn", usage: { inputTokens: 40_000, cachedReadTokens: 30_000, cachedWriteTokens: 1000, outputTokens: 300, thoughtTokens: 20 } }
|
||||
})
|
||||
}
|
||||
const normalize = (responses) => responses.map((parsed) => {
|
||||
const ids = new Map()
|
||||
return {
|
||||
stopReason: parsed.stopReason,
|
||||
model: parsed.model,
|
||||
usage: plain(parsed.usage),
|
||||
content: parsed.content.map((block) => {
|
||||
if (block.type === "tool_use") {
|
||||
if (!ids.has(block.id)) ids.set(block.id, `tool-${ids.size}`)
|
||||
return { type: "tool_use", id: ids.get(block.id), name: block.name, input: plain(block.input) }
|
||||
}
|
||||
if (block.type === "thinking") return { type: "thinking", thinking: block.thinking, signed: /^agyb1\./.test(block.signature) }
|
||||
return { type: block.type, text: block.text }
|
||||
}),
|
||||
}
|
||||
})
|
||||
const results = []
|
||||
for (const stream of [true, false]) {
|
||||
await withKit({}, async (kit) => {
|
||||
scenario(kit)
|
||||
const { responses } = await runTurn(kit, baseBody(), { stream })
|
||||
for (const parsed of responses) assertCleanUsage(parsed.usage, `stream=${stream}`)
|
||||
results.push(normalize(responses))
|
||||
})
|
||||
}
|
||||
assert.equal(results[0].length, 2)
|
||||
assert.deepEqual(results[1], results[0])
|
||||
})
|
||||
@@ -0,0 +1,516 @@
|
||||
import assert from "node:assert/strict"
|
||||
import childProcess, { spawnSync } from "node:child_process"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { syncBuiltinESMExports } from "node:module"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { test } from "node:test"
|
||||
import { createUsageReader, fetchUsage, parseUsageReport } from "../usage.mjs"
|
||||
|
||||
const report = groups => ({ status: "SUCCESS", command: { name: "usage", data: { groups } } })
|
||||
const group = (buckets, name = "Gemini Models") => ({ name, buckets })
|
||||
const bucket = (overrides = {}) => ({ id: "gemini-5h", name: "Five Hour Limit Remaining", window: "5h", remaining_fraction: 0.75, ...overrides })
|
||||
|
||||
test("maps all groups/cadences to display-only Magpie windows, without invented identity", () => {
|
||||
const result = parseUsageReport(report([
|
||||
group([bucket(), bucket({ id: "gemini-weekly", window: "weekly", remaining_fraction: 0.5 })]),
|
||||
group([bucket({ id: "3p-5h", remaining_fraction: 0 }), bucket({ id: "3p-weekly", window: "weekly", remaining_fraction: 1 })], "Claude and GPT models"),
|
||||
group([bucket({ id: "gemini-argon-weekly", window: "weekly", remaining_fraction: 0.53 })], "Gemini 4 Argon"),
|
||||
]))
|
||||
assert.equal(result.windows.length, 5)
|
||||
assert.deepEqual(result.windows.map(w => w.name), ["Gemini · 5 hours", "Gemini · 7 days", "Claude & GPT · 5 hours", "Claude & GPT · 7 days", "Gemini 4 Argon · 7 days"])
|
||||
assert.deepEqual(result.windows.map(w => w.used), [25, 50, 100, 0, 47])
|
||||
assert.deepEqual(result.windows.map(w => w.span), [18000, 604800, 18000, 604800, 604800])
|
||||
assert.ok(result.windows.every(w => w.aside === true))
|
||||
assert.equal(result.plan, undefined)
|
||||
assert.equal(result.user, undefined)
|
||||
})
|
||||
|
||||
test("accepts camel case and nested/oneof fractions plus ISO and epoch-second resets", () => {
|
||||
const result = parseUsageReport(JSON.stringify(report([{
|
||||
displayName: "Gemini Models",
|
||||
buckets: [
|
||||
{ bucketId: "gemini-5h", displayName: "Session", window: "5h", remaining: { remainingFraction: 0.4 }, resetTime: "2026-10-27T02:00:00+02:00" },
|
||||
{ bucketId: "gemini-weekly", remaining: { case: "remainingFraction", value: 0.8 }, resetTime: "1793059200" },
|
||||
],
|
||||
}])))
|
||||
assert.equal(result.windows[0].used, 60)
|
||||
assert.equal(result.windows[0].resetsAt, "2026-10-27T00:00:00.000Z")
|
||||
assert.equal(result.windows[1].used, 20)
|
||||
assert.equal(result.windows[1].resetsAt, "2026-10-27T00:00:00.000Z")
|
||||
assert.equal(result.windows[1].span, 604800)
|
||||
})
|
||||
|
||||
test("unknown, invalid and disabled quotas are never reported as zero/full usage", () => {
|
||||
const result = parseUsageReport(report([group([
|
||||
bucket(),
|
||||
...[null, undefined, "0.5", true, -0.1, 1.1, NaN, Infinity].map((remaining_fraction, i) => bucket({ id: `unknown-${i}`, remaining_fraction, reset_time: "2026-10-27T00:00:00Z" })),
|
||||
bucket({ id: "disabled", disabled: true }),
|
||||
bucket({ id: "other-oneof", remaining_fraction: undefined, remaining: { case: "unlimited", value: 1 } }),
|
||||
])]))
|
||||
assert.equal(result.windows.length, 10)
|
||||
assert.ok(result.windows.slice(1).every(w => w.used === undefined && w.display === "Limits not available" && w.aside))
|
||||
assert.equal(result.windows[1].resetsAt, "2026-10-27T00:00:00.000Z")
|
||||
})
|
||||
|
||||
test("weekly-only reports stay weekly; explicit unknown cadence never becomes five hours", () => {
|
||||
const result = parseUsageReport(report([group([
|
||||
bucket({ id: "gemini-weekly", window: undefined, name: "Weekly Limit Remaining" }),
|
||||
bucket({ id: "gemini-5h", window: "custom", name: "Special limit", reset_time: "bad" }),
|
||||
bucket({ id: "other", window: undefined, name: "Other", reset_time: "2026-10-27T00:00:00Z" }),
|
||||
])]))
|
||||
assert.equal(result.windows[0].span, 604800)
|
||||
assert.equal(result.windows[1].span, undefined)
|
||||
assert.equal(result.windows[1].resetsAt, undefined)
|
||||
assert.equal(result.windows[2].span, undefined)
|
||||
})
|
||||
|
||||
test("requires a successful usage command with at least one enabled measured bucket", () => {
|
||||
for (const value of [
|
||||
"invalid-json", {}, { status: "ERROR", error: "secret@example.com" },
|
||||
{ ...report([group([bucket()])]), command: { name: "models", data: {} } },
|
||||
report([]), report([group([bucket({ disabled: true })])]),
|
||||
report([group([bucket({ remaining_fraction: undefined })])]),
|
||||
report([group([{ remaining_fraction: 0.5 }])]),
|
||||
]) {
|
||||
assert.throws(() => parseUsageReport(value), error => !error.message.includes("secret@example.com"))
|
||||
}
|
||||
})
|
||||
|
||||
async function waitForPidExit(pid, timeoutMs = 1000) {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
} catch (err) {
|
||||
if (err?.code === "ESRCH") return
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 25))
|
||||
}
|
||||
assert.throws(() => process.kill(pid, 0), { code: "ESRCH" })
|
||||
}
|
||||
|
||||
async function fixture(t, extraEnv = {}) {
|
||||
const isWin = process.platform === "win32"
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "agy-usage-test-"))
|
||||
t.after(async () => {
|
||||
for (let i = 0; i < 6; i++) {
|
||||
try { await fs.rm(directory, { recursive: true, force: true }); break }
|
||||
catch { await new Promise(r => setTimeout(r, 50)) }
|
||||
}
|
||||
})
|
||||
const script = path.join(directory, "fake.mjs")
|
||||
const executable = path.join(directory, isWin ? "agy.cmd" : "agy")
|
||||
const logPath = path.join(directory, "calls.jsonl")
|
||||
await fs.writeFile(script, String.raw`
|
||||
import { spawn, spawnSync } from "node:child_process"
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
const args = process.argv.slice(2)
|
||||
const version = args[0] === "--version"
|
||||
const guardRun = process.platform === "win32"
|
||||
? spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "\"" + process.env.BROWSER + "\""], { windowsHide: true })
|
||||
: spawnSync(process.env.BROWSER)
|
||||
const record = {
|
||||
args, cwd: process.cwd(), pid: process.pid,
|
||||
update: process.env.AGY_CLI_DISABLE_AUTO_UPDATE,
|
||||
path: process.env.PATH, browser: process.env.BROWSER,
|
||||
browserContent: (() => { try { return fs.readFileSync(process.env.BROWSER, "utf8") } catch { return null } })(),
|
||||
agent: fs.readFileSync(path.join(process.cwd(), ".agents/agents/magpie-usage/agent.md"), "utf8"),
|
||||
mode: fs.statSync(process.cwd()).mode & 0o777,
|
||||
guard: guardRun.status,
|
||||
}
|
||||
fs.appendFileSync(process.env.TEST_LOG, JSON.stringify(record) + "\n")
|
||||
const mode = process.env.TEST_MODE
|
||||
if (mode === "version-hang" && version || mode === "hang" && !version) setInterval(() => {}, 1000)
|
||||
else if (version) {
|
||||
console.log(process.env.TEST_VERSION || "1.3.5")
|
||||
} else if (mode === "fail") {
|
||||
console.error(process.env.TEST_ERROR || "oops secret@example.com https://secret.invalid/token")
|
||||
process.exitCode = 1
|
||||
} else if (mode === "oversize") {
|
||||
process.stdout.write("x".repeat(1024 * 1024 + 1))
|
||||
} else if (mode === "combined-output") {
|
||||
process.stdout.write("x".repeat(600))
|
||||
process.stderr.write("y".repeat(600))
|
||||
} else if (mode === "malformed") {
|
||||
console.log("invalid secret@example.com")
|
||||
} else if (mode === "descendant") {
|
||||
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "inherit", windowsHide: true })
|
||||
fs.writeFileSync(process.env.TEST_DESCENDANT, String(child.pid))
|
||||
child.unref()
|
||||
console.log(process.env.TEST_REPORT)
|
||||
} else {
|
||||
if (mode === "delay") await new Promise(resolve => setTimeout(resolve, 150))
|
||||
console.log(process.env.TEST_REPORT)
|
||||
}
|
||||
`)
|
||||
if (isWin) {
|
||||
await fs.writeFile(executable, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
|
||||
} else {
|
||||
await fs.writeFile(executable, `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(script)} "$@"\n`, { mode: 0o700 })
|
||||
}
|
||||
const env = { ...process.env, TEST_LOG: logPath, TEST_REPORT: JSON.stringify(report([group([bucket()])])), TEST_DESCENDANT: path.join(directory, "descendant"), ...extraEnv }
|
||||
return {
|
||||
executable, env,
|
||||
options: { env, tempRoot: directory },
|
||||
async logs() { return (await fs.readFile(logPath, "utf8")).trim().split("\n").map(line => JSON.parse(line)) },
|
||||
async assertClean() { assert.deepEqual((await fs.readdir(directory)).filter(name => name.startsWith("magpie-agy-usage-")), []) },
|
||||
}
|
||||
}
|
||||
|
||||
test("queries only the structured command in a private, restricted workspace and cleans up", async t => {
|
||||
const f = await fixture(t, { AGY_CLI_DISABLE_AUTO_UPDATE: "false" })
|
||||
const originalSpawn = childProcess.spawn
|
||||
const spawns = []
|
||||
let result
|
||||
try {
|
||||
childProcess.spawn = (file, args, options) => {
|
||||
spawns.push({ file, args, options })
|
||||
return originalSpawn(file, args, options)
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
result = await fetchUsage(f.executable, f.options)
|
||||
} finally {
|
||||
childProcess.spawn = originalSpawn
|
||||
syncBuiltinESMExports()
|
||||
}
|
||||
assert.equal(result.windows[0].used, 25)
|
||||
const logs = await f.logs()
|
||||
assert.equal(logs.length, 2)
|
||||
assert.equal(spawns.length, 2)
|
||||
for (const [index, actual] of spawns.entries()) {
|
||||
if (actual.file === "taskkill") continue
|
||||
if (process.platform !== "win32") {
|
||||
assert.equal(actual.file, f.executable)
|
||||
assert.deepEqual(actual.args, logs[index].args)
|
||||
assert.equal(actual.options.detached, true)
|
||||
} else {
|
||||
assert.equal(actual.options.detached, false)
|
||||
}
|
||||
assert.equal(actual.options.windowsHide, true, "usage must hide both version and report child windows")
|
||||
assert.deepEqual(actual.options.stdio, ["ignore", "pipe", "pipe"])
|
||||
assert.equal(path.basename(actual.options.cwd), path.basename(logs[index].cwd))
|
||||
assert.equal(actual.options.env.AGY_CLI_DISABLE_AUTO_UPDATE, "false", "a value the user set is passed on as written")
|
||||
assert.equal(actual.options.env.TEST_LOG, f.env.TEST_LOG)
|
||||
assert.notEqual(actual.options.env, f.env)
|
||||
}
|
||||
assert.deepEqual(logs[0].args, ["--version"])
|
||||
assert.deepEqual(logs[1].args.slice(0, 6), ["-p", "/usage", "--output-format", "json", "--agent", "magpie-usage"])
|
||||
assert.equal(logs[1].args[6], "--print-timeout")
|
||||
assert.match(logs[1].args[7], /^\d+s$/)
|
||||
for (const log of logs) {
|
||||
if (process.platform !== "win32") assert.equal(log.mode, 0o700)
|
||||
assert.equal(log.update, "false")
|
||||
assert.ok(log.agent.includes("tools: []\nmcpServers: []"))
|
||||
assert.equal(log.guard, 1)
|
||||
// macOS process.cwd() canonicalizes /var to /private/var.
|
||||
assert.equal(path.basename(log.path.split(path.delimiter)[0]), path.basename(log.cwd))
|
||||
assert.equal(path.dirname(log.browser), log.path.split(path.delimiter)[0])
|
||||
assert.equal(path.basename(log.browser), process.platform === "win32" ? "open.cmd" : "open")
|
||||
await assert.rejects(fs.stat(log.cwd), { code: "ENOENT" })
|
||||
}
|
||||
assert.equal(f.env.AGY_CLI_DISABLE_AUTO_UPDATE, "false")
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("with nothing set, usage children run with auto-update off", async t => {
|
||||
const f = await fixture(t)
|
||||
const env = { ...f.env }
|
||||
for (const key of Object.keys(env)) if (/^agy_cli_disable_auto_update$/i.test(key)) delete env[key]
|
||||
const result = await fetchUsage(f.executable, { ...f.options, env })
|
||||
assert.equal(result.windows[0].used, 25)
|
||||
const logs = await f.logs()
|
||||
assert.equal(logs.length, 2)
|
||||
for (const log of logs) assert.equal(log.update, "true")
|
||||
assert.equal("AGY_CLI_DISABLE_AUTO_UPDATE" in env, false)
|
||||
})
|
||||
|
||||
test("simulated Windows fetches usage with hidden, attached children and a cmd browser guard", { skip: process.platform === "win32" }, async t => {
|
||||
const f = await fixture(t, { PATH: "/usr/bin:/bin", Path: "C:\\Windows\\System32" })
|
||||
const descriptor = Object.getOwnPropertyDescriptor(process, "platform")
|
||||
const originalSpawn = childProcess.spawn
|
||||
const spawns = []
|
||||
let taskkills = 0
|
||||
let result
|
||||
try {
|
||||
Object.defineProperty(process, "platform", { ...descriptor, value: "win32" })
|
||||
childProcess.spawn = (file, args, options) => {
|
||||
if (file === "taskkill") {
|
||||
taskkills++
|
||||
return { unref() {} }
|
||||
}
|
||||
spawns.push({ file, args, options })
|
||||
return originalSpawn(file, args, options)
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
result = await fetchUsage(f.executable, f.options)
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", descriptor)
|
||||
childProcess.spawn = originalSpawn
|
||||
syncBuiltinESMExports()
|
||||
}
|
||||
assert.equal(result.windows[0].used, 25)
|
||||
const logs = await f.logs()
|
||||
assert.equal(logs.length, 2)
|
||||
assert.equal(spawns.length, 2)
|
||||
assert.equal(taskkills, 0, "a clean Windows run must never launch taskkill")
|
||||
for (const [index, actual] of spawns.entries()) {
|
||||
assert.equal(actual.file, f.executable)
|
||||
assert.deepEqual(actual.args, logs[index].args)
|
||||
assert.equal(path.basename(actual.options.cwd), path.basename(logs[index].cwd))
|
||||
assert.equal(actual.options.detached, false, "Windows children stay attached to the runner")
|
||||
assert.equal(actual.options.windowsHide, true)
|
||||
assert.equal(actual.options.env.AGY_CLI_DISABLE_AUTO_UPDATE, "true")
|
||||
assert.ok(!("Path" in actual.options.env), "mixed-case Path must be folded into PATH")
|
||||
assert.equal(actual.options.env.PATH, actual.options.cwd + path.delimiter + "/usr/bin:/bin")
|
||||
}
|
||||
for (const log of logs) {
|
||||
assert.equal(log.update, "true")
|
||||
assert.equal(path.basename(path.dirname(log.browser)), path.basename(log.cwd))
|
||||
assert.equal(path.basename(log.browser), "open.cmd")
|
||||
assert.equal(log.browserContent, "@exit /b 1\r\n")
|
||||
await assert.rejects(fs.stat(log.cwd), { code: "ENOENT" })
|
||||
}
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("simulated Windows timeouts kill the whole tree via taskkill /T /F /PID", { skip: process.platform === "win32" }, async t => {
|
||||
const f = await fixture(t, { TEST_MODE: "hang" })
|
||||
const descriptor = Object.getOwnPropertyDescriptor(process, "platform")
|
||||
const originalSpawn = childProcess.spawn
|
||||
const kills = []
|
||||
try {
|
||||
Object.defineProperty(process, "platform", { ...descriptor, value: "win32" })
|
||||
childProcess.spawn = (file, args, options) => {
|
||||
if (file === "taskkill") {
|
||||
kills.push({ args, options })
|
||||
// Emulate taskkill termination so the killed child releases its pipes on this POSIX host.
|
||||
try { process.kill(Number(args[3]), "SIGKILL") } catch {}
|
||||
return { unref() {} }
|
||||
}
|
||||
return originalSpawn(file, args, options)
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
await assert.rejects(fetchUsage(f.executable, { ...f.options, timeoutMs: 600 }), /timed out/)
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", descriptor)
|
||||
childProcess.spawn = originalSpawn
|
||||
syncBuiltinESMExports()
|
||||
}
|
||||
const logs = await f.logs()
|
||||
const treeKills = kills.filter(kill => kill.args[3] === String(logs[1].pid))
|
||||
assert.equal(treeKills.length, 1)
|
||||
assert.deepEqual(treeKills[0].args, ["/T", "/F", "/PID", String(logs[1].pid)])
|
||||
assert.equal(treeKills[0].options.windowsHide, true)
|
||||
// The runner must actually stop both children, not just stop waiting for them.
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
for (const log of logs) assert.throws(() => process.kill(log.pid, 0), { code: "ESRCH" })
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("simulated Windows tree-kills pipe-holding descendants after the CLI parent exits", { skip: process.platform === "win32" }, async t => {
|
||||
const f = await fixture(t, { TEST_MODE: "descendant" })
|
||||
const descriptor = Object.getOwnPropertyDescriptor(process, "platform")
|
||||
const originalSpawn = childProcess.spawn
|
||||
const kills = []
|
||||
let result
|
||||
try {
|
||||
Object.defineProperty(process, "platform", { ...descriptor, value: "win32" })
|
||||
childProcess.spawn = (file, args, options) => {
|
||||
if (file === "taskkill") {
|
||||
kills.push({ args, options })
|
||||
// Emulate /T tree termination so the inherited pipe closes on this POSIX host.
|
||||
try { process.kill(Number(readFileSync(f.env.TEST_DESCENDANT, "utf8")), "SIGKILL") } catch {}
|
||||
try { process.kill(Number(args[3]), "SIGKILL") } catch {}
|
||||
return { unref() {} }
|
||||
}
|
||||
return originalSpawn(file, args, options)
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
result = await fetchUsage(f.executable, f.options)
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", descriptor)
|
||||
childProcess.spawn = originalSpawn
|
||||
syncBuiltinESMExports()
|
||||
}
|
||||
assert.equal(result.windows[0].used, 25)
|
||||
const logs = await f.logs()
|
||||
const treeKills = kills.filter(kill => kill.args[3] === String(logs[1].pid))
|
||||
assert.equal(treeKills.length, 1)
|
||||
assert.deepEqual(treeKills[0].args, ["/T", "/F", "/PID", String(logs[1].pid)])
|
||||
const pid = Number(await fs.readFile(f.env.TEST_DESCENDANT, "utf8"))
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
// A dead orphan can briefly be a zombie on Linux, which has no running code.
|
||||
const status = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" })
|
||||
assert.ok(!status.stdout.trim() || status.stdout.trim().startsWith("Z"))
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("retries locked-directory removal (EBUSY) until it succeeds", async t => {
|
||||
const f = await fixture(t)
|
||||
const originalRm = fs.rm
|
||||
const attempts = []
|
||||
let result
|
||||
try {
|
||||
fs.rm = async (target, options) => {
|
||||
attempts.push(target)
|
||||
if (attempts.length <= 2) {
|
||||
const error = new Error("EBUSY: directory is locked")
|
||||
error.code = "EBUSY"
|
||||
throw error
|
||||
}
|
||||
return originalRm(target, options)
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
result = await fetchUsage(f.executable, f.options)
|
||||
} finally {
|
||||
fs.rm = originalRm
|
||||
syncBuiltinESMExports()
|
||||
}
|
||||
assert.equal(result.windows[0].used, 25)
|
||||
assert.equal(attempts.length, 3)
|
||||
for (const target of attempts) assert.ok(path.basename(target).startsWith("magpie-agy-usage-"))
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("stops retrying locked-directory removal after four attempts without failing the query", async t => {
|
||||
const f = await fixture(t)
|
||||
const originalRm = fs.rm
|
||||
let attempts = 0
|
||||
try {
|
||||
fs.rm = async () => {
|
||||
attempts++
|
||||
const error = new Error("EBUSY: directory is locked")
|
||||
error.code = "EBUSY"
|
||||
throw error
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
assert.equal((await fetchUsage(f.executable, f.options)).windows[0].used, 25)
|
||||
} finally {
|
||||
fs.rm = originalRm
|
||||
syncBuiltinESMExports()
|
||||
}
|
||||
assert.equal(attempts, 4)
|
||||
const root = path.dirname(f.env.TEST_LOG)
|
||||
for (const name of (await fs.readdir(root)).filter(name => name.startsWith("magpie-agy-usage-"))) {
|
||||
await fs.rm(path.join(root, name), { recursive: true, force: true })
|
||||
}
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("rejects old/unverified versions before any possible model prompt", async t => {
|
||||
for (const version of ["1.1.10", "0.9.0", "garbage", "1.3", "1.3.5-beta"]) {
|
||||
const f = await fixture(t, { TEST_VERSION: version })
|
||||
await assert.rejects(fetchUsage(f.executable, f.options), /1\.1\.11 or later/)
|
||||
assert.equal((await f.logs()).length, 1)
|
||||
await f.assertClean()
|
||||
}
|
||||
for (const version of ["1.1.11", "1.2.0", "2.0.0"]) {
|
||||
const f = await fixture(t, { TEST_VERSION: version })
|
||||
assert.equal((await fetchUsage(f.executable, f.options)).windows.length, 1)
|
||||
await f.assertClean()
|
||||
}
|
||||
})
|
||||
|
||||
test("only concurrent refreshes share work, and callers cannot mutate each other's data", async t => {
|
||||
const f = await fixture(t, { TEST_MODE: "delay" })
|
||||
const read = createUsageReader(() => f.executable, f.options)
|
||||
const results = await Promise.all([read(), read(), read()])
|
||||
assert.equal((await f.logs()).length, 2)
|
||||
assert.equal(results[0].signIn, "kept")
|
||||
results[0].windows[0].used = 99
|
||||
assert.equal(results[1].windows[0].used, 25)
|
||||
await read()
|
||||
assert.equal((await f.logs()).length, 4)
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("reports sanitized failures and preserves the bridge sign-in; failures are retryable", async t => {
|
||||
for (const [message, expected] of [
|
||||
["Not logged in secret@example.com https://secret.invalid/token", /sign in again/],
|
||||
["Eligibility check failed: EOF secret@example.com", /eligibility check failed on a network/],
|
||||
["not eligible secret@example.com", /not eligible/],
|
||||
["connection refused: secret@example.com https://secret.invalid", /network or proxy/],
|
||||
["unrecognized secret@example.com", /could not read usage/],
|
||||
]) {
|
||||
const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: message })
|
||||
const read = createUsageReader(() => f.executable, f.options)
|
||||
const result = await read()
|
||||
assert.deepEqual(result.windows, [])
|
||||
assert.equal(result.signIn, "kept")
|
||||
assert.match(result.error, expected)
|
||||
assert.doesNotMatch(result.error, /secret|https:/)
|
||||
f.env.TEST_MODE = ""
|
||||
assert.equal((await read()).windows.length, 1)
|
||||
await f.assertClean()
|
||||
}
|
||||
})
|
||||
|
||||
test("invalid and oversized stdout/stderr reports fail within the output budget", async t => {
|
||||
for (const [mode, expected, maxOutputBytes] of [
|
||||
["malformed", /invalid usage report/, undefined],
|
||||
["oversize", /size limit/, undefined],
|
||||
["combined-output", /size limit/, 1000],
|
||||
]) {
|
||||
const f = await fixture(t, { TEST_MODE: mode })
|
||||
await assert.rejects(fetchUsage(f.executable, { ...f.options, ...(maxOutputBytes ? { maxOutputBytes } : {}) }), expected)
|
||||
await f.assertClean()
|
||||
}
|
||||
})
|
||||
|
||||
test("version/report hangs time out, terminate the process, and leave no workspace", async t => {
|
||||
for (const mode of ["version-hang", "hang"]) {
|
||||
const f = await fixture(t, { TEST_MODE: mode })
|
||||
await assert.rejects(fetchUsage(f.executable, { ...f.options, timeoutMs: 600 }), /timed out/)
|
||||
// The runner must actually stop the child, not just stop waiting for it.
|
||||
for (const log of await f.logs()) {
|
||||
await waitForPidExit(log.pid)
|
||||
}
|
||||
await f.assertClean()
|
||||
}
|
||||
})
|
||||
|
||||
test("cancellation stops a running report and cleans its private workspace", async t => {
|
||||
const f = await fixture(t, { TEST_MODE: "hang" })
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), 600)
|
||||
try {
|
||||
await assert.rejects(fetchUsage(f.executable, { ...f.options, signal: controller.signal }), /cancelled/)
|
||||
} finally { clearTimeout(timer) }
|
||||
await f.assertClean()
|
||||
const alreadyAborted = new AbortController()
|
||||
alreadyAborted.abort()
|
||||
await assert.rejects(fetchUsage(f.executable, { ...f.options, signal: alreadyAborted.signal }), /cancelled/)
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("terminates owned pipe-inheriting descendants even when the CLI parent already exited", async t => {
|
||||
const f = await fixture(t, { TEST_MODE: "descendant" })
|
||||
await fetchUsage(f.executable, f.options)
|
||||
const pid = Number(await fs.readFile(f.env.TEST_DESCENDANT, "utf8"))
|
||||
if (process.platform === "win32") {
|
||||
await waitForPidExit(pid)
|
||||
} else {
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
// A dead orphan can briefly be a zombie on Linux, which has no running code.
|
||||
const status = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" })
|
||||
assert.ok(!status.stdout.trim() || status.stdout.trim().startsWith("Z"))
|
||||
}
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("missing executables and filesystem failures do not leak local paths", async t => {
|
||||
const f = await fixture(t)
|
||||
for (const executable of [null, path.join(f.env.TEST_LOG, "missing")]) {
|
||||
const result = await createUsageReader(() => executable, f.options)()
|
||||
assert.equal(result.windows.length, 0)
|
||||
assert.ok(result.error)
|
||||
assert.doesNotMatch(result.error, /agy-usage-test-/)
|
||||
await f.assertClean()
|
||||
}
|
||||
const result = await createUsageReader(() => f.executable, { ...f.options, tempRoot: f.executable })()
|
||||
assert.ok(result.error)
|
||||
assert.doesNotMatch(result.error, /agy-usage-test-/)
|
||||
})
|
||||
@@ -0,0 +1,289 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { agySpawnSpec, childEnv as agyChildEnv } from "./platform.mjs"
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 15_000
|
||||
const MAX_TIMEOUT_MS = 18_000 // Magpie bounds an auth.usage call to 20 seconds.
|
||||
const MAX_OUTPUT_BYTES = 1024 * 1024
|
||||
|
||||
class UsageError extends Error {}
|
||||
|
||||
const text = value => typeof value === "string" ? value.trim() : ""
|
||||
const field = (value, camel, snake) => value?.[camel] ?? value?.[snake]
|
||||
|
||||
function commandFailure(output) {
|
||||
if (/not (?:logged|signed) in|unauthenticated|authentication required|login required|please (?:log|sign) in|sign in again/i.test(output)) {
|
||||
return new UsageError("agy usage needs authentication. Run `agy` in a terminal to sign in again.")
|
||||
}
|
||||
const eligibility = /eligibility check failed|not eligible|unsupported (?:country|region)|does not support google tos/i.test(output)
|
||||
const network = /\b(?:eof|timeout|timed out|deadline exceeded|no such host|connection (?:refused|reset)|network|proxy|tls|ssl|certificate)\b/i.test(output)
|
||||
if (network) return new UsageError(`agy usage ${eligibility ? "eligibility check " : ""}failed on a network request. Check network or proxy settings.`)
|
||||
if (eligibility) return new UsageError("agy reports that this account is not eligible for Antigravity.")
|
||||
return new UsageError("agy could not read usage. Run `agy` in a terminal to check its status.")
|
||||
}
|
||||
|
||||
function resetTime(value) {
|
||||
if (value == null || value === "" || typeof value === "boolean") return undefined
|
||||
const raw = String(value)
|
||||
let ms
|
||||
if (/^\d+(?:\.\d+)?$/.test(raw)) ms = Number(raw) * (Number(raw) < 1e11 ? 1000 : 1)
|
||||
else if (/^\d{4}-\d{2}-\d{2}T/.test(raw)) ms = Date.parse(raw)
|
||||
if (!Number.isFinite(ms) || ms <= 0 || ms > 253402300799999) return undefined
|
||||
return new Date(ms).toISOString()
|
||||
}
|
||||
|
||||
function cadence(bucket, id, name) {
|
||||
// An explicit, unfamiliar window must not be overridden by an older ID/label.
|
||||
const value = text(bucket.window) || `${id} ${name}`
|
||||
if (/^(?:5h|five[_ -]?hours?|five_hour|session)$/i.test(value) || !text(bucket.window) && /(?:5h|five[ _-]hour|session)/i.test(value)) {
|
||||
return { name: "5 hours", span: 5 * 60 * 60 }
|
||||
}
|
||||
if (/^(?:weekly|week|7d|seven[_ -]?days?)$/i.test(value) || !text(bucket.window) && /(?:weekly|week|7d)/i.test(value)) {
|
||||
return { name: "7 days", span: 7 * 24 * 60 * 60 }
|
||||
}
|
||||
return { name: name || id }
|
||||
}
|
||||
|
||||
// agy's command report is not its token-usage object or a model-availability list.
|
||||
// Unknown quota is not evidence of exhaustion or a full allowance.
|
||||
export function parseUsageReport(value) {
|
||||
let report
|
||||
try { report = typeof value === "string" ? JSON.parse(value) : value } catch {
|
||||
throw new UsageError("agy returned an invalid usage report.")
|
||||
}
|
||||
if (report?.status !== "SUCCESS" || report?.command?.name !== "usage") {
|
||||
throw commandFailure(`${text(report?.error)} ${text(report?.response)}`)
|
||||
}
|
||||
const groups = report.command.data?.groups
|
||||
const windows = []
|
||||
for (const group of Array.isArray(groups) ? groups : []) {
|
||||
const pool = (text(field(group, "displayName", "display_name")) || text(group?.name) || "Quota")
|
||||
.replace(/\s+models$/i, "").replace(/\s+and\s+/gi, " & ")
|
||||
for (const bucket of Array.isArray(group?.buckets) ? group.buckets : []) {
|
||||
const id = text(field(bucket, "bucketId", "bucket_id")) || text(bucket?.id)
|
||||
if (!id || bucket?.disabled === true) continue
|
||||
const label = text(field(bucket, "displayName", "display_name")) || text(bucket?.name)
|
||||
const period = cadence(bucket, id, label)
|
||||
const remaining = bucket.remaining
|
||||
const fraction = field(bucket, "remainingFraction", "remaining_fraction")
|
||||
?? field(remaining, "remainingFraction", "remaining_fraction")
|
||||
?? (remaining?.case === "remainingFraction" ? remaining.value : undefined)
|
||||
const known = typeof fraction === "number" && Number.isFinite(fraction) && fraction >= 0 && fraction <= 1
|
||||
const resetsAt = resetTime(field(bucket, "resetTime", "reset_time"))
|
||||
windows.push({
|
||||
name: `${pool} · ${period.name}`,
|
||||
// This feature displays quota only; it must not change model routing.
|
||||
aside: true,
|
||||
...(known ? { used: Math.round((1 - fraction) * 1e8) / 1e6 } : { display: "Limits not available" }),
|
||||
...(period.span ? { span: period.span } : {}),
|
||||
...(resetsAt ? { resetsAt } : {}),
|
||||
})
|
||||
}
|
||||
}
|
||||
if (!windows.some(w => w.used !== undefined)) {
|
||||
throw new UsageError("Limits not available: agy returned no enabled, measured quota buckets.")
|
||||
}
|
||||
// /usage has no verified account or plan identity. Do not borrow one elsewhere.
|
||||
return { windows }
|
||||
}
|
||||
|
||||
function timeout(value) {
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) && n > 0 ? Math.min(n, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS
|
||||
}
|
||||
|
||||
function run(file, args, { cwd, env, deadline, signal, maxOutputBytes, onTreeKill }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let child
|
||||
let settled = false
|
||||
let stopped = false
|
||||
let bytes = 0
|
||||
const stdout = []
|
||||
const stderr = []
|
||||
let timer
|
||||
let treeKillTimer
|
||||
let fallbackKillTimer
|
||||
const killWindowsTree = () => {
|
||||
let spawned = false
|
||||
try {
|
||||
const killer = spawn("taskkill", ["/T", "/F", "/PID", String(child.pid)], { stdio: "ignore", windowsHide: true })
|
||||
killer?.unref?.()
|
||||
spawned = Boolean(killer)
|
||||
if (typeof killer?.once === "function") {
|
||||
const done = new Promise(r => {
|
||||
killer.once("error", () => { try { child.kill("SIGKILL") } catch {}; r() })
|
||||
killer.once("close", code => { if (code !== 0) try { child.kill("SIGKILL") } catch {}; r() })
|
||||
})
|
||||
onTreeKill?.(done)
|
||||
}
|
||||
} catch {}
|
||||
if (!spawned) {
|
||||
try { child.kill("SIGKILL") } catch {}
|
||||
} else {
|
||||
fallbackKillTimer = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 500)
|
||||
fallbackKillTimer.unref?.()
|
||||
}
|
||||
}
|
||||
const stop = (fromExit = false) => {
|
||||
if (!child?.pid || stopped) return
|
||||
if (process.platform === "win32") {
|
||||
if (fromExit && child.exitCode !== null) {
|
||||
treeKillTimer = setTimeout(() => {
|
||||
if (!settled && !stopped) {
|
||||
stopped = true
|
||||
killWindowsTree()
|
||||
}
|
||||
}, 30)
|
||||
treeKillTimer.unref?.()
|
||||
return
|
||||
}
|
||||
stopped = true
|
||||
clearTimeout(treeKillTimer)
|
||||
killWindowsTree()
|
||||
return
|
||||
}
|
||||
stopped = true
|
||||
// Only this detached child/group is ours, never an existing user agy.
|
||||
try { process.kill(-child.pid, "SIGKILL") } catch {
|
||||
try { child.kill("SIGKILL") } catch {}
|
||||
}
|
||||
}
|
||||
const finish = (error, result) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
clearTimeout(treeKillTimer)
|
||||
clearTimeout(fallbackKillTimer)
|
||||
signal?.removeEventListener("abort", abort)
|
||||
if (process.platform !== "win32" || error || child?.exitCode === null) {
|
||||
stop() // Also stop MCP descendants if the parent exited first.
|
||||
}
|
||||
child?.stdout?.destroy()
|
||||
child?.stderr?.destroy()
|
||||
if (error) reject(error)
|
||||
else resolve(result)
|
||||
}
|
||||
const abort = () => finish(new UsageError("agy usage query was cancelled."))
|
||||
if (signal?.aborted) return abort()
|
||||
if (Date.now() >= deadline) return finish(new UsageError("agy usage query timed out."))
|
||||
try {
|
||||
const command = agySpawnSpec(file, args)
|
||||
child = spawn(command.file, command.args, {
|
||||
cwd,
|
||||
env,
|
||||
detached: process.platform !== "win32",
|
||||
...command.options,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
} catch {
|
||||
finish(new UsageError("agy usage could not start the CLI."))
|
||||
return
|
||||
}
|
||||
signal?.addEventListener("abort", abort, { once: true })
|
||||
timer = setTimeout(() => finish(new UsageError("agy usage query timed out.")), Math.max(1, deadline - Date.now()))
|
||||
const collect = chunks => chunk => {
|
||||
if (settled) return
|
||||
bytes += chunk.length
|
||||
if (bytes > maxOutputBytes) return finish(new UsageError("agy usage output exceeded the size limit."))
|
||||
chunks.push(chunk)
|
||||
}
|
||||
child.stdout.on("data", collect(stdout))
|
||||
child.stderr.on("data", collect(stderr))
|
||||
child.on("error", () => finish(new UsageError("agy usage could not start the CLI.")))
|
||||
// exit, not close: a descendant may inherit the pipe and keep it open.
|
||||
// Drain the already-written output through close for a normal parent exit.
|
||||
child.on("exit", () => stop(true))
|
||||
child.on("close", code => finish(null, {
|
||||
code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8"),
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
function supportedVersion(output) {
|
||||
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(output.trim())
|
||||
if (!match) return false
|
||||
const [major, minor, patch] = match.slice(1).map(Number)
|
||||
return major > 1 || major === 1 && (minor > 1 || minor === 1 && patch >= 11)
|
||||
}
|
||||
|
||||
export async function fetchUsage(agy, {
|
||||
env = process.env,
|
||||
timeoutMs = env.AGY_BRIDGE_USAGE_TIMEOUT_MS,
|
||||
maxOutputBytes = MAX_OUTPUT_BYTES,
|
||||
signal,
|
||||
tempRoot = os.tmpdir(),
|
||||
} = {}) {
|
||||
if (!agy) throw new UsageError("agy CLI not found. Install it and run `agy` once to sign in.")
|
||||
const deadline = Date.now() + timeout(timeoutMs)
|
||||
const directory = await fs.mkdtemp(path.join(tempRoot, "magpie-agy-usage-"))
|
||||
let pendingTreeKill = null
|
||||
try {
|
||||
await fs.chmod(directory, 0o700)
|
||||
const agentDir = path.join(directory, ".agents", "agents", "magpie-usage")
|
||||
await fs.mkdir(agentDir, { recursive: true })
|
||||
await fs.writeFile(path.join(agentDir, "agent.md"), [
|
||||
"---", "name: magpie-usage", "description: Read CLI usage only", "mainAgent: true", "subagent: false",
|
||||
"tools: []", "mcpServers: []", "---", "Do not run model prompts or tools.", "",
|
||||
].join("\n"), { mode: 0o600 })
|
||||
if (process.platform === "win32") {
|
||||
await fs.writeFile(path.join(directory, "open.cmd"), "@exit /b 1\r\n")
|
||||
} else {
|
||||
for (const name of ["open", "xdg-open"]) {
|
||||
await fs.writeFile(path.join(directory, name), "#!/bin/sh\nexit 1\n", { mode: 0o700 })
|
||||
}
|
||||
}
|
||||
const baseEnv = { ...env }
|
||||
const inheritedPath = env.PATH || baseEnv.Path || (process.platform === "win32" ? "" : "/usr/bin:/bin")
|
||||
for (const key of Object.keys(baseEnv)) {
|
||||
if (/^path$/i.test(key) && key !== "PATH") delete baseEnv[key]
|
||||
}
|
||||
const childEnv = agyChildEnv(baseEnv, {
|
||||
PATH: directory + path.delimiter + inheritedPath,
|
||||
BROWSER: path.join(directory, process.platform === "win32" ? "open.cmd" : "open"),
|
||||
})
|
||||
const options = { cwd: directory, env: childEnv, deadline, signal, maxOutputBytes, onTreeKill: p => { pendingTreeKill = p } }
|
||||
const version = await run(agy, ["--version"], { ...options, deadline: Math.min(deadline, Date.now() + 3000) })
|
||||
if (version.code !== 0) throw commandFailure(version.stderr)
|
||||
if (!supportedVersion(version.stdout)) throw new UsageError("agy usage reports require a verified agy version 1.1.11 or later. Update the CLI.")
|
||||
const result = await run(agy, ["-p", "/usage", "--output-format", "json", "--agent", "magpie-usage", "--print-timeout", `${Math.max(1, Math.ceil((deadline - Date.now()) / 1000))}s`], options)
|
||||
if (result.code !== 0) throw commandFailure(result.stderr + "\n" + result.stdout)
|
||||
return parseUsageReport(result.stdout)
|
||||
} finally {
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
await fs.rm(directory, { recursive: true, force: true })
|
||||
break
|
||||
} catch (error) {
|
||||
if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break
|
||||
if (pendingTreeKill) {
|
||||
const waitKill = pendingTreeKill
|
||||
pendingTreeKill = null
|
||||
await Promise.race([waitKill, new Promise(resolve => setTimeout(resolve, 800))])
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 50 * (attempt + 1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No completed-result cache: sequential refreshes must see account/allowance changes.
|
||||
export function createUsageReader(resolveAgy, options = {}) {
|
||||
const pending = new Map()
|
||||
return async () => {
|
||||
try {
|
||||
const agy = resolveAgy()
|
||||
if (!pending.has(agy)) {
|
||||
const query = fetchUsage(agy, options).finally(() => {
|
||||
if (pending.get(agy) === query) pending.delete(agy)
|
||||
})
|
||||
pending.set(agy, query)
|
||||
}
|
||||
return { ...structuredClone(await pending.get(agy)), signIn: "kept" }
|
||||
} catch (error) {
|
||||
return { windows: [], error: error instanceof UsageError ? error.message : "agy usage query failed. Check the CLI and temporary-directory permissions.", signIn: "kept" }
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -246,6 +246,8 @@
|
||||
}
|
||||
},
|
||||
{ "package": "magpie-deepaicode", "name": "DeepAI Code", "icon": "https://raw.githubusercontent.com/aqiu817/magpie-deepaicode/main/icon.svg", "providers": ["deepaicode"],
|
||||
"summary": { "en": "Unofficial DeepAI Code access for magpie: browser sign-in, the desktop app's saved credentials or an API key, direct upstream requests with the device's real machine fingerprint, live models, daily Theos quota and check-in.", "zh": "非官方接入 DeepAI Code:浏览器登录、桌面端凭据或 API Key,直连上游并使用真实设备指纹,动态模型目录、每日 Theos 额度与签到。" } }
|
||||
"summary": { "en": "Unofficial DeepAI Code access for magpie: browser sign-in, the desktop app's saved credentials or an API key, direct upstream requests with the device's real machine fingerprint, live models, daily Theos quota and check-in.", "zh": "非官方接入 DeepAI Code:浏览器登录、桌面端凭据或 API Key,直连上游并使用真实设备指纹,动态模型目录、每日 Theos 额度与签到。" } },
|
||||
{ "package": "@magpie-community/opencode-agy-cli-auth", "name": "Antigravity (local agy CLI)", "icon": "antigravity-color", "providers": ["agy-cli"], "community": true,
|
||||
"summary": { "en": "Unofficial provider that runs the agy CLI you installed and signed in to through the Agent Client Protocol (agy acp), serving only the models agy offers this client. Unlike Antigravity ACP, which downloads Google's ACP server and rides the Antigravity IDE's sign-in, it uses your own agy and adds a process pool, a history budget, a bridge for the client's tools, session resume and agy's usage windows.", "zh": "非官方插件:通过 Agent Client Protocol(agy acp)驱动你自己安装并登录的 agy CLI,只提供 agy 向本客户端开放的模型。与自行下载 Google ACP 服务端、依赖 Antigravity IDE 登录的 Antigravity ACP 不同,它用你本机的 agy,并带进程池、历史体积预算、客户端工具桥接、会话续接与 agy 用量窗口。" } }
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user