diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index 45fe60e..3353f3b 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -253,6 +253,7 @@ usage reads wait 10 minutes before the next try, doubling up to 6 hours. | `AGY_BRIDGE_MINIMAL_AGENT` | off | Set to `1` to drop agy's own prompt components; see "Minimal agent" below | | `AGY_BRIDGE_SYSTEM_APPEND` | off | Set to `1` to append the client's system prompt to agy's own instead of putting it in the first prompt; see below | | `AGY_BRIDGE_IDLE_MS` | 600000 | How long a process may sit idle before it is reclaimed; the session can still resume | +| `AGY_BRIDGE_SPARE` | on | Keeps one spare agy per account, started but with no session and no request sent, so a new conversation skips agy's start; set to `0` to turn it off | | `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 | diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index 082e2a4..a8a52e2 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -184,6 +184,7 @@ agy 的拒绝原因,不显示数字。 | `AGY_BRIDGE_MINIMAL_AGENT` | 关闭 | 设为 `1` 去掉 agy 自带的提示组件,见下文「精简 agent」 | | `AGY_BRIDGE_SYSTEM_APPEND` | 关闭 | 设为 `1` 把客户端的系统提示词附加到 agy 自己的系统提示词后面,而不是放进第一条提示词,见下文 | | `AGY_BRIDGE_IDLE_MS` | 600000 | 进程空闲多久后回收(会话仍可续接) | +| `AGY_BRIDGE_SPARE` | 开启 | 每个账号预先启动一个备用 agy(只启动、不建会话,不发任何请求),新对话直接用它,省掉 agy 的启动时间;设为 `0` 关闭 | | `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" | diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 5a10a2b..875dcb8 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -29,6 +29,7 @@ for (const [name, mocks] of [ ["repeat-batch.mjs", false], ["conversation-key.mjs", false], ["windows-nc.mjs", false], + ["spare.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 29afde8..da783c8 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -1,4 +1,4 @@ -import { agyCandidates, spawnAgy, windowsMcpShim, windowsNcBuild, windowsTreeKill } from "./platform.mjs" +import { agyCandidates, childEnv, spawnAgy, windowsMcpShim, windowsNcBuild, windowsTreeKill } from "./platform.mjs" import { spawn, spawnSync } from "node:child_process" import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto" import { once } from "node:events" @@ -1739,17 +1739,9 @@ class Turn { class Proc { constructor(agyPath, convKey, opts) { this.agyPath = agyPath - this.convKey = convKey - this.model = opts.model - this.selection = opts.selection - this.tools = opts.tools - this.toolsSignature = JSON.stringify(opts.tools) + this.#assign(convKey, opts) this.workDir = opts.workDir - this.instructions = opts.instructions || "" - this.userId = opts.userId || "" - this.openingText = openingTextOf(opts.messages?.[0]) - this.openingImages = openingImagesOf(opts.messages?.[0]) - this.resumeFrom = opts.resume || null + this.spareKey = null this.token = randomUUID() this.sessionId = null this.currentModel = null @@ -1792,7 +1784,45 @@ class Proc { allProcs.add(this) } + // What a conversation sets; a spare gets it when one takes it (adopt). + #assign(convKey, opts) { + this.convKey = convKey + this.model = opts.model + this.selection = opts.selection + this.tools = opts.tools ?? [] + this.toolsSignature = JSON.stringify(this.tools) + this.instructions = opts.instructions || "" + this.userId = opts.userId || "" + this.openingText = openingTextOf(opts.messages?.[0]) + this.openingImages = openingImagesOf(opts.messages?.[0]) + this.resumeFrom = opts.resume || null + } + async start() { + await this.#spawn() + await this.#withStartTimeout(async () => { + await this.#initialize() + await this.#openSession() + }) + } + + // A spare: agy started and initialised, with no session. agy sends nothing + // to Google until session/new (it reads its sign-in then too), so a spare + // costs a process and no request. + async warm() { + await this.#spawn() + await this.#withStartTimeout(() => this.#initialize()) + } + + // A conversation takes a warmed spare and opens its session on it. + async adopt(convKey, opts) { + this.#assign(convKey, opts) + this.spareKey = null + this.lastUsed = Date.now() + await this.#withStartTimeout(() => this.#openSession()) + } + + async #spawn() { await ensureControlServer() const bin = await ensureShimDir() sessions.set(this.token, this) @@ -1856,7 +1886,11 @@ class Proc { onRequest: (method, params) => this.#onRequest(method, params), onProtocolError: (error) => this.fail(error), }) + } + async #withStartTimeout(step) { + // a spare that died while it waited + if (this.dead) throw new Error(`agy failed before the ACP session started: ${this.deadError?.message || "agy exited"}`) const timeoutMs = configuredTimeout("AGY_BRIDGE_START_TIMEOUT_MS", DEFAULT_PROC_START_TIMEOUT_MS) let timer const timeout = new Promise((_resolve, reject) => { @@ -1865,7 +1899,7 @@ class Proc { )), timeoutMs) }) try { - await Promise.race([this.#handshake(), timeout]) + await Promise.race([step(), timeout]) } catch (error) { if (this.dead && this.deadError && error !== this.deadError && !/timed out starting/.test(error.message)) { throw new Error(`agy failed before the ACP session started: ${this.deadError.message}`) @@ -1876,7 +1910,7 @@ class Proc { } } - async #handshake() { + async #initialize() { const init = await this.conn.request("initialize", { protocolVersion: 1, // The plugin's own name. agy decides which models it offers this client, @@ -1890,9 +1924,13 @@ class Proc { const capabilities = init?.agentCapabilities ?? {} this.supportsImages = capabilities.promptCapabilities?.image === true || capabilities.prompt_capabilities?.image === true - const appendable = capabilities._meta?.antigravity?.systemPrompt?.append === true - const resumable = !!(capabilities.sessionCapabilities?.resume ?? capabilities.session_capabilities?.resume) - this.instructionsInSession = appendable && systemAppend() && !!this.instructions + this.appendable = capabilities._meta?.antigravity?.systemPrompt?.append === true + this.resumable = !!(capabilities.sessionCapabilities?.resume ?? capabilities.session_capabilities?.resume) + } + + async #openSession() { + const resumable = this.resumable + this.instructionsInSession = this.appendable && systemAppend() && !!this.instructions const meta = this.instructionsInSession ? { _meta: { antigravity: { systemPrompt: { append: outgoing(this.instructions) } } } } : {} @@ -2977,6 +3015,7 @@ async function evictIdle() { } } for (const [key, proc] of victims) await retire(key, proc) + evictIdleSpares(cutoff) for (const { proc, turn, reason } of stale) { if (proc.turn !== turn || proc.retiring) continue logBridgeEvent(proc, turn, "reclaim", reason, {}, { trigger: "evict_idle" }) @@ -3016,6 +3055,85 @@ async function evictLRU() { setInterval(() => { evictIdle().catch(() => {}) }, 60_000).unref() +// A spare agy: started and initialised, with no session, so the next new +// conversation skips agy's start (spawn to initialize: ~0.25s warm, ~1s cold +// on Linux). Only the process is warmed. agy reaches no host from spawn +// through initialize and idling; session/new is where it signs in and asks +// Google for the account, models, quota and settings, and a session nobody +// uses still writes a trajectory at Google when it closes. A session is also +// opened with the conversation's own instructions. So sessions are never +// opened ahead. One spare per way of starting agy (launchKey: the account's +// home, the binary, the folder, flags and environment); idle spares go after +// IDLE_MS like the pool's processes, first when the pool needs room, and with +// the host (reapOnExit; agy also exits when its stdin closes). +// AGY_BRIDGE_SPARE=0 turns them off. +const spares = new Map() +const SPARE_MAX = 2 + +function sparesOn() { + return !/^(?:0|false|off|no|disabled)$/i.test(process.env.AGY_BRIDGE_SPARE || "") +} + +// Everything that decides how Proc starts agy for the current work. +async function launchKey(agyPath, workDir) { + let mtime = 0 + try { mtime = (await fs.promises.stat(agyPath)).mtimeMs } catch {} + const own = await geminiDirArgs(agyPath) + return digest(JSON.stringify([currentHome(), agyPath, mtime, workDir || "", + await noDefaultCustomizationsArgs(agyPath), own.args, childEnv(process.env)])) +} + +function dropSpare(spare) { + if (spares.get(spare.spareKey) === spare) spares.delete(spare.spareKey) + return spare.stop().catch(() => {}) +} + +async function takeSpare(agyPath, workDir) { + if (!spares.size || !sparesOn()) return null + const key = await launchKey(agyPath, workDir) + const spare = spares.get(key) + if (!spare) return null + spares.delete(key) + try { + await spare.ready + } catch { + return null + } + if (spare.dead || spare.stopping) { + await spare.stop().catch(() => {}) + return null + } + return spare +} + +async function warmSpare(agyPath, workDir) { + if (!agyPath || !sparesOn()) return + const key = await launchKey(agyPath, workDir) + if (spares.has(key)) return + // never at the cost of a conversation's room + if (allProcs.size + 1 >= maxProcs()) return + if (spares.size >= SPARE_MAX) { + let oldest = null + for (const spare of spares.values()) if (!oldest || spare.lastUsed < oldest.lastUsed) oldest = spare + await dropSpare(oldest) + } + if (spares.has(key) || allProcs.size + 1 >= maxProcs()) return + const proc = new Proc(agyPath, null, { workDir }) + proc.spareKey = key + spares.set(key, proc) + proc.ready = proc.warm().catch(async (error) => { + await dropSpare(proc) + throw error + }) + proc.ready.catch(() => {}) +} + +function evictIdleSpares(cutoff) { + for (const spare of [...spares.values()]) { + if (spare.dead || spare.lastUsed < cutoff) dropSpare(spare) + } +} + const acquireLocks = new Map() async function withAcquireLock(key, fn) { @@ -3152,24 +3270,33 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo dropFromPool(existing) await existing.stop().catch(() => {}) } - while (allProcs.size >= maxProcs()) { + const spare = await takeSpare(agyPath, opts.workDir) + while (!spare && allProcs.size >= maxProcs()) { + const idle = spares.values().next().value + if (idle) { + await dropSpare(idle) + continue + } if (!(await evictLRU())) { throw new BusyError(`agy bridge: ${maxProcs()} agy processes are running and all have unfinished responses`) } } const resume = forceNew || isFreshConversation ? null : takeParked(convKey, opts) - const proc = new Proc(agyPath, key, { ...opts, resume }) + const proc = spare ?? new Proc(agyPath, key, { ...opts, resume }) try { - await proc.start() + if (spare) await spare.adopt(key, { ...opts, resume }) + else await proc.start() } catch (error) { await proc.stop().catch(() => {}) throw error } pool.set(key, proc) + // the next new conversation of this account and folder takes one ready + warmSpare(agyPath, opts.workDir).catch(() => {}) // Why this request got a new agy session, so a cache that never hits can be // traced to the check that failed (#1058). Counts only, never content. logSessionEvent(proc, why, { - fresh: !!isFreshConversation, resumed: !!proc.resumed, + fresh: !!isFreshConversation, resumed: !!proc.resumed, spare: !!spare, parked: !!resume, history: Array.isArray(opts.history) ? opts.history.length : null, }) return { proc, history: opts.history } diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 821eded..63221f8 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.70", + "version": "0.1.71", "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", diff --git a/packages/agy-cli/test/spare.mjs b/packages/agy-cli/test/spare.mjs new file mode 100644 index 0000000..8f40b1d --- /dev/null +++ b/packages/agy-cli/test/spare.mjs @@ -0,0 +1,148 @@ +// A spare agy: the next new conversation takes an agy already started and +// initialised (no session), so it skips agy's start. Sessions are never opened +// ahead: agy asks Google for the account at session/new. +// +// bun test ./spare.mjs + +import { test } from "node:test" +import assert from "node:assert/strict" +import { MESSAGES_URL, baseBody, createBridgeKit, readSse, sleep } from "./testkit.mjs" + +const SPARE_ON = { AGY_BRIDGE_SPARE: "1" } + +async function withKit(options, fn) { + const kit = await createBridgeKit({ ...options, env: { ...SPARE_ON, ...(options.env || {}) } }) + kit.defaultPrompt = async (agent) => { + await agent.text("hello") + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } } + } + try { + return await fn(kit) + } finally { + await kit.dispose() + } +} + +// Wait for a state, never a duration; the cap only bounds a hang. +async function until(what, check, capMs = 20_000) { + const started = Date.now() + while (!check()) { + if (Date.now() - started > capMs) throw new Error(`timed out waiting for ${what}`) + await sleep(5) + } +} + +// Time to the first streamed text of one request. +async function ttft(send) { + const started = performance.now() + const response = await send() + assert.equal(response.status, 200, await response.clone().text()) + const reader = response.body.getReader() + const decoder = new TextDecoder() + let text = "" + let first = null + for (;;) { + const { value, done } = await reader.read() + if (done) break + text += decoder.decode(value, { stream: true }) + if (first === null && text.includes("content_block_delta")) first = performance.now() - started + } + return Math.round(first) +} + +const sessionsOn = (kit) => kit.acpLog.filter((entry) => entry.method === "session/new").map((entry) => entry.spawn) +const conversation = (n) => baseBody({ system: `conversation ${n}`, messages: [{ role: "user", content: `open ${n}` }] }) + +test("a second new conversation takes the warmed agy and skips agy's start", async () => { + const INIT_MS = 1000 + await withKit({ initializeDelayMs: INIT_MS, sessionNewDelayMs: 3000 }, async (kit) => { + const first = await ttft(() => kit.request(conversation(1))) + // the spare is started after the first conversation's agy and initialised on its own + await until("a spare agy initialised", () => kit.initialized === 2) + const spawnsBefore = kit.acpSpawns.length + const second = await ttft(() => kit.request(conversation(2))) + console.log(`TTFT new conversation (agy start ${INIT_MS}ms, session/new 3000ms): first ${first}ms, second ${second}ms`) + assert.equal(spawnsBefore, 2) + // conversation 2 opened its session on the spare: spawn #1, not a new one + assert.deepEqual(sessionsOn(kit).slice(0, 2), [0, 1]) + // agy's start is gone from it; half the start is room for a loaded machine + assert.ok(second < first - INIT_MS / 2, `second ${second}ms, first ${first}ms`) + // and another spare is warmed for the conversation after + await until("the next spare", () => kit.acpSpawns.length === 3) + }) +}) + +test("a spare opens no session until a conversation takes it", async () => { + await withKit({}, async (kit) => { + await readSse(await kit.request(conversation(1))) + await until("a spare agy initialised", () => kit.initialized === 2) + assert.equal(kit.acpSpawns.length, 2) + assert.deepEqual(kit.acpLog.filter((entry) => entry.spawn === 1).map((entry) => entry.method), ["initialize"]) + }) +}) + +test("a spare belongs to its account: another account starts its own agy", async () => { + await withKit({}, async (kit) => { + await readSse(await kit.request(conversation(1))) + await until("the default account's spare", () => kit.initialized === 2) + const other = await kit.plugin.auth.loader(async () => ({ type: "oauth", metadata: { agyHome: "otheracct1" } })) + await readSse(await other.fetch(MESSAGES_URL, { method: "POST", body: JSON.stringify(conversation(2)) })) + // spawn #1 is the default account's spare; the other account opened on a new agy + assert.equal(sessionsOn(kit)[1], 2) + assert.match(kit.acpSpawns[2].env.HOME ?? "", /otheracct1$/) + assert.notEqual(kit.acpSpawns[1].env.HOME, kit.acpSpawns[2].env.HOME) + // the default account's next conversation still takes its own spare + await readSse(await kit.request(conversation(3))) + assert.equal(sessionsOn(kit)[2], 1) + }) +}) + +test("an idle spare is stopped after the idle time", async () => { + await withKit({ env: { AGY_BRIDGE_IDLE_MS: "60000" } }, async (kit) => { + await readSse(await kit.request(conversation(1))) + await until("a spare agy initialised", () => kit.initialized === 2) + const spare = kit.acpSpawns[1].child + kit.clock.advance(61_000) + // the next request sweeps idle processes before it picks one + await readSse(await kit.request(conversation(2))) + assert.equal(spare.closed, true, "the idle spare was stopped") + assert.notEqual(sessionsOn(kit)[1], 1) + }) +}) + +test("a spare is the first to go when the pool is full", async () => { + await withKit({ env: { AGY_BRIDGE_MAX_PROCS: "3" } }, async (kit) => { + await readSse(await kit.request(conversation(1))) + await until("a spare agy initialised", () => kit.initialized === 2) + const spare = kit.acpSpawns[1].child + const other = await kit.plugin.auth.loader(async () => ({ type: "oauth", metadata: { agyHome: "otheracct1" } })) + const third = await kit.plugin.auth.loader(async () => ({ type: "oauth", metadata: { agyHome: "otheracct2" } })) + await readSse(await other.fetch(MESSAGES_URL, { method: "POST", body: JSON.stringify(conversation(2)) })) + // three agy now: two conversations and the spare, so no second spare + assert.equal(kit.acpSpawns.length, 3) + await readSse(await third.fetch(MESSAGES_URL, { method: "POST", body: JSON.stringify(conversation(3)) })) + assert.equal(spare.closed, true, "the spare made room") + // both conversations kept their agy + assert.equal(kit.acpSpawns[0].child.closed, false) + assert.equal(kit.acpSpawns[2].child.closed, false) + }) +}) + +test("the host's exit stops a spare", async () => { + await withKit({}, async (kit) => { + await readSse(await kit.request(conversation(1))) + await until("a spare agy initialised", () => kit.initialized === 2) + kit.module.__agyTestReapOnExit() + assert.equal(kit.acpSpawns[1].child.closed, true) + }) +}) + +test("AGY_BRIDGE_SPARE=0 starts no spare", async () => { + await withKit({ env: { AGY_BRIDGE_SPARE: "0" } }, async (kit) => { + await readSse(await kit.request(conversation(1))) + await readSse(await kit.request(conversation(2))) + await sleep(50) + assert.equal(kit.acpSpawns.length, 2) + assert.deepEqual(sessionsOn(kit), [0, 1]) + }) +}) diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index 385d792..411f429 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -215,6 +215,7 @@ class FakeAgy { this.child = child this.env = opts?.env || {} this.token = this.env.AGY_BRIDGE_TOKEN + this.spawnIndex = kit.acpSpawns.length - 1 this.sessionId = null this.buffer = "" this.cancelWaiters = [] @@ -247,13 +248,19 @@ class FakeAgy { onMessage(message) { const { id, method, params } = message - this.kit.acpLog.push({ method, params, sessionId: this.sessionId }) + this.kit.acpLog.push({ method, params, sessionId: this.sessionId, spawn: this.spawnIndex }) if (method === "initialize") { - this.respond(id, { - protocolVersion: 1, - agentInfo: { name: "fake-agy", version: this.kit.agentVersion }, - agentCapabilities: this.kit.sessionResume ? { sessionCapabilities: { resume: {} } } : {}, - }) + const reply = () => { + this.kit.initialized++ + this.respond(id, { + protocolVersion: 1, + agentInfo: { name: "fake-agy", version: this.kit.agentVersion }, + agentCapabilities: this.kit.sessionResume ? { sessionCapabilities: { resume: {} } } : {}, + }) + } + // agy's own start: spawn to initialize is ~0.25s warm, ~1s cold on Linux + if (this.kit.initializeDelayMs) setTimeout(reply, this.kit.initializeDelayMs) + else reply() } 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 }) @@ -439,6 +446,8 @@ export async function createBridgeKit(options = {}) { sessionNewError: options.sessionNewError ?? null, setModelError: options.setModelError ?? null, sessionNewDelayMs: options.sessionNewDelayMs ?? 0, + initializeDelayMs: options.initializeDelayMs ?? 0, + initialized: 0, sessionResume: options.sessionResume ?? false, agentVersion: options.agentVersion ?? "1.5.0", setModels: [], @@ -460,6 +469,8 @@ export async function createBridgeKit(options = {}) { // agy's stored sign-in is read only when a test says what it is // (options.storedSignIn, macOS keychain output or "missing") ...(options.storedSignIn === undefined ? { AGY_BRIDGE_STORED_SIGNIN: "skip" } : {}), + // no spare agy unless a test asks: suites count spawns and ACP calls + AGY_BRIDGE_SPARE: "0", ...(options.env || {}), } for (const [key, value] of Object.entries(kit.env)) { @@ -490,7 +501,7 @@ export async function createBridgeKit(options = {}) { } if (args[0] === "acp") { const child = new FakeChild(kit, file, args) - kit.acpSpawns.push({ file, args, env: opts.env }) + kit.acpSpawns.push({ file, args, env: opts.env, child }) new FakeAgy(kit, child, opts) return child }