When plugins change, magpie retires the old plugin host and starts a new one. The old host can keep port 43717 for up to 10 minutes while it finishes calls. In 0.10.0, the new host stored its failed bind as the service, and `if (service) return` blocked every later try. Once the old host exited, the page stayed refused until the host restarted. Now a service is kept only once it is listening. A failed bind retries with backoff (1s, doubling, capped at 30s, the timer unref'd) while a store exists, and a listener that closes starts again. A failed backend start is retried too, and the first mutation's race with the empty-store check gets one more check. layerfs 0.10.1. Run at the reviewed head 6f2d484e8f3367d1d614d4be5d9a44a701165fb4, on mote (temp HOME, Bun 1.4.2): - bun test packages/layerfs: 68 pass (main: 64). page-lifecycle.test.mjs: 3 of 3 green. bun scripts/check.mjs: exit 0. - The new tests against main's index.mjs: the handover and backend-retry tests go red. - Broken by hand: dropping the backendPromise reset, the retry schedule, or storing the service before it listens each turns a test red. - Probes: a closed listener comes back; with the port held for good, the retries cap at one every 30s and leak no servers; a pending retry doesn't hold the process open. page-service.mjs is unchanged, so its Host and Origin checks cover every retry. Not covered by a test (follow-up): restarting a closed listener, sharing one startup between concurrent calls, and the store-version recheck. recheck and storeVersion overlap: either alone handles the race.
334 lines
18 KiB
JavaScript
334 lines
18 KiB
JavaScript
// LayerFS for every agent magpie connects: instead of each agent copying a
|
|
// project tree to work on it, agents share one durable, deduplicated history
|
|
// and work through stable workspace paths. Forking a branch for a parallel
|
|
// agent copies no file bytes; a checkpoint stores only what changed.
|
|
// Arguments are JSON Schema, so the package needs no dependency.
|
|
//
|
|
// The page's data channel: the plugin host's own localhost-only service
|
|
// (page-service.mjs). A magpie page cannot fetch and cannot read
|
|
// plugin-private files, so the installed page/index.html only navigates
|
|
// its frame to the service, which embeds backend.trajectory() — the
|
|
// page's real commits, branches, storage and dedup accounting, with the
|
|
// real calling agent on each — in the HTML it returns. The service
|
|
// starts only once a store exists; see the README's page section.
|
|
//
|
|
// Backend: a local content-addressed store with the LayerFS model, in
|
|
// layerfs.mjs. The native backend (the real LayerFS SDK) is not shipped
|
|
// in this registry package — the SDK is still not published to npm —
|
|
// and returns once the plugin can pin it as a dependency. See the README.
|
|
import { readdirSync } from "node:fs"
|
|
import { join } from "node:path"
|
|
import { checkBranch, checkInnerPath, checkProject, checkSourceDir, createBackend, storeHome } from "./layerfs.mjs"
|
|
import { resolvePagePort, startPageService } from "./page-service.mjs"
|
|
|
|
const str = (v, name) => {
|
|
if (typeof v !== "string" || !v) throw new Error(`${name} is a non-empty string`)
|
|
return v
|
|
}
|
|
const opt = (v, name, dflt) => (v === undefined || v === "" ? dflt : str(v, name))
|
|
|
|
// The calling agent, as the gateway knows it (the tool host's ctx.agent):
|
|
// the one field of a tool call that says WHO made it. Trimmed and capped,
|
|
// then recorded on the events and commits the call creates — the page
|
|
// attributes the work to the agent that actually made it, not to a token
|
|
// guessed from the branch name.
|
|
const callingAgent = (ctx) => {
|
|
const a = ctx?.agent
|
|
return typeof a === "string" && a.trim() ? a.trim().slice(0, 40) : ""
|
|
}
|
|
|
|
// ---- the page's live channel: the host's own service ---------------------
|
|
// The service starts once per plugin instance, and only once a store
|
|
// exists — two read-only gates, so a user with no store gets no service
|
|
// and nothing written anywhere: a projects folder that holds entries
|
|
// (not merely exists; the backend's constructor mkdirs it), and a
|
|
// non-empty answer from the backend that will serve the calls. A host
|
|
// whose store gains its first project later starts the service after
|
|
// the call that created it (mutate, below). The start is off the tool
|
|
// calls' path and every failure is swallowed: a held port or a failed
|
|
// read leaves the tools untouched, and the page's redirect simply finds
|
|
// nothing listening.
|
|
|
|
export const LayerfsTools = async (ctx = {}, options = {}) => {
|
|
let backendPromise
|
|
const backend = () => (backendPromise ??= createBackend(process.env, options).catch((error) => {
|
|
backendPromise = undefined
|
|
throw error
|
|
}))
|
|
const execEnabled = () => options?.exec === true || process.env.MAGPIE_LAYERFS_EXEC === "1"
|
|
// A call touches only the state its own operation needs. Reads (history,
|
|
// resolve, status) change nothing and start nothing.
|
|
const call = async (fn) => {
|
|
const b = await backend()
|
|
return fn(b)
|
|
}
|
|
// A new host may start before the retired host releases this port.
|
|
// Keep one start in flight, and remember a service only after it
|
|
// actually listens. Retry while a real store exists, without keeping
|
|
// an otherwise finished host alive or polling before the first project.
|
|
let service = null
|
|
let starting = null
|
|
let retryTimer = null
|
|
let retryDelay = 1000
|
|
let storeVersion = 0
|
|
let recheck = false
|
|
let hasStore = false
|
|
const retry = () => {
|
|
if (!hasStore || retryTimer || service?.server.listening) return
|
|
retryTimer = setTimeout(() => {
|
|
retryTimer = null
|
|
ensureService().catch(() => { /* the page never blocks a tool */ })
|
|
}, retryDelay)
|
|
retryTimer.unref?.()
|
|
retryDelay = Math.min(retryDelay * 2, 30000)
|
|
}
|
|
const ensureService = () => {
|
|
if (service?.server.listening) return Promise.resolve()
|
|
if (starting) {
|
|
recheck = true
|
|
return starting
|
|
}
|
|
if (retryTimer) {
|
|
clearTimeout(retryTimer)
|
|
retryTimer = null
|
|
}
|
|
const version = storeVersion
|
|
recheck = false
|
|
starting = (async () => {
|
|
let hasEntries
|
|
try {
|
|
hasEntries = readdirSync(join(storeHome(), "projects")).length > 0
|
|
} catch (error) {
|
|
hasStore = false
|
|
return
|
|
}
|
|
if (!hasEntries) {
|
|
hasStore = false
|
|
return
|
|
}
|
|
const b = await backend()
|
|
const data = await b.trajectory()
|
|
if (!data.projects.length) {
|
|
hasStore = false
|
|
return
|
|
}
|
|
hasStore = true
|
|
const candidate = startPageService({ backend: b, port: resolvePagePort(options) })
|
|
const stopped = () => {
|
|
if (service !== candidate || candidate.server.listening) return
|
|
service = null
|
|
retry()
|
|
}
|
|
candidate.server.once("close", stopped)
|
|
candidate.server.on("error", stopped)
|
|
if (!await candidate.listening || !candidate.server.listening) {
|
|
retry()
|
|
return
|
|
}
|
|
service = candidate
|
|
retryDelay = 1000
|
|
})().catch(() => {
|
|
retry()
|
|
}).finally(() => {
|
|
starting = null
|
|
if ((recheck || storeVersion !== version) &&
|
|
!service?.server.listening && !retryTimer) {
|
|
recheck = false
|
|
queueMicrotask(() => ensureService().catch(() => { /* the tools stay usable */ }))
|
|
}
|
|
})
|
|
return starting
|
|
}
|
|
ensureService().catch(() => { /* no service: the tools are untouched */ })
|
|
// A mutating call may have created the store's first project: offer
|
|
// the service its start, off the call's path.
|
|
const mutate = async (fn) => {
|
|
const b = await backend()
|
|
const out = await fn(b)
|
|
// The first mutation may race the factory's empty-store check. Let the
|
|
// in-flight check finish, then run one more against the new store.
|
|
storeVersion++
|
|
ensureService().catch(() => { /* never on the tool call's path */ })
|
|
return out
|
|
}
|
|
|
|
return {
|
|
tool: {
|
|
provision: {
|
|
description:
|
|
"Gives the agent a LayerFS workspace for a project branch and answers the filesystem path to work in. " +
|
|
"The first provision of a project imports the source directory the caller passes — source is required, there is no default — as its first checkpoint; " +
|
|
"later provisions of the same branch answer the same path without copying the tree again (source is then ignored). " +
|
|
"Pass the directory the user chose for this project: the app's config directory, credential stores (.ssh, .aws, .gnupg), the home directory and the plugin's own store are refused as sources, " +
|
|
"and secret-shaped files in the tree (.env*, private keys, .git internals) never enter the store — the sim backend skips them on import and reports how many. " +
|
|
"Work in the returned path, then save progress with the checkpoint tool. " +
|
|
"Only the returned path is persistent — work anywhere else, including the host's /tmp, is outside LayerFS management; " +
|
|
"the workspace also carries .tmp/ and .cache/ scratch directories (exec points TMPDIR and XDG_CACHE_HOME at them), which checkpoint and publish never capture.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name, e.g. website" },
|
|
branch: { type: "string", description: "branch to work on (default main)" },
|
|
source: { type: "string", description: "the directory the user chose for this project; imported when the project is first created, ignored afterwards" },
|
|
},
|
|
required: ["project", "source"],
|
|
},
|
|
async execute(args, callCtx) {
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
|
// ctx.directory is magpie's config directory, never a default
|
|
// source: it holds plugin credentials. It is refused as a
|
|
// source here (and in the backend) like the other blocked roots.
|
|
if (args.source === undefined) throw new Error(
|
|
"source is required: the directory to import when the project is first created — pass the directory the user chose for this project")
|
|
const source = checkSourceDir(str(args.source, "source"), { configDir: ctx.directory })
|
|
return mutate((b) => b.provision(project, branch, source, callingAgent(callCtx)))
|
|
},
|
|
},
|
|
checkpoint: {
|
|
description:
|
|
"Saves the workspace's current state as a deduplicated checkpoint on its branch: only blobs the store has not seen are written. " +
|
|
"The real cost model: the changed blobs, plus one commit record per checkpoint holding the tree's full manifest — " +
|
|
"for a wide tree the manifests are a real part of the store's bytes, and the storage accounting counts them. " +
|
|
"Answers the commit id and the added / modified / deleted counts with the new-bytes and saved-bytes accounting.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name" },
|
|
branch: { type: "string", description: "branch the workspace belongs to (default main)" },
|
|
message: { type: "string", description: "what this checkpoint did" },
|
|
},
|
|
required: ["project"],
|
|
},
|
|
async execute(args, callCtx) {
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
|
return mutate((b) => b.checkpoint(project, branch, opt(args.message, "message", ""), callingAgent(callCtx)))
|
|
},
|
|
},
|
|
fork: {
|
|
description:
|
|
"Forks a branch of a project for a parallel agent. A fork is a pointer at an existing checkpoint: it copies no file bytes and is ready immediately, " +
|
|
"where copying the tree for another agent costs the whole tree's size and time. Provision the new branch to get its workspace path.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name" },
|
|
branch: { type: "string", description: "the new branch's name" },
|
|
from: { type: "string", description: "branch to fork from (default main)" },
|
|
},
|
|
required: ["project", "branch"],
|
|
},
|
|
async execute(args, callCtx) {
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(str(args.branch, "branch"))
|
|
const from = checkBranch(opt(args.from, "from", "main"))
|
|
return mutate((b) => b.fork(project, branch, from, callingAgent(callCtx)))
|
|
},
|
|
},
|
|
publish: {
|
|
description:
|
|
"Publishes a branch's head as main's new state (a Layer), so the work every agent did on that branch becomes what new work forks from. " +
|
|
"Guarded: main's current head must be in the branch's history, so a publish can only move main forward; if main has newer checkpoints the branch never saw, " +
|
|
"the publish is refused and says so. Pass force: true only to overwrite deliberately; the result then reports overwrote and the previous main head.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name" },
|
|
branch: { type: "string", description: "branch to publish to main" },
|
|
force: { type: "boolean", description: "overwrite main even if it has checkpoints the branch never saw (default false)" },
|
|
},
|
|
required: ["project", "branch"],
|
|
},
|
|
async execute(args, callCtx) {
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(str(args.branch, "branch"))
|
|
return mutate((b) => b.publish(project, branch, { force: args.force === true, agent: callingAgent(callCtx) }))
|
|
},
|
|
},
|
|
exec: {
|
|
description:
|
|
"Runs a shell command inside a branch's provisioned workspace and checkpoints whatever it changed as one commit: run, test, fix, all captured in the branch's history. " +
|
|
"DISABLED by default: the command runs with the plugin host's privileges, and the host serves these tools to remote callers holding a gateway key, so a shell is not something a model key should silently become. " +
|
|
"It runs only when the user has opted in — the plugin's \"exec\" option set to true, or the exec switch in the host's environment. " +
|
|
"A command that changes nothing commits nothing. A failing command's changes are still checkpointed (history can be rewound), and its exit code, stdout and stderr are returned. " +
|
|
"Only the workspace path is persistent: the command runs with TMPDIR and XDG_CACHE_HOME redirected into the workspace (.tmp/ and .cache/), " +
|
|
"workspace-local scratch that checkpoint and publish never capture, and files written to the host's real /tmp are likewise outside LayerFS management. " +
|
|
"The timeout is capped at 55 seconds, the tools budget.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name" },
|
|
branch: { type: "string", description: "branch whose workspace to run in (default main)" },
|
|
command: { type: "string", description: "the shell command to run in the workspace" },
|
|
message: { type: "string", description: "checkpoint message (default: the command itself)" },
|
|
timeoutMs: { type: "number", description: "timeout in milliseconds (default 50000, capped at 55000)" },
|
|
},
|
|
required: ["project", "command"],
|
|
},
|
|
async execute(args, callCtx) {
|
|
if (!execEnabled()) throw new Error(
|
|
"layerfs_exec is disabled by default: it runs shell commands with the plugin host's privileges, and these tools are reachable by any caller holding a gateway key. " +
|
|
"To enable it, the user sets the plugin's \"exec\" option to true in the host's plugin options, or turns on the exec switch in the plugin host's environment (see the package's README), and restarts the host.")
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
|
const command = str(args.command, "command")
|
|
const message = args.message === undefined ? "" : str(args.message, "message")
|
|
const timeoutMs = args.timeoutMs === undefined ? 50000 : Number(args.timeoutMs) || 50000
|
|
return mutate((b) => b.exec(project, branch, command, message, timeoutMs, callingAgent(callCtx)))
|
|
},
|
|
},
|
|
history: {
|
|
description:
|
|
"Lists a branch's checkpoints, newest first: commit id, message, time, file count and the logical size of the tree at that point, " +
|
|
"plus how many new bytes that checkpoint actually stored. The history is shared and durable: any agent can read what every other agent committed.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name" },
|
|
branch: { type: "string", description: "branch to read (default main)" },
|
|
limit: { type: "number", description: "how many checkpoints to return (default 20)" },
|
|
},
|
|
required: ["project"],
|
|
},
|
|
async execute(args) {
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
|
const limit = args.limit === undefined ? 20 : Math.max(1, Math.min(200, Number(args.limit) || 20))
|
|
return call((b) => b.history(project, branch, limit))
|
|
},
|
|
},
|
|
resolve: {
|
|
description:
|
|
"Resolves a logical LayerFS location to a real filesystem path without copying anything: the workspace path for a project branch, " +
|
|
"or one file inside it, with the checkpoint that path currently answers for and, for a file, its content hash and size. " +
|
|
"Use it to find where a branch lives before reading or handing the path to another tool.",
|
|
args: {
|
|
type: "object",
|
|
properties: {
|
|
project: { type: "string", description: "LayerFS project name" },
|
|
branch: { type: "string", description: "branch to resolve (default main)" },
|
|
path: { type: "string", description: "a file path inside the workspace, relative to its root" },
|
|
},
|
|
required: ["project"],
|
|
},
|
|
async execute(args) {
|
|
const project = checkProject(str(args.project, "project"))
|
|
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
|
const inner = args.path === undefined || args.path === "" ? "" : checkInnerPath(str(args.path, "path"))
|
|
return call((b) => b.resolve(project, branch, inner))
|
|
},
|
|
},
|
|
status: {
|
|
description:
|
|
"Reports the LayerFS backend in use, the projects and branches it holds, and the storage accounting: " +
|
|
"the logical bytes of every checkpoint ever taken against the bytes the deduplicated store actually occupies, and the ratio between them.",
|
|
args: { type: "object", properties: {} },
|
|
async execute() {
|
|
return call((b) => b.status())
|
|
},
|
|
},
|
|
},
|
|
}
|
|
}
|