Files
yetone 319b0a6459 layerfs 0.10.2: the page shows its empty state before the first project, not Connecting for good
AlanWang1027713 on X (magpie v0.1.4026, macOS): Plugins -> LayerFS
轨迹 stays on "Connecting to the local trajectory service…".

The page's boot.js jumps its frame to the host's service on 43717, and
the service started only once a store with a project existed. With no
store the jump is refused. The README said the frame then shows the
browser's refused-to-connect page; that is Chromium. A WebKit frame
(magpie's window on macOS and Linux) keeps the old document when its
jump is refused, so it said Connecting for good.

The service now starts when the host loads, store or no store. With no
store (or an empty projects folder) it answers an empty recording
without building the backend, so nothing is written under ~ until a
tool call makes the first project. The empty state now reloads itself
every 5s like the full page, so the first provision shows up without
reopening the page. The retry on a held port no longer waits for a
store, and the store-race recheck it needed is gone.

Run on mote (Bun 1.4.2, temp HOME):
- bun test packages/layerfs: 69 pass, 0 fail. bun scripts/check.mjs: 0.
- Broken by hand: 0.10.1's index.mjs and app.js turn the two new
  tests red (the no-store service test and the empty-state reload).
- Real browsers (Playwright 1.62.0): a sandboxed frame doing boot.js's
  jump against a no-store host. 0.10.1: WebKit's frame stays on
  "Connecting to the local trajectory service…", Chromium's shows
  chrome-error. 0.10.2: both show the zh empty state
  ("还没有记录到轨迹…").

Not tried: the page inside the real magpie window with the plugin
installed.
2026-11-13 17:07:35 +08:00

310 lines
17 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. With no store
// it serves the empty state; 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, at load, store or no
// store: the installed page jumps its frame to it, and a WebKit frame
// whose jump is refused keeps showing "Connecting…" for good (0.10.1 and
// before started it only once a store existed). With no store it serves
// the page's empty state and builds no backend, so nothing is written
// under ~ until a tool call makes the first project. The start is off
// the tool calls' path and every failure is swallowed: a held port or a
// failed read leaves the tools untouched.
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 with backoff, without keeping an otherwise
// finished host alive.
let service = null
let starting = null
let retryTimer = null
let retryDelay = 1000
const retry = () => {
if (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)
}
// What the service serves: the store's trajectory once a store exists,
// else an empty recording, so the page shows its empty state (and
// reloads itself into the first project) instead of a frame that never
// lands. The store is looked for without building the backend: its
// constructor is what creates the store's folders, and a user with no
// store gets nothing written.
const empty = () => ({ projects: [], events: [], generatedAt: new Date().toISOString() })
const pageBackend = {
trajectory: async () => {
try {
if (!readdirSync(join(storeHome(), "projects")).length) return empty()
} catch {
return empty()
}
return (await backend()).trajectory()
},
}
const ensureService = () => {
if (service?.server.listening) return Promise.resolve()
if (starting) return starting
if (retryTimer) {
clearTimeout(retryTimer)
retryTimer = null
}
starting = (async () => {
const candidate = startPageService({ backend: pageBackend, 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
})
return starting
}
ensureService().catch(() => { /* no service: the tools are untouched */ })
// A mutating call: the service, up since load, reads the store it
// writes on the page's next reload.
const mutate = call
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())
},
},
},
}
}