diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index 379fec6..e11706c 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -219,6 +219,13 @@ client's system prompt is added to it: in the session when agy advertises `systemPrompt.append`, otherwise as `` at the start of the first prompt. +Antigravity answers a 429 "Resource has been exhausted" to a few system +prompt lines whatever quota is left (Claude Code's billing line, the Claude +Agent SDK, Codex and Hermes Agent identities, oh-my-pi's RFC 2119 line). The +plugin breaks each of them up with zero-width spaces before agy sends it, as +the Antigravity provider does (`cloak.mjs`). Should such a 429 still come +back, it is reported as a 400 about the prompt, not as a quota. + 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 diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index 4ce3c3f..39c44d1 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -169,6 +169,11 @@ magpie quota refresh agy-cli --json 支持 `systemPrompt.append` 时放进会话,否则作为 `` 放在 第一条提示词开头)。 +Antigravity 对几行系统提示词(Claude Code 的计费行、Claude Agent SDK、Codex 和 Hermes Agent +的身份句、oh-my-pi 的 RFC 2119 行)不论余量多少都回 429 "Resource has been exhausted"。插件在 +agy 发出之前用零宽空格把这几行拆开,和 Antigravity 提供商的做法一样(`cloak.mjs`)。如果仍然 +回了这样的 429,会报成针对提示词的 400,而不是额度用完。 + 设为 `1` 后,临时 agent 带上 `excludeDefaultComponents: true`:发往上游的请求里不再有 agy 自己的系统提示词,只剩插件的一行工具说明和客户端的系统提示词(同样以上面两种方式之一 发送)。原作者实测每次模型调用的输入从约 8,400 token 降到约 500 token。代价是上游看到的 diff --git a/packages/agy-cli/cloak.mjs b/packages/agy-cli/cloak.mjs new file mode 100644 index 0000000..f4bd3ee --- /dev/null +++ b/packages/agy-cli/cloak.mjs @@ -0,0 +1,79 @@ +// System prompt lines Antigravity turns away, the same list and the same +// break-up as packages/antigravity/index.mjs (TURNED_AWAY, breakUp, cloak, +// hint). Each package ships on its own, so the code is a copy; cloak.test.mjs +// fails when the two give a different answer for any line. +// +// Antigravity answers a 429 "Resource has been exhausted" to a request whose +// system prompt has one of these lines, whatever quota is left, and lets the +// same prompt through with a zero-width space after the first and second +// character of each word. agy-cli hands the client's system prompt to agy +// (session instructions, or in the prompt), +// and agy sends it to Antigravity as written, so it is broken up here before +// it goes. What the bridge keys sessions on (instructionsIdentity) is the +// prompt as the client wrote it. + +// TURNED_AWAY are the lines, lower-cased. +export const TURNED_AWAY = [ + "x-anthropic-billing-header:", + "built on anthropic's claude agent sdk", + "you are codex, an agent based on gpt-5", + "you are codex, a coding agent based on gpt-5", + "hermes agent, an intelligent ai assistant created by nous research", + "rfc 2119 keywords: must, required, should, recommended, may, optional.", +] + +const ZW = "​" + +export function turnsAway(system) { + const low = String(system ?? "").toLowerCase() + return TURNED_AWAY.some((l) => low.includes(l)) +} + +const asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase()) + +// breakUp puts a zero-width space after the first and after the second +// character of every run of three or more letters or digits in a line. +// One after the first letter only stopped working on 11-11. +const breakUp = (line) => line.replace(/[A-Za-z0-9]{3,}/g, (w) => w[0] + ZW + w[1] + ZW + w.slice(2)) + +export function cloak(system) { + if (typeof system !== "string" || !turnsAway(system)) return system + const low = asciiLower(system) + const at = [] + for (const line of TURNED_AWAY) { + for (let i = 0; ; ) { + const j = low.indexOf(line, i) + if (j < 0) break + at.push([j, j + line.length]) + i = j + line.length + } + } + at.sort((a, b) => a[0] - b[0]) + let out = "" + let prev = 0 + for (const [from, to] of at) { + if (from < prev) continue + out += system.slice(prev, from) + breakUp(system.slice(from, to)) + prev = to + } + return out + system.slice(prev) +} + +const HINT = + "Antigravity answers this 429 to the system prompt of Claude Code and the Claude Agent SDK (Claude Desktop's chats) whatever quota is left, so it is not a quota and waiting won't help; use another provider for these chats, or put one after Antigravity in a routing group" + +const CODEX_HINT = + "Antigravity answers this 429 to Codex's own system prompt for GPT-5 models whatever quota is left, so it is not a quota and waiting won't help; a Codex chat begun on a GPT model keeps that prompt after a model switch or a fork, so start a new chat on this model" +const HERMES_HINT = + "Antigravity answers this 429 to Hermes Agent's earlier default persona (its SOUL.md) whatever quota is left, so it is not a quota and waiting won't help; Hermes' current default persona goes through, so put it in SOUL.md, or use another provider for these chats" + +const RFC_HINT = + "Antigravity answers this 429 to the line \"RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.\" that starts oh-my-pi (omp)'s system prompt, and to any prompt that has it, whatever quota is left, so it is not a quota and waiting won't help; magpie breaks that line up before it goes, so this one came from a copy of it that was worded another way" + +export function hint(system) { + const low = String(system ?? "").toLowerCase() + if (low.includes("rfc 2119 keywords: must, required, should, recommended, may, optional.")) return RFC_HINT + if (low.includes("you are codex, an agent based on gpt-5") || low.includes("you are codex, a coding agent based on gpt-5")) return CODEX_HINT + if (low.includes("hermes agent, an intelligent ai assistant created by nous research")) return HERMES_HINT + return HINT +} diff --git a/packages/agy-cli/cloak.test.mjs b/packages/agy-cli/cloak.test.mjs new file mode 100644 index 0000000..5fbfa68 --- /dev/null +++ b/packages/agy-cli/cloak.test.mjs @@ -0,0 +1,48 @@ +// cloak.mjs is a copy of packages/antigravity's TURNED_AWAY, cloak and hint +// (#980): these fail when the two packages stop agreeing. +import { expect, test } from "bun:test" +import { TURNED_AWAY, cloak, hint, turnsAway } from "./cloak.mjs" +import { _internal as antigravity } from "../antigravity/index.mjs" + +const ZW = "​" + +const samples = [ + "x-anthropic-billing-header: cc_version=2.1.0.abc; cc_entrypoint=cli; cch=1a2b3;", + "You are a Claude agent, built on Anthropic's Claude Agent SDK.", + "You are Codex, an agent based on GPT-5. You are running as a coding agent.", + "You are Codex, a coding agent based on GPT-5.", + "You are Hermes Agent, an intelligent AI assistant created by Nous Research.", + "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.\n\nYou are omp.", + "Two: RFC 2119 KEYWORDS: must, required, should, recommended, may, optional. and x-anthropic-billing-header: x", + "Nothing to see here; Claude Agent SDK alone is fine.", + "", +] + +test("every turned-away line is broken up, and the model still reads it", () => { + for (const s of samples) { + const out = cloak(s) + expect(out.replaceAll(ZW, "")).toBe(s) + if (turnsAway(s)) { + expect(out).not.toBe(s) + expect(turnsAway(out)).toBe(false) + } else { + expect(out).toBe(s) + } + } + expect(cloak("RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.")).toBe( + `R${ZW}F${ZW}C 2${ZW}1${ZW}19 k${ZW}e${ZW}ywords: M${ZW}U${ZW}ST, R${ZW}E${ZW}QUIRED, S${ZW}H${ZW}OULD, R${ZW}E${ZW}COMMENDED, M${ZW}A${ZW}Y, O${ZW}P${ZW}TIONAL.`, + ) +}) + +test("agy-cli and antigravity break up and explain the same lines", () => { + for (const line of TURNED_AWAY) { + expect(antigravity.turnsAway(line)).toBe(true) + expect(cloak(line)).toBe(antigravity.cloak(line)) + expect(hint(line)).toBe(antigravity.hint(line)) + } + for (const s of samples) { + expect(turnsAway(s)).toBe(antigravity.turnsAway(s)) + expect(cloak(s)).toBe(antigravity.cloak(s)) + expect(hint(s)).toBe(antigravity.hint(s)) + } +}) diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 68d606c..2334479 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -11,6 +11,7 @@ import { createUsageReader } from "./usage.mjs" import { sanitizePatternFields } from "./re2-pattern.mjs" import { startLogin } from "./login.mjs" import { ensureGeminiArrayItems } from "./array-items.mjs" +import { cloak, hint, turnsAway } from "./cloak.mjs" const PROVIDER_ID = "agy-cli" // Client tools reach the session through a private `nc` placed first on agy's @@ -1218,7 +1219,7 @@ class Proc { const resumable = !!(capabilities.sessionCapabilities?.resume ?? capabilities.session_capabilities?.resume) this.instructionsInSession = appendable && !!this.instructions const meta = this.instructionsInSession - ? { _meta: { antigravity: { systemPrompt: { append: this.instructions } } } } + ? { _meta: { antigravity: { systemPrompt: { append: cloak(this.instructions) } } } } : {} let session = null @@ -1559,6 +1560,15 @@ class Proc { } #formatAgentError(detail) { + // The system prompt turned away, not a quota (cloak.mjs): a 400 the next + // member of a group is asked after, and the client doesn't retry. It says + // what Antigravity answered (a 429). + if (/code 429\b/i.test(detail) && /resource has been exhausted/i.test(detail) && turnsAway(this.instructions)) { + return new AgentTurnError( + `agy bridge: Antigravity answered 429 to this system prompt: ${detail} — ${hint(this.instructions)}`, + "invalid_request_error", + ) + } if (/QUOTA_EXHAUSTED|RESOURCE_EXHAUSTED|MODEL_CAPACITY_EXHAUSTED|code 429\b/i.test(detail)) { return new AgentTurnError( `agy bridge: Antigravity quota or rate limit reached${detail ? ": " + detail : ""}`, @@ -3496,7 +3506,9 @@ function renderTurnMessage(message) { function renderTurnMessageParts(message) { if (message.role !== "user" || !Array.isArray(message.content)) { - const text = renderTurnMessage(message) + let text = renderTurnMessage(message) + // a system or developer message later in the chat is system text too + if (message.role === "system" || message.role === "developer") text = cloak(text) return text === "" ? [] : [{ type: "text", text }] } const parts = [] @@ -3657,7 +3669,7 @@ function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, re const head = [] if (!instructionsInSession) { const system = systemText(body) - if (system.trim()) appendPrompt(head, `\n${system}\n\n`) + if (system.trim()) appendPrompt(head, `\n${cloak(system)}\n\n`) if (callerWorkDir) appendPrompt(head, `\n${workDirNote(callerWorkDir)}\n\n`) } const currentParts = renderTurnMessagesParts(current) @@ -3988,7 +4000,7 @@ function inspectToolTurn(results, body) { if (extractQueuedPrompt(rest) !== null || userInterruption.test(rest)) { userSteered = true } else if (!isNoise(rest)) { - notices.push(rest) + notices.push(cloak(rest)) } } else if (!isNoise(rest)) { if ((hookOutput.test(rest) || claudeMetaFeedback.test(rest)) && !userInterruption.test(rest)) { diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index d401f00..aefec04 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.17", + "version": "0.1.18", "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", @@ -20,7 +20,8 @@ "LICENSE", "NOTICE.md", "re2-pattern.mjs", - "array-items.mjs" + "array-items.mjs", + "cloak.mjs" ], "keywords": [ "magpie", diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index 7bac933..ac3f604 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -217,6 +217,11 @@ async function prompt(params) { log({ type: "agentError", convId: session.id }) return { stopReason: "end_turn" } } + if (text.includes("TURNED429")) { + fs.appendFileSync(agentLog, "E1111 09:12:01.000000 685 errorreport.go:224] agent executor error: generating and executing: RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n") + chunk("\n⚠ Agent execution terminated due to error.\n") + return { stopReason: "end_turn" } + } if (text.includes("QUOTA")) { fs.appendFileSync(agentLog, "E1103 17:11:25.570096 685 errorreport.go:224] agent executor error: generating and executing: RESOURCE_EXHAUSTED (code 429): quota exhausted.\n") chunk("\n⚠ Agent execution ") @@ -378,7 +383,7 @@ async function handle(message) { loadSession: true, ...(process.env.FAKE_AGY_IMAGES === "omit" ? {} : { promptCapabilities: { image: process.env.FAKE_AGY_IMAGES !== "0", audio: false, embeddedContext: true } }), sessionCapabilities: { resume: {}, close: {} }, - _meta: { antigravity: { systemPrompt: { append: true } } }, + ...(process.env.FAKE_AGY_APPEND === "0" ? {} : { _meta: { antigravity: { systemPrompt: { append: true } } } }), }, agentInfo: { name: "Antigravity ACP Server", version: process.env.FAKE_AGY_IMAGES === "omit" ? "1.4.12" : "1.5.0" }, authMethods: [], @@ -1222,6 +1227,59 @@ for (const change of ["tools", "model"]) { check("split error marker and quota map to rate_limit_error", error?.type === "rate_limit_error" && error.message.includes("quota exhausted") && textOf(events) === "", JSON.stringify({ error, text: textOf(events) })) } +// #980: the system lines Antigravity turns away are broken up before agy +// sends them, in the session instructions, in the prompt when agy can't take +// them, and in a later system message; a 429 to such a prompt is not a quota. +{ + const zw = "\u200b" + const rfc = "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL." + const sdk = "You are a Claude agent, built on Anthropic's Claude Agent SDK." + const system = `${rfc}\nx-anthropic-billing-header: cc_version=2.1.0; cch=1;\n${sdk}\nCLOAK-MARKER` + const plain = (text) => String(text ?? "").replaceAll(zw, "") + const body = { model, system, messages: [{ role: "user", content: "cloak session instructions" }] } + const events = (await readSSE(await callFetch(body))).events + const init = inits().at(-1) + const sent = init.systemAppend ?? "" + check("#980 a turned-away line is broken up in the session instructions", + sent.includes("CLOAK-MARKER") && !sent.includes(rfc) && !sent.includes("x-anthropic-billing-header") && !sent.includes("Claude Agent SDK") && + sent.includes("R" + zw + "F" + zw + "C 2" + zw + "1" + zw + "19") && sent.includes("C" + zw + "l" + zw + "aude A" + zw + "g" + zw + "ent S" + zw + "D" + zw + "K") && + plain(sent).includes(system), JSON.stringify(sent)) + const convId = init.convId + const before = inits().length + await readSSE(await callFetch(nextTurn(body, events, "cloak second turn"))) + check("#980 the broken-up instructions keep the conversation in its session", inits().length === before && lastOf("user").convId === convId, + JSON.stringify({ inits: inits().length - before, user: lastOf("user") })) + + const later = { model, system: "CLOAK-LATER", messages: [{ role: "user", content: "cloak later system" }] } + const laterEvents = (await readSSE(await callFetch(later))).events + const next = nextTurn(later, laterEvents, "after the system note") + next.messages.splice(next.messages.length - 1, 0, { role: "system", content: sdk }) + await readSSE(await callFetch(next)) + const laterText = lastOf("user").text + check("#980 a later system message is broken up too", !laterText.includes("Claude Agent SDK") && plain(laterText).includes(sdk), JSON.stringify(laterText)) + + const user = { model, system: "CLOAK-USER", messages: [{ role: "user", content: `user wrote ${sdk}` }] } + await readSSE(await callFetch(user)) + check("#980 what the user wrote goes as written", lastOf("user").text.includes(sdk), JSON.stringify(lastOf("user").text)) + + process.env.FAKE_AGY_APPEND = "0" + await readSSE(await callFetch({ model, system: system + " NOAPPEND", messages: [{ role: "user", content: "cloak in the prompt" }] })) + const prompted = lastOf("user").text + check("#980 a turned-away line is broken up in ", + inits().at(-1).systemAppend === null && prompted.includes("") && prompted.includes("CLOAK-MARKER") && + !prompted.includes(rfc) && !prompted.includes("Claude Agent SDK") && plain(prompted).includes(system), JSON.stringify(prompted)) + delete process.env.FAKE_AGY_APPEND + + const turned = (await readSSE(await callFetch({ model, system: system + " T429", messages: [{ role: "user", content: "TURNED429 please" }] }))).events + const turnedError = turned.find(event => event.event === "error")?.data?.error + check("#980 a 429 to a turned-away prompt is a prompt rejection, not a quota", + turnedError?.type === "invalid_request_error" && turnedError.message.includes("answered 429 to this system prompt") && + turnedError.message.includes("RFC 2119") && !/quota or rate limit reached/.test(turnedError.message), JSON.stringify(turnedError)) + const quota = (await readSSE(await callFetch({ model, system: "CLOAK-QUOTA", messages: [{ role: "user", content: "TURNED429 plain" }] }))).events + const quotaError = quota.find(event => event.event === "error")?.data?.error + check("#980 the same 429 to any other prompt is still a rate limit", quotaError?.type === "rate_limit_error", JSON.stringify(quotaError)) +} + { process.env.AGY_BRIDGE_START_TIMEOUT_MS = "40" process.env.FAKE_AGY_INIT_MODE = "slow" @@ -1618,6 +1676,7 @@ for (const location of ["inline", "system", "developer", "user"]) { { type: "text", text: "tool.call hook additional context: lowercase-hook-context" }, { type: "text", text: "PostToolUse:Bash hook additional context: hook-head\n\n# Environment update\n - Primary working directory: /remote-wsl/project/subdir" }, { type: "text", text: "The user hasn't heard from you in a while." }, + { type: "text", text: "You are Codex, a coding agent based on GPT-5." }, ], }) const response = await callFetch(second) @@ -1634,6 +1693,9 @@ for (const location of ["inline", "system", "developer", "user"]) { mcpText.includes("# Environment update") && mcpText.includes("hasn't heard from you") && !mcpText.includes("hook success: Success"), mcpText) + check("#980 a turned-away line in a system notice beside a tool result is broken up", + !mcpText.includes("You are Codex, a coding agent based on GPT-5") && + mcpText.replaceAll("\u200b", "").includes("You are Codex, a coding agent based on GPT-5."), mcpText) } { diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index bd48216..db9bad0 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -32,6 +32,7 @@ export const INDEX_FILE = process.env.AGY_BRIDGE_TEST_INDEX || path.join(REPO_DI export const USAGE_FILE = path.join(REPO_DIR, "usage.mjs") export const PLATFORM_FILE = path.join(REPO_DIR, "platform.mjs") export const ARRAY_ITEMS_FILE = path.join(REPO_DIR, "array-items.mjs") +export const CLOAK_FILE = path.join(REPO_DIR, "cloak.mjs") export const LOGIN_FILE = path.join(REPO_DIR, "login.mjs") export const RE2_PATTERN_FILE = path.join(REPO_DIR, "re2-pattern.mjs") export const MESSAGES_URL = "agy://local/v1/messages" @@ -489,6 +490,7 @@ export async function createBridgeKit(options = {}) { const usageUrl = pathToFileURL(USAGE_FILE).href const platformUrl = pathToFileURL(PLATFORM_FILE).href const arrayItemsUrl = pathToFileURL(ARRAY_ITEMS_FILE).href + const cloakUrl = pathToFileURL(CLOAK_FILE).href const loginUrl = pathToFileURL(LOGIN_FILE).href const re2Url = pathToFileURL(RE2_PATTERN_FILE).href const linker = (specifier) => { @@ -500,6 +502,7 @@ export async function createBridgeKit(options = {}) { if (key === "./usage.mjs") module = sourceModule(USAGE_FILE, "", usageUrl) else if (key === "./platform.mjs") module = sourceModule(PLATFORM_FILE, "", platformUrl) else if (key === "./array-items.mjs") module = sourceModule(ARRAY_ITEMS_FILE, "", arrayItemsUrl) + else if (key === "./cloak.mjs") module = sourceModule(CLOAK_FILE, "", cloakUrl) else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl) else if (key === "./re2-pattern.mjs") module = sourceModule(RE2_PATTERN_FILE, "", re2Url) else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])