Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ A1–A16、U1–U6 逐项并入。两边都有、且 `acb8d84` 写法更新的
| 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)
## 4. `usage.mjs` 并入的修复与改动(U1–U7)

| 编号 | 内容 |
|---|---|
Expand All @@ -64,6 +64,7 @@ A1–A16、U1–U6 逐项并入。两边都有、且 `acb8d84` 写法更新的
| U4 | Windows 上拦截浏览器启动:写入内容为 `@exit /b 1` 的 `open.cmd`,并让 `BROWSER` 指向它 |
| U5 | PATH 大小写去重:删除非大写的 `Path` 键,继承 `env.PATH`,没有时回落到 `env.Path` |
| U6 | 临时目录删除遇到 `EBUSY`、`EPERM`、`ENOTEMPTY` 时,先等待在途的 `taskkill` 释放目录句柄,再最多重试 4 次,每次间隔递增 50 ms |
| U7 | 用量只经 agy 自己读取(`agy -p /usage`):插件不读 agy 存的登录令牌去直接请求 Google 的额度接口(`loadCodeAssist`、`retrieveUserQuotaSummary`),也不替 agy 续期令牌;Google 看到的每个额度请求都是 agy 自己发的 |

## 5. 包与文档层改动

Expand Down
143 changes: 113 additions & 30 deletions README.en.md

Large diffs are not rendered by default.

