Skip to content
Merged
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
1 change: 1 addition & 0 deletions agy-cli.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ for (const [name, mocks] of [
["claude-code-sessions.mjs", false],
["media-input.mjs", false],
["default-agent.mjs", false],
["workspace-handoff.mjs", false],
]) {
test(`test/${name}`, () => {
// bun's 5s default per test is a fixed wait these process-spawning tests
Expand Down
169 changes: 146 additions & 23 deletions index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2710,6 +2710,8 @@ class Turn {
if (type === "tool_call_update" && update.status &&
update.status !== "in_progress" && update.status !== "pending") {
const wasActive = this.activeAcpToolCalls.delete(id)
// a call the gate couldn't start: the next one finds the folder again
if (update.status === "failed") this.proc.keepWorkspace()
if (wasActive && update.status === "failed" && typeof update.rawOutput === "string" &&
update.rawOutput.startsWith("tool call denied by pre-tool hook: ")) {
this.proc.deniedHooks++
Expand Down Expand Up @@ -2954,14 +2956,24 @@ class Proc {
await ensureControlServer()
const bin = await ensureShimDir()
sessions.set(this.token, this)
this.workspaceOwner = randomUUID()
if (this.workspace) {
// agy's prompt cache follows the folder it runs in: a session resumed
// anywhere else replays its whole history uncached. It
// starts again in its own folder, made again if it was removed.
await workspaceRemovals.get(this.workspace)?.catch(() => {})
await fs.promises.mkdir(this.workspace, { recursive: true, mode: 0o700 })
} else {
if (!await claimWorkspace(this.workspace, this.workspaceOwner)) {
// A consumed rebase entry hands over cleanup once its agy has exited.
// Keep that responsibility when this agy needs a different directory.
if (this.resumeFrom?.rebase && this.resumeFrom.workspaceOwner) {
this.abandonedWorkspace = { path: this.workspace, owner: this.resumeFrom.workspaceOwner }
}
this.workspace = null
}
}
if (!this.workspace) {
this.workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-bridge-"))
fs.writeFileSync(path.join(this.workspace, WORKSPACE_OWNER_FILE), this.workspaceOwner, { mode: 0o600 })
}
// Opt-in: AGY_BRIDGE_ALLOW_AGY_TOOLS=1 hands every session/request_permission
// to agy's own --dangerously-skip-permissions, so agy's built-in tools (shell,
Expand All @@ -2973,6 +2985,7 @@ class Proc {
const home = currentHome()
const geminiDir = own.dir || path.join(home || os.homedir(), ".gemini")
const hookEnv = await writeDefaultAgentFiles(this.workspace, { ...bridgeAgentFiles(this.media, allowAgyTools), geminiDir })
this.workspaceFiles = workspaceSnapshot(this.workspace)
this.logPath = path.join(this.workspace, "agy-acp.log")

const args = [
Expand Down Expand Up @@ -3037,6 +3050,31 @@ class Proc {
})
}

// agy starts the tool gate in the folder that holds hooks.json, by path,
// for every tool call: with that folder gone, the hook can't start
// ("fork/exec /bin/sh: no such file or directory", "The directory name
// is invalid." on Windows) and every call fails. Another host still on an
// older plugin, or a temp cleaner, can remove it from under a live agy;
// it is made again before each prompt and each step's results.
keepWorkspace() {
if (!this.workspace || !this.workspaceFiles || this.stopping || this.dead) return
// the claim only on a folder that was gone whole: one there names
// whichever agy claimed it since
const gone = !fs.existsSync(this.workspace)
let restored = 0
for (const [name, bytes] of this.workspaceFiles) {
const file = path.join(this.workspace, name)
if (name === WORKSPACE_OWNER_FILE && !gone) continue
if (fs.existsSync(file)) continue
try {
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
fs.writeFileSync(file, bytes, { mode: 0o600, flag: "wx" })
restored++
} catch {}
}
if (restored) logBridgeEvent(this, this.turn, "workspace_restored", "missing", {}, { files: restored })
}

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"}`)
Expand Down Expand Up @@ -3481,6 +3519,7 @@ class Proc {
async steerInSession(turn, results, history) {
if (this.dead || this.stopping || this.retiring || this.turn !== turn || turn.steering || turn.done ||
turn.finalized || !Array.isArray(history)) return false
this.keepWorkspace()
// agy offloads an image in an MCP result to a file the model can't open,
// so the call is answered with its text and the image goes in the
// steer's prompt (withoutAnswered keeps it there).
Expand Down Expand Up @@ -3529,6 +3568,7 @@ class Proc {
async #runTurn(turn, content, model, selection, seeds = []) {
let logWatch
try {
this.keepWorkspace()
turn.arm()
logWatch = turn.logWatch = this.#watchTurnLog(turn)
if (model) await this.#setModel(model, selection)
Expand Down Expand Up @@ -3569,6 +3609,7 @@ class Proc {
return
}
turn.arm()
this.keepWorkspace()
this.hasSentFirstTurn = true
// the session is about to hold this turn's messages: a restart from
// here resumes at them (parkStep), never at the turn before
Expand Down Expand Up @@ -4075,6 +4116,7 @@ class Proc {
const turn = this.turn
if (!turn || turn.finalized) throw new BusyError("agy bridge: no response is waiting for these tool results")
turn.touchClient()
this.keepWorkspace()
let delivered = 0
for (const { call, result, rawKey } of this.validateResults(results).values()) {
clearTimeout(call.deadline)
Expand Down Expand Up @@ -4308,36 +4350,108 @@ class Proc {
// the folder never goes from under an agy that resumed in it.
if (![...allProcs].some((proc) => proc !== this && proc.workspace === this.workspace)) {
const { convKey, sessionId, workspace } = this
try {
withStateLock(sessionStateFile(), () => {
if (!readStateFile().some((entry) => entry?.key === convKey && entry.sessionId === sessionId && entry.rebase)) {
// taken by another host: never written back from this one's copy
if (parked.get(convKey)?.sessionId === sessionId) parked.delete(convKey)
return
}
fs.rmSync(workspace, { recursive: true, force: true })
})
} catch {}
await releaseWorkspace(workspace, this.workspaceOwner, () => {
if (readStateFile().some((entry) => entry?.key === convKey && entry.sessionId === sessionId && entry.rebase)) return true
// Taken by another host. Never write it back from this one's copy.
if (parked.get(convKey)?.sessionId === sessionId) parked.delete(convKey)
return false
})
}
} else if (this.workspace && ![...allProcs].some((proc) => proc !== this && proc.workspace === this.workspace)) {
const removal = this.#removeWorkspace()
const removal = releaseWorkspace(this.workspace, this.workspaceOwner)
workspaceRemovals.set(this.workspace, removal)
await removal
if (workspaceRemovals.get(this.workspace) === removal) workspaceRemovals.delete(this.workspace)
}
if (this.abandonedWorkspace) {
const { path, owner } = this.abandonedWorkspace
await releaseWorkspace(path, owner)
}
allProcs.delete(this)
}
}

async #removeWorkspace() {
for (let attempt = 0; attempt < 4; attempt++) {
try {
await fs.promises.rm(this.workspace, { recursive: true, force: true })
break
} catch (error) {
if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)))
// A session's folder names the agy that last started in it, the bridge
// process by its workspace owner ID. Another host resumes a parked
// session in the same folder (agy's prompt cache follows it) while the
// host that parked it may still be stopping its own agy there: magpie keeps
// a host it replaced (a plugin update, a recycle) answering its calls for
// up to ten minutes. That host removed the folder when its agy stopped,
// from under the new host's agy, whose every tool call then failed: agy
// starts the tool gate there (keepWorkspace). A folder is now removed only
// by the agy that claimed it last, checked and moved aside under the state
// file's lock, which a claim holds too.
const WORKSPACE_OWNER_FILE = ".magpie-agy-owner"

async function claimWorkspace(workspace, owner) {
for (let attempt = 0; attempt < 4; attempt++) {
const claimed = withStateLock(sessionStateFile(), () => {
fs.mkdirSync(workspace, { recursive: true, mode: 0o700 })
fs.writeFileSync(path.join(workspace, WORKSPACE_OWNER_FILE), owner, { mode: 0o600 })
return true
})
if (claimed) return true
if (attempt < 3) await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)))
}
// Leave the cached directory alone if its ownership could not be transferred.
// The ACP session can still resume in a new workspace.
return false
}

// What #spawn wrote, for keepWorkspace to write again.
function workspaceSnapshot(workspace) {
const files = new Map()
for (const name of [WORKSPACE_OWNER_FILE, "AGENTS.md", path.join(".agents", "skills.json"),
path.join(".agents", "hooks.json"), path.join(".agents", "tool-gate.cmd")]) {
try { files.set(name, fs.readFileSync(path.join(workspace, name))) } catch {}
}
return files
}

// Under the state file's lock: { aside } is the folder, moved out of the
// way to be removed, when owner claimed it last; { kept } when another agy
// did (or an older bridge's, which names none); { busy } when Windows
// still holds it for an agy that just ended; {} when it is gone already.
function takeWorkspaceLocked(workspace, owner) {
let held
try {
held = fs.readFileSync(path.join(workspace, WORKSPACE_OWNER_FILE), "utf8")
} catch (error) {
return error?.code === "ENOENT" && !fs.existsSync(workspace) ? {} : { kept: true }
}
if (!owner || held !== owner) return { kept: true }
const aside = `${workspace}.gone-${randomUUID().slice(0, 8)}`
try {
fs.renameSync(workspace, aside)
} catch (error) {
return ["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"].includes(error?.code) ? { busy: true } : {}
}
return { aside }
}

async function releaseWorkspace(workspace, owner, shouldRelease = () => true) {
for (let attempt = 0; attempt < 4; attempt++) {
const taken = withStateLock(sessionStateFile(), () => shouldRelease() ? takeWorkspaceLocked(workspace, owner) : { kept: true })
if (taken && !taken.busy) {
if (taken.aside) await fs.promises.rm(taken.aside, { recursive: true, force: true, maxRetries: 3 }).catch(() => {})
return
}
// the lock taken elsewhere, or the folder still held
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)))
}
}

function releaseWorkspaceSync(workspace, owner, attempts) {
const wait = new Int32Array(new SharedArrayBuffer(4))
for (let attempt = 0; attempt < attempts; attempt++) {
const taken = withStateLock(sessionStateFile(), () => takeWorkspaceLocked(workspace, owner))
if (taken && !taken.busy) {
if (taken.aside) {
try { fs.rmSync(taken.aside, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }) } catch {}
}
return
}
Atomics.wait(wait, 0, 0, 50)
}
}

Expand Down Expand Up @@ -4774,6 +4888,7 @@ function writeParked(proc, midTurn, rebase = null) {
rebase: true, count: rebase.rows.length, beyond: !!rebase.beyond,
requestHash: digest(historyKey(rebase.messages)), requestCount: rebase.messages.length,
stopping: true, holder: { pid: proc.child?.pid ?? null, host: HOST_ID },
workspaceOwner: proc.workspaceOwner,
}
: midTurn ? { midTurn: true, count: proc.expectedMessages.length } : {},
at: Date.now(),
Expand Down Expand Up @@ -4996,6 +5111,7 @@ function takeParked(convKey, opts, miss = {}) {
return {
sessionId: entry.sessionId, expectedMessages: prefix, workspace, rebase: true, beyond: entry.beyond !== false,
holder: entry.holder ?? null,
workspaceOwner: entry.workspaceOwner,
}
}
// A step parked mid-turn is taken only by its results: the request goes
Expand Down Expand Up @@ -10414,6 +10530,7 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a
let flattened = proc.pendingFlattenedTurn
proc.pendingFlattenedTurn = null
const isFirstTurn = !proc.hasSentFirstTurn
proc.keepWorkspace()
// the prompt names each video or audio by its file; the session is still
// matched by body.messages
const messages = body.messages.map((message) => stageMedia(message, proc.workspace))
Expand Down Expand Up @@ -10721,6 +10838,10 @@ function readUsageOf(home, email = "") {
}
await keepOwn(email, stored)
}
// Load this account's saved catalog rows before reading usage so its
// windows map its own models even when usage runs before models().
const agy = findAgy()
if (agy) useAgyPath(agy)
const result = await read()
if (email && !result.error && toldNotHeld.delete(email.toLowerCase()) && result.signIn === "kept") {
return { ...result, signIn: "renewed" }
Expand Down Expand Up @@ -11462,8 +11583,10 @@ function reapOnExit() {
}
for (const proc of allProcs) {
// A process that just ended can hold its cwd (the workspace) for a moment.
if (proc.workspace) {
try { fs.rmSync(proc.workspace, { recursive: true, force: true, maxRetries: windows ? 10 : 0, retryDelay: 50 }) } catch {}
if (proc.workspace) releaseWorkspaceSync(proc.workspace, proc.workspaceOwner, windows ? 10 : 2)
if (proc.abandonedWorkspace) {
const { path, owner } = proc.abandonedWorkspace
releaseWorkspaceSync(path, owner, windows ? 10 : 2)
}
}
if (shimDir && shimDirOwned) {
Expand Down
80 changes: 45 additions & 35 deletions model-ids.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// The runtime catalog `agy models` listed, so usage windows can name the ids
// the provider serves (usage.mjs stays import-free of index.mjs).
import { currentHome } from "./account.mjs"

// The runtime catalog `agy models` listed for each account (keyed by
// currentHome() ?? ""), so usage windows name the ids that account serves
// without one account's refresh overwriting another's (usage.mjs stays
// import-free of index.mjs).
//
// rows(): [{ id, name, effort? }] — the shape `agy models` parses into
// (parseAgyModels), the saved catalog, and FALLBACK_MODELS.
Expand All @@ -9,15 +13,20 @@
// in it, plus the bare family id itself even when agy lists no variant of
// that name (the catalog serves it as its default).

let rows = null
let index = new Map()
const states = new Map()

export function storeCatalogRows(list) {
rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id) : null
index = null
const key = currentHome() ?? ""
const rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id) : null
if (!rows) {
states.delete(key)
return
}
states.set(key, { rows, index: null })
}

export function catalogRows() {
const rows = states.get(currentHome() ?? "")?.rows
return rows ? [...rows] : null
}

Expand All @@ -40,37 +49,38 @@ function listedNames(description) {
}

export function nameIndex() {
if (index) return index
index = new Map()
if (rows) {
const families = new Map()
const shown = new Map() // family -> its display name
const claims = new Map() // display name -> the families that use it
for (const model of rows) {
const effort = /-(high|medium|low|minimal|xhigh|max)$/i.exec(model.id)?.[1]?.toLowerCase() || ""
const family = effort ? model.id.slice(0, -(effort.length + 1)) : model.id
if (!families.has(family)) families.set(family, new Set())
families.get(family).add(model.id)
const name = normalizeName(model.name)
if (!name) continue
// the family's name as agy shows it, its effort word left off
if (!shown.has(family)) shown.set(family, stripEffortSuffix(String(model.name).trim().replace(/\s+/g, " ")))
for (const alias of [name, stripEffortSuffix(name)]) {
if (!claims.has(alias)) claims.set(alias, new Set())
claims.get(alias).add(family)
}
}
for (const [family, ids] of families) {
// the bare id the catalog serves even when agy lists no variant of it
ids.add(family)
}
for (const [name, owners] of claims) {
// one name, two families: no match, rather than whichever came first
if (owners.size !== 1) continue
const [family] = owners
index.set(name, { family, ids: families.get(family), name: shown.get(family) || family })
const state = states.get(currentHome() ?? "")
if (!state?.rows) return new Map()
if (state.index) return state.index
const index = new Map()
const families = new Map()
const shown = new Map() // family -> its display name
const claims = new Map() // display name -> the families that use it
for (const model of state.rows) {
const effort = /-(high|medium|low|minimal|xhigh|max)$/i.exec(model.id)?.[1]?.toLowerCase() || ""
const family = effort ? model.id.slice(0, -(effort.length + 1)) : model.id
if (!families.has(family)) families.set(family, new Set())
families.get(family).add(model.id)
const name = normalizeName(model.name)
if (!name) continue
// the family's name as agy shows it, its effort word left off
if (!shown.has(family)) shown.set(family, stripEffortSuffix(String(model.name).trim().replace(/\s+/g, " ")))
for (const alias of [name, stripEffortSuffix(name)]) {
if (!claims.has(alias)) claims.set(alias, new Set())
claims.get(alias).add(family)
}
}
for (const [family, ids] of families) {
// the bare id the catalog serves even when agy lists no variant of it
ids.add(family)
}
for (const [name, owners] of claims) {
// one name, two families: no match, rather than whichever came first
if (owners.size !== 1) continue
const [family] = owners
index.set(name, { family, ids: families.get(family), name: shown.get(family) || family })
}
state.index = index
return index
}

Expand Down
Loading