zycode 0.1.0: zycode as a magpie agent through a reversible agent.toml (#1104)

Adds `@magpie-community/agent-zycode` 0.1.0: zycode (`zypi`, the VS Code extension, the ACP agent) on magpie's Agents page. magpie writes the model, gateway URL and key to `~/.pi-python/local.env`. A host part (`bridge.mjs`) copies them into the `[model]` table of `agent.toml` as text, and puts the file back byte for byte on disconnect, keeping any edits the user made meanwhile.

Reviewed at 618771e7c9269c8248599f05cd86eb18e00c358f:
- WSL Ubuntu 24.04, Bun 1.4.2: `bun test` in packages/zycode 20 pass; `bun scripts/check.mjs zycode` exit 0.
- Broken by hand: disconnect leaving agent.toml as is (`const back = current`) turns 9 of 20 red.
- No network and no child processes; local files only, temp-and-rename, symlinks refused.
- Real run by the author (Ubuntu VM, zypi 0.9.1, magpie v0.1.4069): only the four [model] lines changed; one turn answered through magpie (Usage shows zycode, 4 calls); after disconnect, agent.toml and local.env have identical sha256.

Not tried: Windows, macOS, the VS Code extension's frozen agent binary.

Co-authored-by: zy1233 <zy1233@users.noreply.github.com>
This commit is contained in:
zhangy
2026-11-13 23:17:06 +08:00
committed by GitHub
co-authored by zy1233
parent 8647819cd1
commit a410afe0d9
8 changed files with 670 additions and 0 deletions
+1
View File
@@ -293,6 +293,7 @@ it off puts the config back.
| [minimax-design](packages/minimax-design) | [MiniMax Design](https://design.minimax.io), the local multimodal creation studio: one custom-model entry in `%APPDATA%\@hilo\desktop\hub-config.json` whose model menu follows magpie's list; Windows only |
| [eta](packages/eta) | [Eta](https://github.com/Lingwcy/eta): connect-only local gateway integration; choose models and routing groups in Eta’s own picker after restarting. Requires Eta 0.1.164 or later |
| [rhino9-ai](packages/rhino9-ai) | [Magpie-Rhino](https://github.com/mikidaren/Magpie-Rhino) for Rhino 9 on Windows, with Magpie models, custom groups and routing strategies through Rhino MCP. Install the companion `.yak`, restart Rhino once, then open its AI panel and choose **Magpie**; no command required |
| [zycode](packages/zycode) | [zycode](https://github.com/zy1233/pi-python) (`zypi`, the VS Code extension, the ACP agent): Magpie's model in the `[model]` table of `~/.pi-python/agent.toml`, set by a host part that follows `local.env` and puts the file back byte for byte; restart zycode after choosing a model |
```sh
magpie plugin add @magpie-community/agent-<name>
+62
View File
@@ -0,0 +1,62 @@
# @magpie-community/agent-zycode
[zycode](https://github.com/zy1233/pi-python) (the ACP agent `pi-agent-cli-lc`,
the terminal UI `zypi` and the VS Code extension `zycode.zycode`) as a magpie
agent. magpie has no setup of its own for zycode; with this plugin it is on
magpie's Agents page like the agents magpie ships with. Unofficial.
```sh
magpie plugin add @magpie-community/agent-zycode
```
Then pick one of magpie's models in zycode's row. zycode keeps its model in
the `[model]` table of `~/.pi-python/agent.toml` and its keys in
`~/.pi-python/local.env`. magpie edits `local.env`, and the host part of this
package copies the result into `[model]`, because magpie cannot edit TOML.
`~/.pi-python/local.env`, written by magpie:
```sh
MAGPIE_ZYCODE_MODEL=deepseek/deepseek-flash # magpie's model
MAGPIE_ZYCODE_API_KEY=magpie-zycode # zycode's own key, so Usage names it
MAGPIE_ZYCODE_BASE_URL=http://127.0.0.1:3425/v1
```
`~/.pi-python/agent.toml`, written by the host part:
```toml
[model]
provider = "openai"
id = "deepseek/deepseek-flash"
base_url = "http://127.0.0.1:3425/v1"
api_key_env = "MAGPIE_ZYCODE_API_KEY"
```
Only those four keys of `[model]` are set. `thinking_level`, `permission`,
`[[models]]`, comments and every other key stay as they are. If there is no
`agent.toml`, or it has no `[model]` table, one is made.
Picking zycode's own model again, or switching the plugin off or removing it,
puts `agent.toml` back as it was before: byte for byte when nobody changed it
meanwhile. If you or zycode (`--setup`) changed the file while it was
connected, only the lines magpie wrote are put back (or taken out), and your
change stays. The file as it was is kept in `~/.pi-python/.magpie-zycode.json`
(mode 0600) until then.
Restart zycode after a change: it reads `agent.toml` and `local.env` when it
starts. Its `/model` picker then lists the one model magpie set.
What it does not do:
- It writes `agent.toml` only when its `[model]` table is plain: a `model = {…}`
inline table, `model.id = …` keys, `[model.x]` tables, a `[model]` key that
spans several lines, or a symbolic link in place of `agent.toml` make it
stop and change nothing. magpie's log then says once why:
`zycode bridge paused, agent.toml left as it is: …`.
- It follows `~/.pi-python`. A `PI_HOME` that points elsewhere is not read.
- zycode's own thinking level is not touched: set `thinking_level` in
`agent.toml` as before.
- zycode sends the OpenAI SDK's User-Agent, so Usage names its requests by the
key `magpie-zycode`.
How agent plugins work: [usemagpie.ai/docs/plugins#agents](https://usemagpie.ai/docs/plugins#agents).
+255
View File
@@ -0,0 +1,255 @@
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { randomUUID } from "node:crypto"
import { agent } from "./zycode.agent.js"
export const KEY_ENV = "MAGPIE_ZYCODE_API_KEY"
export const URL_ENV = "MAGPIE_ZYCODE_BASE_URL"
export const MODEL_ENV = agent.model
const MANAGED = ["provider", "id", "base_url", "api_key_env"]
// a refusal says why; any other error is logged without its text
const refuse = (why) => Object.assign(new Error(why), { refusal: true })
export function pathsFor(home = os.homedir()) {
const env = agent.config.replace(/^~(?=\/|$)/, home)
if (!path.isAbsolute(env)) throw new Error("agent.config must be an absolute or ~/ path")
const dir = path.dirname(env)
return { env, toml: path.join(dir, "agent.toml"), state: path.join(dir, ".magpie-zycode.json") }
}
// What local.env says magpie wants, as zycode reads that file: KEY=value
// lines, the first line of a key counts, one pair of quotes is dropped.
// null while magpie is not connected (any of the three values missing).
export function wanted(envText) {
const found = {}
for (const raw of (envText ?? "").split(/\r?\n/)) {
let line = raw.trim()
if (!line || line.startsWith("#")) continue
if (line.startsWith("export ")) line = line.slice(7).trim()
const eq = line.indexOf("=")
if (eq < 1) continue
const name = line.slice(0, eq).trim()
if (![MODEL_ENV, KEY_ENV, URL_ENV].includes(name) || name in found) continue
let value = line.slice(eq + 1).trim()
if (value.length >= 2 && value[0] === value.at(-1) && `"'`.includes(value[0])) value = value.slice(1, -1)
found[name] = value
}
if (!found[MODEL_ENV] || !found[KEY_ENV] || !found[URL_ENV]) return null
const model = found[MODEL_ENV]
if (model.length > 200 || /[\u0000-\u001f\u007f]/.test(model)) throw refuse("Unusable model id in local.env")
let url
try { url = new URL(found[URL_ENV]) } catch { throw refuse("Unusable gateway URL in local.env") }
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw refuse("Unusable gateway URL in local.env")
return { model, url: found[URL_ENV] }
}
// --- the [model] table of agent.toml, edited as text -----------------------
// Only what is needed to find that one table: strings, comments and
// multi-line values are followed so that a "[model]" inside one is not
// taken for a header. Anything it cannot place safely is an error, and no
// file is written.
function scanLine(line, st) {
let i = 0
if (st.quote) {
const close = st.quote
let j = 0
while (j < line.length && !line.startsWith(close, j)) j += close[0] === '"' && line[j] === "\\" ? 2 : 1
if (j >= line.length) return
i = j + 3
st.quote = null
}
for (; i < line.length; i++) {
const c = line[i]
if (c === "#") return
if (c === '"' || c === "'") {
const triple = c.repeat(3)
if (line.startsWith(triple, i)) {
const end = line.indexOf(triple, i + 3)
if (end < 0) { st.quote = triple; return }
i = end + 2
continue
}
for (i++; i < line.length && line[i] !== c; i++) if (c === '"' && line[i] === "\\") i++
continue
}
if (c === "[" || c === "{") st.depth++
else if (c === "]" || c === "}") st.depth = Math.max(0, st.depth - 1)
}
}
const unquote = (s) => (/^(["']).*\1$/.test(s) ? s.slice(1, -1) : s)
function modelTable(text) {
const lines = text.split(/(?<=\n)/)
const st = { quote: null, depth: 0 }
let owner = -1 // line of the open table's header, -1 before the first
let header = -1
let end = lines.length
const keys = new Map()
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
const atStart = !st.quote && st.depth === 0
const t = line.trim()
if (atStart && t.startsWith("[")) {
const m = /^\[(\[)?\s*([^\]#]*?)\s*\]\]?\s*(#.*)?$/.exec(t)
if (!m) throw refuse("A table header in agent.toml is not readable")
const name = m[2].split(".").map((s) => unquote(s.trim())).join(".")
if (owner === header && header >= 0 && end === lines.length) end = i
owner = i
if (name === "model" || name.startsWith("model.")) {
if (m[1] || name !== "model" || header >= 0) throw refuse("agent.toml has a [model] layout this plugin does not edit")
header = i
}
continue
}
let entry
if (atStart) {
if (owner === -1 && /^\s*(["']?)model\1\s*[.=]/.test(line)) throw refuse("agent.toml sets model outside a [model] table")
const k = /^\s*(?:"([^"]*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*=/.exec(line)
if (k && header >= 0 && owner === header) {
const name = k[1] ?? k[2] ?? k[3]
if (keys.has(name)) throw refuse("agent.toml repeats a key of [model]")
entry = { i, line, multi: false }
keys.set(name, entry)
}
}
scanLine(line, st)
if (entry) entry.multi = st.quote !== null || st.depth > 0
}
if (st.quote || st.depth) throw refuse("agent.toml ends inside a value")
return { lines, header, end, keys }
}
const valueOf = (line) => {
const m = /^[^=]*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?\r?\n?$/.exec(line)
if (!m) return undefined
try { return m[1][0] === "'" ? m[1].slice(1, -1) : JSON.parse(m[1]) } catch { return undefined }
}
export function applyModel(text, { model, url }) {
const src = text ?? ""
const eol = src.includes("\r\n") ? "\r\n" : "\n"
const values = { provider: "openai", id: model, base_url: url, api_key_env: KEY_ENV }
const table = modelTable(src)
const make = (k, indent = "", nl = eol) => `${indent}${k} = ${JSON.stringify(values[k])}${nl}`
if (table.header < 0) {
const gap = src.trim() === "" ? "" : (src.endsWith("\n") ? "" : eol) + eol
return src + gap + `[model]${eol}` + MANAGED.map((k) => make(k)).join("")
}
const lines = [...table.lines]
const added = []
for (const k of MANAGED) {
const e = table.keys.get(k)
if (!e) { added.push(make(k)); continue }
if (e.multi) throw refuse(`[model] ${k} spans several lines`)
if (valueOf(e.line) === values[k]) continue
lines[e.i] = make(k, /^\s*/.exec(e.line)[0], /\r?\n$/.exec(e.line)?.[0] ?? "")
}
if (added.length) {
if (!lines[table.header].endsWith("\n")) lines[table.header] += eol
lines.splice(table.header + 1, 0, ...added)
}
return lines.join("")
}
// Takes magpie's lines out of text that was edited after the bridge wrote
// it: a line is put back, or removed, only while it still reads as the
// bridge wrote it. What the user changed since stays.
function revert(current, state) {
const was = modelTable(state.original ?? "")
const wrote = modelTable(state.last)
const now = modelTable(current)
if (now.header < 0) return current
const lines = [...now.lines]
const drop = new Set()
for (const k of MANAGED) {
const mine = now.keys.get(k)
if (!mine || mine.line !== wrote.keys.get(k)?.line) continue
const old = was.keys.get(k)
if (old) lines[mine.i] = old.line.endsWith("\n") || !mine.line.endsWith("\n") ? old.line : old.line + (/\r\n$/.test(mine.line) ? "\r\n" : "\n")
else drop.add(mine.i)
}
let next = lines.filter((_, i) => !drop.has(i))
if (was.header < 0) {
const left = modelTable(next.join(""))
const body = left.lines.slice(left.header + 1, left.end).some((l) => l.trim() !== "")
if (!body) next = next.filter((_, i) => i !== left.header && !(i > left.header && i < left.end))
}
const out = next.join("")
if (state.original !== null && out.trimEnd() === state.original.trimEnd()) return state.original
return out
}
// --- files ---------------------------------------------------------------
function read(file) {
try {
const st = fs.lstatSync(file)
if (!st.isFile()) throw refuse("The bridge edits only regular files")
return fs.readFileSync(file, "utf8")
} catch (e) {
if (e.code === "ENOENT") return null
throw e
}
}
function write(file, text, mode = 0o600) {
if (text === null) { fs.rmSync(file, { force: true }); return }
let keep = mode
try { keep = fs.statSync(file).mode & 0o777 } catch {}
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
const temp = path.join(path.dirname(file), `.magpie-${randomUUID()}.tmp`)
try {
fs.writeFileSync(temp, text, { mode: keep, flag: "wx" })
fs.renameSync(temp, file)
} finally {
fs.rmSync(temp, { force: true })
}
}
// One pass: make agent.toml say what local.env asks, or put it back.
export function sync(p = pathsFor()) {
const want = wanted(read(p.env))
const raw = read(p.state)
const state = raw === null ? null : JSON.parse(raw)
if (!want && !state) return "disconnected"
const current = read(p.toml)
if (want) {
const next = applyModel(current, want)
const kept = state ?? { version: 1, original: current }
if (!state || state.last !== next) write(p.state, JSON.stringify({ ...kept, last: next }))
if (next !== current) write(p.toml, next)
return "connected"
}
if (current !== null) {
const back = current === state.last ? state.original : revert(current, state)
if (back !== current) write(p.toml, back === null || (state.original === null && back.trim() === "") ? null : back)
}
fs.rmSync(p.state, { force: true })
return "disconnected"
}
export function startBridge(p = pathsFor(), { interval = 1000, onError = (e) => console.error(`zycode bridge paused, agent.toml left as it is${e.refusal ? `: ${e.message}` : ""}`) } = {}) {
let last
let lastError = ""
const tick = () => {
try {
const want = wanted(read(p.env))
const sig = JSON.stringify(want)
if (sig === last && !(want === null && read(p.state) !== null)) return
sync(p)
last = sig
lastError = ""
} catch (error) {
last = undefined
if (error.message !== lastError) onError(error)
lastError = error.message
}
}
tick()
const timer = setInterval(tick, interval)
timer.unref?.()
return () => clearInterval(timer)
}
+20
View File
@@ -0,0 +1,20 @@
import { pathsFor, startBridge, sync } from "./bridge.mjs"
const instance = Symbol.for("magpie.zycode.bridge.v1")
// The agent file runs in moejs, which edits json, yaml and env but not
// TOML. This part runs in magpie's plugin host and puts what magpie wrote
// to local.env into the [model] table of agent.toml, and takes it out again.
export default async function ZycodeBridgePlugin() {
if (!globalThis[instance]) {
const paths = pathsFor()
globalThis[instance] = { stop: startBridge(paths) }
// magpie takes its lines out of local.env before it closes the host on
// disable or removal: undo agent.toml on the way out, without waiting
// for the next poll.
process.once("exit", () => {
try { sync(paths) } catch (e) { console.error(`zycode bridge paused, agent.toml left as it is${e.refusal ? `: ${e.message}` : ""}`) }
})
}
return {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@magpie-community/agent-zycode",
"version": "0.1.0",
"description": "zycode as a magpie agent: pick one of magpie's models for it on the Agents page",
"type": "module",
"main": "./index.mjs",
"files": ["zycode.agent.js", "index.mjs", "bridge.mjs", "README.md"],
"keywords": ["magpie", "magpie-agent", "zycode", "llm-gateway"],
"license": "MIT",
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/zycode" },
"magpie": { "agent": "./zycode.agent.js" }
}
+21
View File
@@ -0,0 +1,21 @@
// zycode (https://github.com/zy1233/pi-python) reads its model from the
// [model] table of ~/.pi-python/agent.toml, and its keys from
// ~/.pi-python/local.env. magpie cannot edit TOML, so magpie writes the
// three values to local.env, where it can, and index.mjs puts them into
// the [model] table (see bridge.mjs).
export const agent = {
id: "zycode",
name: "zycode",
bin: "zypi",
dir: "~/.pi-python",
config: "~/.pi-python/local.env",
model: "MAGPIE_ZYCODE_MODEL",
notice: "zycode reads its settings when it starts: restart it to use the new model.",
}
export function connect({ gateway }) {
return {
MAGPIE_ZYCODE_API_KEY: gateway.key,
MAGPIE_ZYCODE_BASE_URL: gateway.v1,
}
}
+298
View File
@@ -0,0 +1,298 @@
import { afterEach, beforeEach, expect, test } from "bun:test"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { KEY_ENV, applyModel, pathsFor, startBridge, sync, wanted } from "./bridge.mjs"
import { agent, connect } from "./zycode.agent.js"
const gateway = { url: "http://127.0.0.1:3425", v1: "http://127.0.0.1:3425/v1", key: "magpie-zycode" }
// What magpie writes to local.env for this agent: the model, then connect's keys
const envText = (model, extra = "") =>
`${extra}MAGPIE_ZYCODE_MODEL=${model}\nMAGPIE_ZYCODE_API_KEY=magpie-zycode\n# magpie: points at magpie's local gateway\nMAGPIE_ZYCODE_BASE_URL=${gateway.v1}\n`
// A real-looking agent.toml: comments, unknown keys, a multi-line string
// that holds a line that looks like a header, and tables after [model].
const user = `# my zycode
permission = "ask" # ask | auto | always-approve
thinking_level = "off"
future_key = { nested = [1, 2, 3] }
[model]
provider = "deepseek" # my own provider
id = "deepseek-ai/DeepSeek-V4-Flash"
base_url = "https://api.example.com/v1"
api_key_env = "REAL_LLM_API_KEY"
reasoning = true
unknown_model_key = "keep"
[[models]]
id = "deepseek-ai/DeepSeek-V4-Pro"
[prompt]
append_system_prompt = """
[model]
id = "not a header"
"""
[skills]
paths = [
"~/.pi-python/skills",
".pi/skills",
]
`
let root
let p
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-zycode-"))
p = pathsFor(root)
fs.mkdirSync(path.dirname(p.toml), { recursive: true })
})
afterEach(() => fs.rmSync(root, { recursive: true, force: true }))
const put = (file, text) => fs.writeFileSync(file, text)
const get = (file) => (fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null)
const pick = (model, extra) => put(p.env, envText(model, extra))
const off = (extra = "") => put(p.env, extra)
test("names zycode and where it keeps its model", () => {
expect(agent).toMatchObject({ id: "zycode", name: "zycode", config: "~/.pi-python/local.env", model: "MAGPIE_ZYCODE_MODEL" })
expect(agent.dir).toBe("~/.pi-python")
})
test("connect gives zycode the gateway and its own key", () => {
const out = connect({ gateway, model: { id: "deepseek/pro" }, models: [], agent: { id: "zycode", config: "/home/u/.pi-python/local.env" } })
expect(out).toEqual({ MAGPIE_ZYCODE_API_KEY: "magpie-zycode", MAGPIE_ZYCODE_BASE_URL: "http://127.0.0.1:3425/v1" })
expect(Object.keys(out)).toContain(KEY_ENV)
})
test("declares a plain agent package with a host part and no dependencies", () => {
const pkg = JSON.parse(fs.readFileSync(new URL("./package.json", import.meta.url), "utf8"))
expect(pkg.name).toBe("@magpie-community/agent-zycode")
expect(pkg.magpie.agent).toBe("./zycode.agent.js")
expect(pkg.main).toBe("./index.mjs")
expect(pkg.dependencies).toBeUndefined()
expect(pkg.scripts).toBeUndefined()
for (const f of ["zycode.agent.js", "index.mjs", "bridge.mjs", "README.md"]) expect(pkg.files).toContain(f)
})
test("reads what magpie wrote, as zycode reads local.env", () => {
expect(wanted(envText("deepseek/pro"))).toEqual({ model: "deepseek/pro", url: gateway.v1 })
expect(wanted(`export MAGPIE_ZYCODE_MODEL="a/b"\nMAGPIE_ZYCODE_API_KEY='k'\nMAGPIE_ZYCODE_BASE_URL=http://localhost:3425/v1\n`)).toEqual({ model: "a/b", url: "http://localhost:3425/v1" })
expect(wanted("")).toBeNull()
expect(wanted(null)).toBeNull()
expect(wanted("MAGPIE_ZYCODE_MODEL=a/b\nMAGPIE_ZYCODE_API_KEY=k\n")).toBeNull()
expect(() => wanted("MAGPIE_ZYCODE_MODEL=a\nMAGPIE_ZYCODE_API_KEY=k\nMAGPIE_ZYCODE_BASE_URL=ftp://127.0.0.1:3425/v1\n")).toThrow()
expect(() => wanted("MAGPIE_ZYCODE_MODEL=a\nMAGPIE_ZYCODE_API_KEY=k\nMAGPIE_ZYCODE_BASE_URL=not a url\n")).toThrow()
expect(() => wanted("MAGPIE_ZYCODE_MODEL=a\nMAGPIE_ZYCODE_API_KEY=k\nMAGPIE_ZYCODE_BASE_URL=http://user:pass@127.0.0.1:3425/v1\n")).toThrow()
})
test("connect: a home with no agent.toml gets a [model] table, and disconnect removes the file", () => {
pick("deepseek/pro")
expect(sync(p)).toBe("connected")
expect(get(p.toml)).toBe(
`[model]\nprovider = "openai"\nid = "deepseek/pro"\nbase_url = "http://127.0.0.1:3425/v1"\napi_key_env = "MAGPIE_ZYCODE_API_KEY"\n`,
)
off()
expect(sync(p)).toBe("disconnected")
expect(get(p.toml)).toBeNull()
expect(get(p.state)).toBeNull()
})
test("connect: replaces the four keys of [model] and keeps every other line", () => {
put(p.toml, user)
pick("deepseek/pro")
sync(p)
const out = get(p.toml)
expect(out).toBe(
user
.replace(/^provider = .*$/m, 'provider = "openai"')
.replace(/^id = "deepseek-ai\/DeepSeek-V4-Flash"$/m, 'id = "deepseek/pro"')
.replace(/^base_url = .*$/m, 'base_url = "http://127.0.0.1:3425/v1"')
.replace(/^api_key_env = .*$/m, 'api_key_env = "MAGPIE_ZYCODE_API_KEY"'),
)
// the unknown key, the comments, [[models]] and the string that holds "[model]" are all still there
for (const kept of ["# my zycode", "future_key = { nested = [1, 2, 3] }", 'unknown_model_key = "keep"', "reasoning = true", '[[models]]', '[model]\nid = "not a header"']) {
expect(out).toContain(kept)
}
})
test("switching the model changes only id, and disconnect still restores the first file", () => {
put(p.toml, user)
pick("deepseek/pro")
sync(p)
const first = get(p.toml)
pick("codex/gpt-5.5")
sync(p)
const second = get(p.toml)
expect(second).toBe(first.replace('id = "deepseek/pro"', 'id = "codex/gpt-5.5"'))
pick("deepseek/pro")
sync(p)
expect(get(p.toml)).toBe(first)
off()
sync(p)
expect(get(p.toml)).toBe(user)
})
test("disconnect restores the original file byte for byte, CRLF and a missing final newline included", () => {
const crlf = user.replaceAll("\n", "\r\n").replace(/\r\n$/, "")
put(p.toml, crlf)
pick("a/b")
sync(p)
expect(get(p.toml)).not.toBe(crlf)
expect(get(p.toml)).toContain('id = "a/b"\r\n')
off()
sync(p)
expect(Buffer.from(get(p.toml))).toEqual(Buffer.from(crlf))
})
test("a file with no [model] table gets one at the end, and loses it again", () => {
const plain = '# only a mode\npermission = "auto"\n\n[[models]]\nid = "x"'
put(p.toml, plain)
pick("a/b")
sync(p)
const out = get(p.toml)
expect(out.startsWith(plain + "\n\n[model]\n")).toBe(true)
off()
sync(p)
expect(get(p.toml)).toBe(plain)
})
test("a [model] table that lacks some keys gets them, and loses them again", () => {
const partial = '[model]\nprovider = "openai" # same as ours\nreasoning = false\n'
put(p.toml, partial)
pick("a/b")
sync(p)
const out = get(p.toml)
expect(out).toContain('provider = "openai" # same as ours\n')
expect(out).toContain('id = "a/b"')
expect(out).toContain("reasoning = false")
off()
sync(p)
expect(get(p.toml)).toBe(partial)
})
test("a second pass with nothing new writes nothing", () => {
put(p.toml, user)
pick("a/b")
sync(p)
const before = fs.statSync(p.toml).mtimeMs
const state = get(p.state)
sync(p)
expect(fs.statSync(p.toml).mtimeMs).toBe(before)
expect(get(p.state)).toBe(state)
})
test("keeps the file's own mode, and makes the state file private", () => {
if (process.platform === "win32") return
put(p.toml, user)
fs.chmodSync(p.toml, 0o640)
pick("a/b")
sync(p)
expect(fs.statSync(p.toml).mode & 0o777).toBe(0o640)
expect(fs.statSync(p.state).mode & 0o777).toBe(0o600)
})
test("an edit made while connected stays when magpie is switched off", () => {
put(p.toml, user)
pick("a/b")
sync(p)
// the user edits other lines and zycode --setup rewrites nothing of ours
put(p.toml, get(p.toml).replace('permission = "ask"', 'permission = "auto"').replace('reasoning = true', 'reasoning = false'))
off()
sync(p)
expect(get(p.toml)).toBe(user.replace('permission = "ask"', 'permission = "auto"').replace("reasoning = true", "reasoning = false"))
})
test("a [model] key the user changed while connected is not put back over their change", () => {
put(p.toml, user)
pick("a/b")
sync(p)
put(p.toml, get(p.toml).replace('id = "a/b"', 'id = "mine/own"'))
off()
sync(p)
const out = get(p.toml)
expect(out).toContain('id = "mine/own"')
expect(out).toContain('provider = "deepseek" # my own provider')
expect(out).toContain('api_key_env = "REAL_LLM_API_KEY"')
})
test("a table magpie made, with an edit made after it, is removed down to that edit", () => {
pick("a/b")
sync(p)
put(p.toml, `permission = "ask"\n\n` + get(p.toml))
off()
sync(p)
expect(get(p.toml)).toBe('permission = "ask"\n\n')
})
test("a file that is gone while connected is not brought back", () => {
put(p.toml, user)
pick("a/b")
sync(p)
fs.rmSync(p.toml)
off()
sync(p)
expect(get(p.toml)).toBeNull()
expect(get(p.state)).toBeNull()
})
test("refuses layouts it cannot edit safely and writes nothing", () => {
const bad = [
'model = { id = "x" }\n',
'model.id = "x"\n',
'[model]\nid = "x"\n[model.extra]\na = 1\n',
'[[model]]\nid = "x"\n',
'[model]\nid = """\nx\n"""\n',
'[model]\nid = "x"\nid = "y"\n',
"[model\nid = 1\n",
'[prompt]\nappend_system_prompt = """\nnever closed\n',
]
for (const text of bad) {
put(p.toml, text)
pick("a/b")
expect(() => sync(p)).toThrow()
try { sync(p) } catch (e) { expect(e.refusal).toBe(true) }
expect(get(p.toml)).toBe(text)
expect(get(p.state)).toBeNull()
}
})
test("refuses a symbolic link in place of agent.toml", () => {
if (process.platform === "win32") return
const real = path.join(root, "dotfiles-agent.toml")
put(real, user)
fs.symlinkSync(real, p.toml)
pick("a/b")
expect(() => sync(p)).toThrow()
expect(get(real)).toBe(user)
expect(fs.lstatSync(p.toml).isSymbolicLink()).toBe(true)
})
test("applyModel never changes a table it already matches", () => {
const done = applyModel(user, { model: "a/b", url: gateway.v1 })
expect(applyModel(done, { model: "a/b", url: gateway.v1 })).toBe(done)
})
test("the host part follows local.env: connect, switch, disconnect", () => {
put(p.toml, user)
const stop = startBridge(p, { interval: 20, onError: () => { throw new Error("bridge paused") } })
const settle = (ok) => new Promise((resolve, reject) => {
const t0 = Date.now()
const look = () => (ok() ? resolve() : Date.now() - t0 > 3000 ? reject(new Error("timeout")) : setTimeout(look, 10))
look()
})
return (async () => {
try {
pick("a/b")
await settle(() => get(p.toml).includes('id = "a/b"'))
pick("c/d")
await settle(() => get(p.toml).includes('id = "c/d"'))
off()
await settle(() => get(p.toml) === user && get(p.state) === null)
} finally {
stop()
}
})()
})
+1
View File
@@ -292,6 +292,7 @@
{ "package": "@magpie-community/page-harnessweight", "name": "HarnessWeight", "kind": "page", "community": true,
"summary": { "en": "Compare agent harnesses behind your gateway by input tokens, cache, failures, latency and estimated tool-definition size. Its local service reads this machine's usage ledger; a read-only hook samples tool sizes and tracks in-flight requests.", "zh": "按 Agent 对比网关后面的输入 token、缓存、失败率、延迟与工具定义体积估算。本机服务读取用量记录,只读 hook 采样工具大小并追踪进行中的请求。" } },
{ "package": "@magpie-community/agent-wave", "name": "Wave", "kind": "agent", "community": true, "icon": "https://github.com/wavetermdev.png", "summary": {"en": "Wave Terminal (waveterm) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Wave Terminal(waveterm)加到 magpie 的 Agent 页:给它选 magpie 的模型,关掉即恢复它原来的配置。"}},
{ "package": "@magpie-community/agent-zycode", "name": "zycode", "kind": "agent", "community": true, "summary": {"en": "zycode (zypi, the VS Code extension, the ACP agent) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put agent.toml back. A host part copies the model into the [model] table of agent.toml, because magpie cannot edit TOML. Restart zycode after a change.", "zh": "把 zycode(zypi、VS Code 扩展、ACP agent)加到 magpie 的 Agent 页:给它选 magpie 的模型,关掉即恢复 agent.toml。magpie 不能编辑 TOML,所以由宿主部分把模型写进 agent.toml 的 [model] 表。切换后需重启 zycode。"}},
{ "package": "magpie-dafeiyu", "name": "DaFeiYu Desktop Pet", "kind": "page",
"summary": { "en": "A guide page for DaFeiYu, a desktop pet that lights a bulb per request and shows quota percentages and API balances. The pet is a separate Windows/macOS app you download yourself; this page does not install or start it. Artwork from PC2005-cloud/dsh-pet, non-commercial use only.", "zh": "蓝色大肥鱼桌宠的使用指南页:几个请求亮几盏灯,订阅显示额度百分比,API 钱包显示余额。桌宠是需要另外下载的 Windows/macOS 独立 App,本页不会安装或启动它。角色素材来自 PC2005-cloud/dsh-pet,仅限非商用。" } }
]