97 changes: 77 additions & 20 deletions README.md

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions agy-cli.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ for (const [name, mocks] of [
["platform.mjs", true],
["compat.mjs", true],
["prefill.mjs", false],
["images.mjs", false],
["usage.mjs", true],
["signin.mjs", false],
["catalog.mjs", false],
Expand All @@ -33,13 +34,26 @@ for (const [name, mocks] of [
["conversation-key.mjs", false],
["windows-nc.mjs", false],
["spare.mjs", false],
["account-scope.mjs", false],
["stateless-reuse.mjs", false],
["tools-listed.mjs", false],
["slash-commands.mjs", false],
["concurrent-convs.mjs", false],
["masking-drift.mjs", false],
["spilled-output.mjs", false],
["web-search.mjs", false],
["tool-result-prefill.mjs", false],
["tool-step-retry.mjs", false],
["image-bytes.mjs", false],
["dsh-replay-state.mjs", false],
["duplicate-result-notice.mjs", false],
["image-slim.mjs", false],
["transient-history.mjs", false],
["prompt-suggestion.mjs", false],
["seed-replay.mjs", false],
["session-continuity.mjs", false],
["same-opening.mjs", false],
["claude-code-sessions.mjs", false],
]) {
test(`test/${name}`, () => {
// bun's 5s default per test is a fixed wait these process-spawning tests
Expand Down
94 changes: 94 additions & 0 deletions cloak.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,100 @@ export function reword(system) {
// with USER_TURNED_AWAY's lines reworded and everything else as written
export const cloakUser = (text) => cloak(text, USER_TURNED_AWAY)

// agy hydrates slash commands in every prompt it is handed: the prompt is
// split at white space (Go's unicode.IsSpace), and a word that is "/" and
// one of the session's command names, exactly and case and all, gets that
// command's whole text in an <ADDITIONAL_METADATA> block ("/learn is a
// [Slash Command]: <LEARN>…") and the command after the turn (the last
// such word, when there are several). A client's system prompt, a skill
// list, a replayed reply or a tool result that names a command is read as
// the user running it: Cindy's (Pi) "when the user directly invokes /learn
// or /skill:learn in Pi" had every turn start agy's /learn (plugins#1294,
// huangzhenhao90, and dyss1992 on agy-cli 0.1.147, each on a real account).
// A word joiner (U+2060) after the "/" makes it another word, so agy finds
// no command, and the model reads the same words. Only such a word is
// touched: /learn. /learning /skill:learn /Learn `/learn` /path/to/learn
// and URLs aren't commands to agy and go as written. Checked against agy
// 1.5.18 itself through a local gateway (11-27): a tab, \v, a no-break
// space, U+0085, U+2002, U+2028 or U+3000 on either side makes a word, and
// so does a code fence; U+FEFF and U+2060 don't. JavaScript's \s isn't that
// set (it has U+FEFF and not U+0085), so GO_SPACE spells it out.
// DEFAULT_SLASH_COMMANDS are the commands a fresh session lists
// (available_commands_update, 11-26 and 11-27); the session's own list is
// added to them as it comes (a skill of the user's is a command too).
export const DEFAULT_SLASH_COMMANDS = [
"goal", "compact", "schedule", "browser", "plan", "grill-me", "teamwork", "learn", "boost",
"agy-customizations", "antigravity-guide", "run-workflow", "swarm",
]

const GO_SPACE = "[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]"
const GO_SPACE_RE = new RegExp(GO_SPACE)
const JOINER = "\u2060"
const slashCommandReCache = new Map()

function slashCommandRe(commands) {
const names = [...new Set(Array.from(commands || [], (c) => (typeof c === "string" ? c : "")).filter((c) => c && !GO_SPACE_RE.test(c)))]
.sort((a, b) => b.length - a.length)
if (!names.length) return null
const key = names.join("\0")
let re = slashCommandReCache.get(key)
if (!re) {
const alt = names.map(escape).join("|")
re = {
defuse: new RegExp(`(^|${GO_SPACE})\\/(${alt})(?=$|${GO_SPACE})`, "g"),
restore: new RegExp(`(^|${GO_SPACE})\\/${JOINER}(${alt})(?=$|${GO_SPACE})`, "g"),
}
if (slashCommandReCache.size > 64) slashCommandReCache.clear()
slashCommandReCache.set(key, re)
}
return re
}

// defuseSlashCommands is text with a word joiner after the "/" of each run
// agy would read as one of commands
export function defuseSlashCommands(text, commands = DEFAULT_SLASH_COMMANDS) {
if (typeof text !== "string" || !text.includes("/")) return text
const re = slashCommandRe(commands)?.defuse
if (!re) return text
re.lastIndex = 0
return text.replace(re, `$1/${JOINER}$2`)
}

// restoreSlashCommands is value (a tool call's arguments) with the word
// joiner defuseSlashCommands puts in taken out of every string in it: a
// model that copies "/\u2060plan" out of a replayed file or command into an
// edit's old_string or a command means the "/plan" the file has.
export function restoreSlashCommands(value, commands = DEFAULT_SLASH_COMMANDS) {
const re = slashCommandRe(commands)?.restore
if (!re) return value
const walk = (v) => {
if (typeof v === "string") {
if (!v.includes(JOINER)) return v
re.lastIndex = 0
return v.replace(re, "$1/$2")
}
if (Array.isArray(v)) {
let changed = false
const out = v.map((item) => {
const next = walk(item)
if (next !== item) changed = true
return next
})
return changed ? out : v
}
if (v && typeof v === "object") {
let out = null
for (const [k, item] of Object.entries(v)) {
const next = walk(item)
if (next !== item) (out ??= { ...v })[k] = next
}
return out ?? v
}
return v
}
return walk(value)
}

// outgoing is system text as agy is handed it: each turned-away line and
// each paragraph of REWORDED reworded
export const outgoing = (system) => reword(cloak(system))
Expand Down
69 changes: 68 additions & 1 deletion cloak.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// more, so cloak.mjs is the one copy now.
import { expect, test } from "bun:test"
import { readFileSync } from "node:fs"
import { REWORDED, TURNED_AWAY, cloak, cloakUser, hint, outgoing, turnsAway } from "./cloak.mjs"
import { DEFAULT_SLASH_COMMANDS, REWORDED, TURNED_AWAY, cloak, cloakUser, defuseSlashCommands, hint, outgoing, restoreSlashCommands, turnsAway } from "./cloak.mjs"

const ZW = "​"

Expand Down Expand Up @@ -144,3 +144,70 @@ test("DeepSeek Harness 0.2.2-rc.3's whole Web GUI prompt goes with only its turn
}
expect(out.split("\n").length).toBe(raw.split("\n").length)
})

// agy's own rule (cloak.mjs): the text split at Go's unicode.IsSpace, a
// word that is "/" and a command name
const GO_SPACE = /[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/
const agyRuns = (text, commands = DEFAULT_SLASH_COMMANDS) =>
text.split(GO_SPACE).filter((w) => w.startsWith("/") && commands.includes(w.slice(1))).map((w) => w.slice(1))
const J = "⁠"

test("defuseSlashCommands leaves agy no command to run, and touches nothing agy wouldn't run", () => {
expect(DEFAULT_SLASH_COMMANDS).toEqual([
"goal", "compact", "schedule", "browser", "plan", "grill-me", "teamwork", "learn", "boost",
"agy-customizations", "antigravity-guide", "run-workflow", "swarm",
])
// Cindy's (Pi) system prompt line, as plugins#1294 quotes it
const cindy = "when the user directly invokes /learn or /skill:learn in Pi"
expect(agyRuns(cindy)).toEqual(["learn"])
expect(defuseSlashCommands(cindy)).toBe(cindy.replace(" /learn ", ` /${J}learn `))
expect(agyRuns(defuseSlashCommands(cindy))).toEqual([])

const raw = [
"/plan",
"/grill-me",
"Check /learn /plan /grill-me together\t/goal\r\n/swarm\f/boost",
"```sh\n/compact\n```",
"Path /path/to/learn and URL https://example.com/learn and /learning and /learn-more and /skill:learn",
"Punctuation /learn. /learn, `/learn` <tag>/learn</tag> (/plan) x/plan //plan /Learn /PLAN",
"No-break\u00a0/learn and /learn\u00a0x, vertical\v/learn and /learn\vx",
"Wide\u3000/plan\u3000x, next line\u0085/goal now, BOM\ufeff/learn, joiner\u2060/learn",
].join("\n")
const out = defuseSlashCommands(raw)
expect(agyRuns(raw)).toEqual([
"plan", "grill-me", "learn", "plan", "grill-me", "goal", "swarm", "boost", "compact", "learn", "learn", "learn", "learn", "plan", "goal",
])
expect(agyRuns(out)).toEqual([])
// each change is a joiner after a "/" agy would have read as a command
expect(out.replaceAll(`/${J}`, "/")).toBe(raw)
expect(out.split(`/${J}`).length - 1).toBe(15)
expect(out).toContain(`Check /${J}learn /${J}plan /${J}grill-me together\t/${J}goal\r\n/${J}swarm\f/${J}boost`)
expect(out).toContain(`\`\`\`sh\n/${J}compact\n\`\`\``)
expect(out).toContain("Path /path/to/learn and URL https://example.com/learn and /learning and /learn-more and /skill:learn")
expect(out).toContain("Punctuation /learn. /learn, `/learn` <tag>/learn</tag> (/plan) x/plan //plan /Learn /PLAN")
expect(out).toContain(`No-break\u00a0/${J}learn and /${J}learn\u00a0x, vertical\v/${J}learn and /${J}learn\vx`)
expect(out).toContain(`Wide\u3000/${J}plan\u3000x, next line\u0085/${J}goal now, BOM\ufeff/learn, joiner\u2060/learn`)
// already defused text stays as it is
expect(defuseSlashCommands(out)).toBe(out)
// a session's own commands, with regexp characters in a name
expect(defuseSlashCommands("run /foo.bar now, not /fooxbar", ["foo.bar"])).toBe(`run /${J}foo.bar now, not /fooxbar`)
expect(defuseSlashCommands("run /learn now", [])).toBe("run /learn now")
expect(defuseSlashCommands("run /learn now", undefined)).toBe(`run /${J}learn now`)
})

test("restoreSlashCommands gives a tool call's arguments back as the prompt's own text had them", () => {
const file = "Use /plan to start.\n/learn\nSee /path/to/plan"
const copied = defuseSlashCommands(file)
expect(copied).not.toBe(file)
const args = { file_path: "/repo/README.md", old_string: copied, edits: [{ text: `cd /${J}plan` }], n: 2, ok: true, none: null }
const back = restoreSlashCommands(args)
expect(back).toEqual({ file_path: "/repo/README.md", old_string: file, edits: [{ text: "cd /plan" }], n: 2, ok: true, none: null })
expect(args.old_string).toBe(copied)
// nothing to restore: the very same object
const plain = { command: "ls /plan", list: ["/learn"] }
expect(restoreSlashCommands(plain)).toBe(plain)
// a joiner anywhere else is the model's own
const other = { text: `a${J}b /${J}learning x/${J}plan` }
expect(restoreSlashCommands(other)).toBe(other)
expect(restoreSlashCommands({ c: `/${J}custom` }, ["custom"])).toEqual({ c: "/custom" })
})
139 changes: 139 additions & 0 deletions gateway-free.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import fs from "node:fs"
import path from "node:path"

// Antigravity's desktop app keeps its gateway in ~/.gemini/config/config.json
// ({"gateway":{"enabled":true,"url":…}}), and agy reads the same file: an agy
// on ~/.gemini lists and serves the gateway's models, not the Google
// account's, and its /usage reads no Google quota at all ({"groups": []},
// agy 1.5.18: on a gateway it asks Google nothing). When magpie has wired
// the app to itself, that gateway is magpie (canlee886 on X, plugins#1591).
// A file that can't be read as JSON counts as on: the folder without the
// gateway is right either way.
export function appGatewayOn(home) {
let text
try {
text = fs.readFileSync(path.join(home, ".gemini", "config", "config.json"), "utf8")
} catch {
return false
}
try {
const gateway = JSON.parse(text)?.gateway
return gateway?.enabled === true
} catch {
return true
}
}

// gatewayFreeDir is agy's own ~/.gemini without the app's gateway, for an agy
// that has to stay on its own folder (its Google sign-in is in a file there,
// antigravity-cli/antigravity-oauth-token, where no keyring is; or
// AGY_BRIDGE_GEMINI_DIR=default) while the app's gateway is on. agy takes it
// as --gemini-dir (acp) or --gemini_dir (agy -p): every entry of ~/.gemini is
// linked into it, so agy reads and renews that sign-in where it is, and its
// config folder is the user's with one file different: config.json without
// the app's gateway and the models it lists. null when it can't be made.
export function gatewayFreeDir(home, env = process.env, platform = process.platform) {
const src = path.join(home, ".gemini")
const base = env.XDG_STATE_HOME || path.join(home, ".local", "state")
const dir = path.join(base, "magpie-agy-bridge", "agy-own")
try {
fs.mkdirSync(path.join(dir, "config"), { recursive: true, mode: 0o700 })
linkAll(src, dir, new Set(["config"]), platform)
linkAll(path.join(src, "config"), path.join(dir, "config"), new Set(["config.json"]), platform)
writeWithoutGateway(path.join(src, "config", "config.json"), path.join(dir, "config", "config.json"))
} catch {
return null
}
return dir
}

function entries(dir) {
try {
return fs.readdirSync(dir, { withFileTypes: true })
} catch {
return []
}
}

// linkAll links each entry of src (but those in skip) into dir, and takes
// out a link of dir's whose entry is gone. What agy made in dir itself is
// left as it is.
function linkAll(src, dir, skip, platform) {
const wanted = new Set()
for (const entry of entries(src)) {
if (skip.has(entry.name)) continue
wanted.add(entry.name)
const target = path.join(src, entry.name)
const at = path.join(dir, entry.name)
let isDir = entry.isDirectory()
if (entry.isSymbolicLink()) {
try { isDir = fs.statSync(target).isDirectory() } catch { continue }
}
linkOne(target, at, isDir, platform)
}
for (const entry of entries(dir)) {
if (skip.has(entry.name) || wanted.has(entry.name)) continue
const at = path.join(dir, entry.name)
if (linked(at)) try { fs.rmSync(at, { force: true }) } catch {}
}
}

// linked: at is a link (a junction on Windows reads as one too)
function linked(at) {
try {
return fs.lstatSync(at).isSymbolicLink()
} catch {
return false
}
}

function sameTarget(at, target) {
try {
return path.resolve(path.dirname(at), fs.readlinkSync(at)) === path.resolve(target)
} catch {
return false
}
}

function linkOne(target, at, isDir, platform) {
if (linked(at)) {
if (sameTarget(at, target)) return
fs.rmSync(at, { force: true })
} else if (fs.existsSync(at)) {
// agy's own in this folder: never thrown away
return
}
if (platform === "win32") {
// a junction needs no privilege; a file link does, so a file that
// can't be linked is copied (the folders hold what agy writes)
if (isDir) return fs.symlinkSync(target, at, "junction")
try {
fs.symlinkSync(target, at, "file")
} catch {
fs.copyFileSync(target, at)
}
return
}
fs.symlinkSync(target, at)
}

// writeWithoutGateway writes the user's config.json without "gateway" and
// "models" (the list the app takes from the gateway), through a temp file
// and a rename, so agy never reads half of it. One that can't be read as
// JSON gives an empty object.
function writeWithoutGateway(from, to) {
let config = {}
try {
const read = JSON.parse(fs.readFileSync(from, "utf8"))
if (read && typeof read === "object" && !Array.isArray(read)) config = read
} catch {}
delete config.gateway
delete config.models
const text = JSON.stringify(config, null, 2)
try {
if (fs.readFileSync(to, "utf8") === text) return
} catch {}
const tmp = `${to}.${process.pid}.tmp`
fs.writeFileSync(tmp, text, { mode: 0o600 })
fs.renameSync(tmp, to)
}
Loading