agy-cli 0.1.2: list what agy acp offers before the first request (#854)

Until a request had opened an ACP session, agy-cli listed Gemini only
(offeredFilter), so a user who hadn't sent a Gemini request yet saw no
Opus (chriskan666 on Discord). provider.models() now asks agy's ACP
server itself, as yulong-ge's antigravity-official-acp (#854) does:
a short `agy acp` with the plugin's own clientInfo, initialize and
session/new (no prompt), reading the session's model option and
models.availableModels into the same offered set a request's session
fills. The session is closed when agy says it can be, and the process
and its temp folder are removed.

- Only provider.models() probes; a request opens its own session.
- It runs once `agy models` has answered (agy is signed in), at most
  once a minute while the offer is unknown, and not at all once known.
- models() waits for it as briefly as for the listing (500ms) and
  never longer; a failed or timed-out probe (30s) keeps Gemini only.
- An agy older than 1.4.12 gets no session.

#854's own code reads session/new's availableModels, not `agy models`
(its body says `agy models`); agy-cli already parsed `agy models`, so
nothing of that parser changed.

Run at origin/main ae518836 plus this diff (this commit's tree) on mote (macOS), HOME=$(mktemp -d), under suite.lock:

- `bun test packages/agy-cli`: 6 of 7 suites pass; test/usage.mjs was red
  once ("version/report hangs time out", 1239ms), a timing test this
  change doesn't touch: filed as #856. It then passed 5 of 5 alone.
  catalog 17 pass, smoke ALL OK (314 checks).
- `bun scripts/check.mjs agy-cli`: registry.json and agy-cli ok.
- repo-root `bun test`: 6878 pass, 0 fail (6898 tests, 500 files).

Broken by hand: models() with the probe off. catalog.mjs went 2 red
(the probe lists Opus with no request; a failed probe is tried again
after a minute) and smoke.mjs 1 BAD ("listing models learns what agy's
ACP server offers, before any request").

Not tried: a real signed-in agy. This Mac's agy 1.5.3 (CLI 1.4.12) is
signed out: `agy models` says "Please sign in to view available
models", and its `agy acp` answers initialize and refuses session/new
with -32000 "Authentication required" (the fake's sign-in error is that
reply). mote has no agy. That the ACP session offers Claude and GPT-OSS
to a non-editor client rests on #854's author's run (agy 1.5.3 acp,
13 models incl. Claude and GPT-OSS).

Co-authored-by: yulong-ge <41790869+yulong-ge@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-08 13:17:47 +08:00
co-authored by yulong-ge
parent ae51883634
commit 03ab6d66f4
7 changed files with 162 additions and 18 deletions
+2 -1
View File
@@ -63,7 +63,8 @@ MCP server. The control port listens on loopback only, with a token per process.
- **The models agy offers**: the list follows the model option agy advertises
in the ACP session. A model `agy models` lists but the session does not offer
this client (agy may keep Claude and GPT-OSS for clients it recognises) is
left out, and before the first session only Gemini is listed.
left out. To list models, the plugin opens one session with `agy acp` (no
prompt is sent) and reads what it offers; until it has, only Gemini is listed.
Models and thinking levels can be switched mid-conversation without losing
history.
- **Streaming with thought summaries**: summaries come back as `thinking` blocks.
+2 -1
View File
@@ -48,7 +48,8 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy
- **agy 开放的模型**:模型列表以 ACP 会话里 agy 给出的模型选项为准。`agy models` 列出的
模型如果没有在会话里向本客户端开放(agy 可能只向它认可的客户端开放 Claude、GPT-OSS),
就不会出现在列表里;第一个会话建立之前只列 Gemini。模型和思考等级可以在会话中切换,
就不会出现在列表里。列模型时插件会先用 `agy acp` 开一个会话(不发 prompt)问 agy 开放了哪些,
问到之前只列 Gemini。模型和思考等级可以在会话中切换,
历史保留。
- **流式输出与思考摘要**:思考摘要以 `thinking` 块返回,设置 `AGY_BRIDGE_THINKING=0` 可关闭。
- **图片输入**:支持内联 base64 的 PNG、JPEG、GIF、WebP。需要 agy 1.5.0 或更新版本,
+93 -3
View File
@@ -276,6 +276,79 @@ function offeredFilter(list) {
(modelFamilyId(model) && acpOfferedModels.has(modelFamilyId(model)))))
}
// Before any request has opened a session, ask agy itself: a short `agy acp`
// that opens a session (no prompt) and reads what it offers, so the catalog
// lists Claude and GPT-OSS without a Gemini request first. Approach from
// yulong-ge's antigravity-official-acp (#854).
const OFFERED_PROBE_TIMEOUT_MS = 30_000
const OFFERED_PROBE_RETRY_MS = 60_000
let offeredProbePromise = null
let offeredProbeAt = null
function killQuietly(child) {
try { child.stdin?.end() } catch {}
if (child.exitCode !== null || child.signalCode !== null) return
if (process.platform === "win32" && child.pid) {
execOnce("taskkill", ["/T", "/F", "/PID", String(child.pid)], { timeoutMs: 3_000, unrefTimer: true }).catch(() => {})
} else {
try { child.kill("SIGTERM") } catch {}
}
}
async function probeOfferedModels(agyPath) {
let workspace = null
let child = null
let conn = null
let timer
try {
workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-models-"))
child = spawnAgy(agyPath, ["acp"], { cwd: workspace, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
child.on("error", () => conn?.close(new Error("agy acp failed to start")))
child.on("close", () => conn?.close(new Error("agy acp exited")))
child.stdin?.on("error", () => {})
child.stderr?.resume?.()
conn = new AcpConnection(child, {
onNotification: () => {},
onRequest: async (method) => { throw Object.assign(new Error(`not served: ${method}`), { code: -32601 }) },
onProtocolError: (error) => conn.close(error),
})
const deadline = new Promise((_resolve, reject) => {
timer = setTimeout(() => reject(new Error("agy acp model probe timed out")), OFFERED_PROBE_TIMEOUT_MS)
timer.unref?.()
})
await Promise.race([deadline, (async () => {
const init = await conn.request("initialize", {
protocolVersion: 1,
clientInfo: CLIENT_INFO,
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
})
if (agyTooOld(init?.agentInfo?.version ?? null)) return
const session = await conn.request("session/new", { cwd: workspace, mcpServers: [] })
noteOfferedModels(session?.configOptions, session?.models)
const caps = init?.agentCapabilities ?? {}
if (session?.sessionId && (caps.sessionCapabilities?.close ?? caps.session_capabilities?.close)) {
await conn.request("session/close", { sessionId: session.sessionId }).catch(() => {})
}
})()])
} catch {
// Unknown: keep serving Gemini only, and try again later.
} finally {
clearTimeout(timer)
conn?.close(new Error("probe done"))
if (child) killQuietly(child)
if (workspace) fs.promises.rm(workspace, { recursive: true, force: true }).catch(() => {})
}
}
function probeOfferedOnce(agyPath) {
if (acpOfferedModels || offeredProbePromise) return offeredProbePromise
const now = Date.now()
if (offeredProbeAt !== null && now - offeredProbeAt < OFFERED_PROBE_RETRY_MS) return null
offeredProbeAt = now
offeredProbePromise = probeOfferedModels(agyPath).finally(() => { offeredProbePromise = null })
return offeredProbePromise
}
function catalogOf(entry) {
if (entry.offeredKey !== acpOfferedKey || !entry.catalog) {
entry.catalog = buildModelCatalog(offeredFilter(entry.list))
@@ -353,7 +426,9 @@ function fallbackModelCatalog(agyPath = null) {
// Magpie gives models() about two seconds, while `agy models` can take longer.
// Serve the last catalog (static until the first success), refresh it in the
// background at most once at a time, and wait for that refresh only briefly.
async function loadModelCatalog(agyPath) {
// probeOffered: the caller is listing models (provider.models), not routing a
// request that is about to open a session of its own.
async function loadModelCatalog(agyPath, { probeOffered = false } = {}) {
if (cachedModelCatalog.agyPath !== agyPath) {
// An old executable's dynamic additions must not route to a new one.
cachedModelCatalog = fallbackModelCatalog(agyPath)
@@ -362,7 +437,11 @@ async function loadModelCatalog(agyPath) {
const current = cachedModelCatalog
if (!agyPath) return catalogOf(current)
const now = Date.now()
if (!current.isFallback && now - current.fetchedAt < MODEL_CATALOG_TTL_MS) return catalogOf(current)
if (!current.isFallback && now - current.fetchedAt < MODEL_CATALOG_TTL_MS) {
// A signed-in agy whose offer is unknown yet is asked in the background.
if (probeOffered) probeOfferedOnce(agyPath)
return catalogOf(current)
}
if (!modelCatalogRefreshPromise &&
(current.lastAttemptAt === null || now - current.lastAttemptAt >= MODEL_CATALOG_RETRY_MS)) {
current.lastAttemptAt = now
@@ -396,6 +475,17 @@ async function loadModelCatalog(agyPath) {
clearTimeout(timer)
}
}
// `agy models` answered, so agy is signed in: learn what its ACP server
// offers this client, waiting for it as briefly as for the listing.
const probe = probeOffered && !cachedModelCatalog.isFallback ? probeOfferedOnce(agyPath) : null
if (probe) {
let timer
try {
await Promise.race([probe, new Promise((resolve) => { timer = setTimeout(resolve, MODEL_CATALOG_FAST_WAIT_MS) })])
} finally {
clearTimeout(timer)
}
}
return catalogOf(cachedModelCatalog)
}
@@ -4256,7 +4346,7 @@ export const AntigravityBridgePlugin = async () => {
models: async () => {
const agy = findAgy()
// Never force a refresh here: Magpie times models() out after about two seconds.
const catalog = await loadModelCatalog(agy)
const catalog = await loadModelCatalog(agy, { probeOffered: true })
const out = {}
for (const model of catalog.models) {
const imageModel = /^(?:gemini-|claude-)/.test(model.id)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-agy-cli-auth",
"version": "0.1.1",
"version": "0.1.2",
"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",
+53 -9
View File
@@ -84,20 +84,14 @@ test("首次快速成功时直接拿到动态目录", async () => {
})
})
test("会话开放的型号才列出:Claude、GPT-OSS 和 agy models 没列的型号随会话出现", async () => {
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))
await kit.models()
await settle(kit)
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 })
@@ -107,6 +101,56 @@ test("会话开放的型号才列出:Claude、GPT-OSS 和 agy models 没列的
assert.equal(after["gemini-3.8-flash"], undefined, "会话没开放的 Gemini 也不应列出")
assert.equal(after["mystery-model"], undefined)
assert.ok(after["gemini-4-argon"])
// 探测只开会话、不发 prompt,用插件自己的名字,进程跑完就关。
assert.equal(kit.acpLog.filter(entry => entry.method === "session/prompt").length, 0, "探测不应发 prompt")
assert.equal(kit.acpLog.filter(entry => entry.method === "session/new").length, 1)
assert.equal(kit.acpLog.find(entry => entry.method === "initialize")?.params?.clientInfo?.name, "opencode-agy-cli-auth")
assert.deepEqual(kit.acpSpawns.map(spawn => spawn.args), [["acp"]])
assert.equal(kit.children.size, 0, "探测的 agy acp 应已退出")
// 已知开放什么之后不再探测。
kit.clock.advance(CATALOG_TTL_MS)
await kit.models()
await settle(kit)
assert.equal(kit.acpSpawns.length, 1)
})
})
test("探测会话失败(agy 要求登录)时只列 Gemini,限流后再试,成功即列出", async () => {
await withKit({ modelsBehavior: DYNAMIC_OK, sessionNewError: { code: -32000, message: "Authentication required" }, offeredModels: [
["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["claude-opus-5-5-high", "Claude Opus 5.5 (High)"], ["claude-opus-5-5-low", "Claude Opus 5.5 (Low)"],
] }, async (kit) => {
await kit.models()
await settle(kit)
const failed = await kit.models()
assert.equal(failed["claude-opus-5-5"], undefined)
assert.ok(failed["gemini-4-argon"])
assert.equal(kit.children.size, 0, "失败的探测也应关掉 agy acp")
assert.equal(kit.acpSpawns.length, 1, "一分钟内不再探测")
kit.sessionNewError = null
kit.clock.advance(60_000)
await kit.models()
// 新鲜目录不等探测:等它起来并跑完。
for (let i = 0; i < 200 && kit.acpSpawns.length < 2; i++) await sleep(5)
await settle(kit)
assert.equal(kit.acpSpawns.length, 2)
const listed = await kit.models()
assert.deepEqual(Object.keys(listed["claude-opus-5-5"]?.variants ?? {}).sort(), ["high", "low"])
})
})
test("会话后来开放的型号变了,目录随之更新", async () => {
await withKit({ modelsBehavior: DYNAMIC_OK, offeredModels: [["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["gemini-4-argon-low", "Gemini 4 Argon (Low)"]] }, async (kit) => {
await kit.models()
await settle(kit)
assert.equal((await kit.models())["claude-opus-5-5"], undefined)
kit.offeredModels = [["gemini-4-argon-high", "Gemini 4 Argon (High)"], ["claude-opus-5-5-high", "Claude Opus 5.5 (High)"], ["claude-opus-5-5-low", "Claude Opus 5.5 (Low)"]]
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))
assert.ok((await kit.models())["claude-opus-5-5"])
})
})
+4 -2
View File
@@ -614,7 +614,7 @@ const legacyModel = "agy-cli/gemini-test-low"
process.env.AGY_PATH = probeWrapper
const probesBefore = logs().filter(event => event.type === "models").length
let models = {}
for (let attempt = 0; attempt < 50 && !models["gemini-test"]; attempt++) {
for (let attempt = 0; attempt < 50 && !(models["gemini-test"] && models["claude-test-medium"]); attempt++) {
if (attempt) await new Promise(resolve => setTimeout(resolve, 100))
models = await plugin.provider.models()
}
@@ -628,7 +628,9 @@ const legacyModel = "agy-cli/gemini-test-low"
check("grouped model declares sorted variants", Object.keys(models["gemini-test"]?.variants || {}).join(",") === "low,medium,high")
check("grouped model declares Magpie and OpenCode reasoning", models["gemini-test"]?.capabilities?.reasoning === true && models["gemini-test"]?.reasoning === true)
check("Gemini models expose image input to the host", models["gemini-test"]?.capabilities?.input?.image === true)
check("before any session offers it, a non-Gemini model agy lists is not served", !models["claude-test-medium"], Object.keys(models).join(","))
// Listing asks agy's ACP server what it offers this client (a session, no
// prompt), so a non-Gemini model it offers is served before any request.
check("listing models learns what agy's ACP server offers, before any request", !!models["claude-test-medium"], Object.keys(models).join(","))
process.env.AGY_PATH = wrapper
// The original executable gets its own fresh catalog before later requests route on it.
for (let attempt = 0; attempt < 50 && !(await plugin.provider.models())["gemini-test"]; attempt++) {
+7 -1
View File
@@ -238,9 +238,14 @@ class FakeAgy {
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.kit.sessionNewError) {
// Real agy 1.5.3 not signed in: {"code":-32000,"message":"Authentication required"}.
this.send({ id, error: this.kit.sessionNewError })
} else if (method === "session/new") {
this.sessionId = `fake-session-${++this.kit.sessionSerial}`
this.control({ kind: "list" })
// Only the bridge's own processes carry a control token; the catalog's
// model probe runs agy without one, as real agy does without --ide-mcp-port.
if (this.token) 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 }))
@@ -398,6 +403,7 @@ export async function createBridgeKit(options = {}) {
sessionSerial: 0,
initialAgyModel: options.initialAgyModel ?? "gemini-3.8-flash-low",
offeredModels: options.offeredModels ?? null,
sessionNewError: options.sessionNewError ?? null,
agentVersion: options.agentVersion ?? "1.5.0",
setModels: [],
acpLog: [],