proc: a Linux zombie no longer holds a lock (#1198)

yetihan (#1198): a lock whose owner is a Linux zombie was held for
good. process.kill(pid, 0) succeeds on a zombie, so 15 packages' lock
and liveness checks counted an exited, unreaped owner as alive.

- scripts/proc.mjs: processStatus(pid) is dead on ESRCH, and on Linux
  also when /proc/<pid>/stat says Z or X; EPERM is "permission", any
  other error "unknown". processAlive / processExists keep each
  caller's old EPERM and unknown-error meaning.
- scripts/sync-proc.mjs copies it into each package (--check in the
  tests); every package's own check keeps its old semantics, now with
  zombies dead. agent-console's daemon bundle and window-warmup's dist
  are rebuilt.
- 15 packages bumped.

Review run at 28ef6622 (mote, HOME=$(mktemp -d)):
- node scripts/sync-proc.mjs --check: ok.
- bun test (whole repo): 8934 pass, 0 fail.
- bun scripts/check.mjs: every package ok.
- window-warmup's build reproduces its dist/plugin.js byte for byte.
  agent-console's bundle diff read line by line: the proc module plus
  esbuild's renumbered imports, nothing else (esbuild isn't installed
  on mote, so it wasn't rebuilt there).
- Real zombie on Linux (WSL, magpie-desktop): a bash child left
  unreaped by an exec'd sleep, /proc stat "Z": the old kill(0) check
  says alive, processStatus says dead; the running process says alive.

Not tried: each package's lock contention end to end.
This commit is contained in:
zhou.han
2026-11-16 12:19:09 +08:00
committed by GitHub
parent 0b0b180957
commit 9e86a2c7b7
63 changed files with 1391 additions and 158 deletions
+72 -30
View File
@@ -8218,7 +8218,7 @@ __export(legacy_exports, {
});
import { cp as cp2, mkdir as mkdir8, readdir as readdir6, readFile as readFile18 } from "node:fs/promises";
import { existsSync as existsSync14 } from "node:fs";
import { join as join20 } from "node:path";
import { join as join21 } from "node:path";
function stamp() {
const d = /* @__PURE__ */ new Date();
const p = (n) => String(n).padStart(2, "0");
@@ -8227,17 +8227,17 @@ function stamp() {
async function migrateLegacy(dataDir, stores) {
const settings = await stores.settings.get();
if (settings.v1Migrated) return { migrated: 0, skipped: true };
const oldDir = join20(dataDir, "sessions");
const oldSettingsPath = join20(dataDir, "settings.json");
const oldDir = join21(dataDir, "sessions");
const oldSettingsPath = join21(dataDir, "settings.json");
if (!existsSync14(oldDir) && !existsSync14(oldSettingsPath)) {
await stores.settings.set({ v1Migrated: true });
return { migrated: 0, skipped: true };
}
const backup = join20(dataDir, "trash", `legacy-${stamp()}`);
const backup = join21(dataDir, "trash", `legacy-${stamp()}`);
await mkdir8(backup, { recursive: true });
if (existsSync14(oldDir)) await cp2(oldDir, join20(backup, "sessions"), { recursive: true }).catch(() => {
if (existsSync14(oldDir)) await cp2(oldDir, join21(backup, "sessions"), { recursive: true }).catch(() => {
});
if (existsSync14(oldSettingsPath)) await cp2(oldSettingsPath, join20(backup, "settings.json")).catch(() => {
if (existsSync14(oldSettingsPath)) await cp2(oldSettingsPath, join21(backup, "settings.json")).catch(() => {
});
const oldSettings = existsSync14(oldSettingsPath) ? JSON.parse(await readFile18(oldSettingsPath, "utf8").catch(() => "{}")) : {};
const projectIdByPath = /* @__PURE__ */ new Map();
@@ -8253,13 +8253,13 @@ async function migrateLegacy(dataDir, stores) {
}
let sessionIds = [];
try {
sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync14(join20(oldDir, d, "meta.json")));
sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync14(join21(oldDir, d, "meta.json")));
} catch {
}
const metas = [];
for (const id2 of sessionIds) {
try {
const m = JSON.parse(await readFile18(join20(oldDir, id2, "meta.json"), "utf8"));
const m = JSON.parse(await readFile18(join21(oldDir, id2, "meta.json"), "utf8"));
if (m?.cwd) metas.push(m);
} catch {
}
@@ -8292,7 +8292,7 @@ async function migrateLegacy(dataDir, stores) {
return best ? projectIdByPath.get(best) : null;
};
let migrated = 0;
const threadsDir = join20(dataDir, "threads");
const threadsDir = join21(dataDir, "threads");
for (const m of metas) {
try {
const projectId = projectOf(m.cwd);
@@ -8329,10 +8329,10 @@ async function migrateLegacy(dataDir, stores) {
importedFrom: m.cliSessionId ? { provider, sessionId: m.cliSessionId } : void 0,
seq: 0
};
const tdir = join20(threadsDir, meta.id);
const tdir = join21(threadsDir, meta.id);
if (existsSync14(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80);
await mkdir8(join20(threadsDir, meta.id), { recursive: true });
const oldEvts = (await readFile18(join20(oldDir, m.id, "events.jsonl"), "utf8").catch(() => "")).split("\n").filter((l) => l.trim()).map((l) => {
await mkdir8(join21(threadsDir, meta.id), { recursive: true });
const oldEvts = (await readFile18(join21(oldDir, m.id, "events.jsonl"), "utf8").catch(() => "")).split("\n").filter((l) => l.trim()).map((l) => {
try {
return JSON.parse(l);
} catch {
@@ -8411,9 +8411,9 @@ async function migrateLegacy(dataDir, stores) {
seq++;
lines.push({ type: "tool_call", itemId: key, kind: "other", title: o.title, status: "failed", seq, ts: Date.now(), threadId: meta.id });
}
for (const ev of lines) await appendJsonl(join20(threadsDir, meta.id, "timeline.jsonl"), ev);
for (const ev of lines) await appendJsonl(join21(threadsDir, meta.id, "timeline.jsonl"), ev);
meta.seq = seq;
await writeJsonAtomic(join20(threadsDir, meta.id, "meta.json"), meta);
await writeJsonAtomic(join21(threadsDir, meta.id, "meta.json"), meta);
migrated++;
} catch (e) {
log("warn", "\u8FC1\u79FB\uFF1A\u4F1A\u8BDD\u5931\u8D25", { id: m.id, err: String(e) });
@@ -8478,7 +8478,7 @@ var init_warm = __esm({
// daemon/src/main.ts
import { mkdirSync as mkdirSync2, rmSync as rmSync2, chmodSync as chmodSync2 } from "node:fs";
import { join as join21, dirname as dirname9 } from "node:path";
import { join as join22, dirname as dirname9 } from "node:path";
import { fileURLToPath as fileURLToPath4 } from "node:url";
// daemon/src/config.ts
@@ -10718,14 +10718,56 @@ var TerminalService = class {
// daemon/src/util/proc.ts
init_pathscan();
import { delimiter } from "node:path";
function pidAlive(pid, kill = (p, s) => process.kill(p, s)) {
if (!Number.isInteger(pid) || pid <= 0) return false;
// lib/proc.mjs
import { readFileSync as readFileSync2 } from "node:fs";
import { join as join19 } from "node:path";
var errCode = (error) => error && typeof error === "object" ? error.code : void 0;
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
function processZombie(pid, {
procRoot = "/proc",
readFile: readFile19 = (file) => readFileSync2(file, "utf8")
} = {}) {
if (!validPid(pid)) return false;
let stat14;
try {
stat14 = readFile19(join19(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat14 === "string" ? stat14.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state2 = stat14.slice(commEnd + 1).trim()[0];
return state2 === "Z" || state2 === "X";
}
function processAlive(pid, deps = {}) {
const state2 = processStatus(pid, deps).state;
return state2 === "alive" || state2 === "permission";
}
function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
return true;
} catch (e) {
return e?.code === "EPERM";
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
// daemon/src/util/proc.ts
function pidAlive(pid, kill = (p, s) => process.kill(p, s), deps = {}) {
return processAlive(pid, { ...deps, kill });
}
function augmentPath(env, nodeDir, platform = process.platform, home) {
const win = platform === "win32";
@@ -10747,9 +10789,9 @@ function augmentPath(env, nodeDir, platform = process.platform, home) {
init_proxy();
// daemon/src/preview/ports.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { readFileSync as readFileSync3 } from "node:fs";
import { homedir as homedir11 } from "node:os";
import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute5, join as join19 } from "node:path";
import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute5, join as join20 } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
var MAGPIE_DEFAULT_PORTS = [3425, 3430];
var GATE_DEFAULT_PORT = 3488;
@@ -10782,13 +10824,13 @@ function magpieConfigDirs(env = process.env, where = {}) {
const cwd = where.cwd ?? (env === process.env ? process.cwd() : "");
if (cwd && basename5(cwd) === "plugin-work") add(dirname8(cwd));
const x = env.XDG_CONFIG_HOME;
if (x && isAbsolute5(x)) add(join19(x, "magpie"));
if (x && isAbsolute5(x)) add(join20(x, "magpie"));
const platform = where.platform ?? process.platform;
const home = where.home ?? (env === process.env ? homedir11() : platform === "win32" ? env.USERPROFILE : env.HOME);
if (home) add(join19(home, ".config", "magpie"));
if (home) add(join20(home, ".config", "magpie"));
return out;
}
function savedGatewayPort(file, read = (f) => readFileSync2(f, "utf8")) {
function savedGatewayPort(file, read = (f) => readFileSync3(f, "utf8")) {
let raw;
try {
raw = read(file);
@@ -10811,7 +10853,7 @@ function previewDeniedPorts(cfg2, env = process.env, opts = {}) {
if (p) out.add(p);
}
for (const d of opts.configDirs ?? magpieConfigDirs(env)) {
const p = savedGatewayPort(join19(d, "settings.json"), opts.read);
const p = savedGatewayPort(join20(d, "settings.json"), opts.read);
if (p) out.add(p);
}
const extra = env.AGENT_CONSOLE_PREVIEW_DENY;
@@ -10841,10 +10883,10 @@ process.on("unhandledRejection", (e) => {
async function main() {
initLog(cfg.dataDir);
for (const d of ["threads", "attachments", "trash", "logs"]) {
mkdirSync2(join21(cfg.dataDir, d), { recursive: true });
mkdirSync2(join22(cfg.dataDir, d), { recursive: true });
}
const appDir = join21(dirname9(fileURLToPath4(import.meta.url)), "..", "..", "app");
const attachments = new AttachmentStore(join21(cfg.dataDir, "attachments"));
const appDir = join22(dirname9(fileURLToPath4(import.meta.url)), "..", "..", "app");
const attachments = new AttachmentStore(join22(cfg.dataDir, "attachments"));
const { bindAttachmentStore: bindAttachmentStore2 } = await Promise.resolve().then(() => (init_attachmentRefs(), attachmentRefs_exports));
bindAttachmentStore2(attachments);
const settings = new SettingsStore(cfg.dataDir);
@@ -10918,7 +10960,7 @@ async function main() {
const { warmProviderCache: warmProviderCache2 } = await Promise.resolve().then(() => (init_warm(), warm_exports));
await warmProviderCache2(await settings.get());
})().catch((e) => log("warn", "Provider \u9884\u70ED\u5931\u8D25", { err: String(e) }));
const daemonJsonPath = join21(cfg.dataDir, "daemon.json");
const daemonJsonPath = join22(cfg.dataDir, "daemon.json");
await writeJsonAtomic(daemonJsonPath, {
pid: process.pid,
port: cfg.port,
File diff suppressed because one or more lines are too long
+13 -8
View File
@@ -1,16 +1,21 @@
// Small process/environment helpers: cross-platform pid liveness, PATH completion.
import { delimiter } from "node:path";
import { extraBinDirs } from "../../../lib/pathscan.mjs";
import { processAlive } from "../../../lib/proc.mjs";
type ProcessAliveDeps = {
platform?: NodeJS.Platform;
procRoot?: string;
readFile?: (file: string) => string;
};
/** kill(pid, 0): ESRCH = gone; EPERM = exists but we may not signal it (common on Windows across sessions / elevated processes), counts as alive. */
export function pidAlive(pid: number, kill: (pid: number, sig: 0) => unknown = (p, s) => process.kill(p, s)): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
kill(pid, 0);
return true;
} catch (e) {
return (e as NodeJS.ErrnoException)?.code === "EPERM";
}
export function pidAlive(
pid: number,
kill: (pid: number, sig: 0) => unknown = (p, s) => process.kill(p, s),
deps: ProcessAliveDeps = {},
): boolean {
return processAlive(pid, { ...deps, kill });
}
/** Append nodeDir and common CLI install directories to the end of PATH (deduped; case-insensitive on Windows). Returns the new PATH string. */
+2 -9
View File
@@ -33,6 +33,7 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createGate } from "./lib/gate.mjs";
import { processAlive } from "./lib/proc.mjs";
import { NODE_TOO_OLD_MESSAGE, requireNode } from "./lib/pathscan.mjs";
const here = dirname(fileURLToPath(import.meta.url));
@@ -68,15 +69,7 @@ function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ESRCH = gone; EPERM = exists but we may not signal it (common on Windows), counts as alive
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return error?.code === "EPERM";
}
}
const pidAlive = processAlive;
// A failed log write (directory deleted, disk full) must never make the host's flow throw
function makeLogger(p) {
+8
View File
@@ -0,0 +1,8 @@
export type ProcessAliveDeps = {
kill?: (pid: number, signal: 0) => unknown;
platform?: NodeJS.Platform;
procRoot?: string;
readFile?: (file: string) => string;
};
export declare function processAlive(pid: number, deps?: ProcessAliveDeps): boolean;
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.3.8",
"version": "1.3.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@magpie-community/page-agent-console",
"version": "1.3.8",
"version": "1.3.9",
"license": "MIT",
"dependencies": {
"@agentclientprotocol/sdk": "2.1.0",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.3.8",
"version": "1.3.9",
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
"author": "qingnian108 (https://github.com/qingnian108)",
"homepage": "https://github.com/qingnian108/magpie-agent-console",
@@ -20,6 +20,7 @@
"app",
"daemon/dist",
"assets",
"proc.mjs",
"README.md",
"LICENSE",
"THIRD-PARTY-NOTICES.md"
@@ -260,7 +260,7 @@ describe("path normalization", () => {
});
describe("process utilities", () => {
it("pidAlive: EPERM counts as alive, ESRCH as dead", () => {
it("pidAlive: EPERM counts as alive, ESRCH as dead; Linux zombies are dead", () => {
const err = (code: string) => () => {
throw Object.assign(new Error(code), { code });
};
@@ -269,6 +269,14 @@ describe("process utilities", () => {
expect(pidAlive(123, () => true)).toBe(true);
expect(pidAlive(0, () => true)).toBe(false);
expect(pidAlive(process.pid)).toBe(true);
expect(pidAlive(123, () => true, {
platform: "linux",
procRoot: "/fake-proc",
readFile: (file: string) => {
if (file === "/fake-proc/123/stat") return "123 (comm)) Z 1";
throw Object.assign(new Error("missing"), { code: "ENOENT" });
},
})).toBe(false);
});
it("augmentPath: appends at the end, dedupes (case-insensitive on Windows), keeps the existing order", () => {
+1 -1
View File
@@ -119,7 +119,7 @@ test("the authenticated standalone page, bridge, live data and JSON options work
try {
const ping = await (await fetch(s.url + "api/ping")).json()
expect(ping.name).toBe("agent-office")
expect(ping.version).toBe("0.3.5")
expect(ping.version).toBe("0.3.6")
const page = await fetch(s.url)
expect(page.status).toBe(200)
expect(await page.text()).toContain('src="_magpie/bridge.js"')
+2 -4
View File
@@ -10,6 +10,7 @@ import { execFile } from "node:child_process"
import { existsSync, readFileSync, readdirSync } from "node:fs"
import { homedir } from "node:os"
import { join } from "node:path"
import { processExists } from "./proc.mjs"
const TTY_RE = /^\/dev\/ttys?\d+$/
const GUID_RE = /^[A-Za-z0-9_:-]{1,64}$/
@@ -75,10 +76,7 @@ function findBin(name, candidates = []) {
return name
}
function pidAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0) return false
try { process.kill(pid, 0); return true } catch (e) { return e?.code !== "ESRCH" }
}
const pidAlive = processExists
function runAsync(bin, args = [], timeout = 1200) {
return new Promise((resolve) => {
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+3 -4
View File
@@ -8,6 +8,7 @@ import { homedir } from "node:os"
import { basename, dirname, join } from "node:path"
import { StringDecoder } from "node:string_decoder"
import { createSessionReader, finalizeUsage, readClaude, readCodex, readCopilot, readCursor, readDsh, readGemini, readGrok, readKimi, readPi } from "./readers.mjs"
import { processExists } from "./proc.mjs"
const READ_CHUNK = 64 * 1024
const GUARD_BYTES = 64 // bounded prefix/end witnesses catch truncate-and-regrow between ticks
@@ -294,11 +295,9 @@ function zstd(path) {
throw new Error("no zstd here")
}
// whether a process with this pid is running: EPERM is someone else's, still
// whether a process with this pid exists: EPERM is someone else's, still
// running; only ESRCH says there is none
function pidAlive(pid) {
try { process.kill(pid, 0); return true } catch (e) { return e?.code !== "ESRCH" }
}
const pidAlive = processExists
// The sessions folder of a Claude-format agent: which session ids have a
// running process. null when it can't say: the folder has never held such a
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-agent-office",
"version": "0.3.5",
"version": "0.3.6",
"description": "我的 Agent 在干嘛:读取本机 Claude Code、Codex、Copilot CLI、Kimi Code、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy、Grok Build、Cursor 的会话文件,把每个会话画成真 3D / 等距 / 2D 办公室里的小人,或分组工作台。Live agent activity dashboard for magpie, with a real WebGL office and eleven scenes.",
"type": "module",
"files": [
@@ -18,6 +18,7 @@
"lib",
"office.hooks.mjs",
"CHANGELOG.md",
"lib/proc.mjs",
"README.md",
"LICENSE",
"bin",
+2 -3
View File
@@ -17,6 +17,7 @@ import { IMPORT_FROM, importedAccounts, tokenFileText } from "./import.mjs"
import { AGY_MANUAL, installAgy, keepAgyCurrent } from "./install.mjs"
import { ensureGeminiArrayItems } from "./array-items.mjs"
import { expandToolSchema } from "./tool-schema.mjs"
import { processExists } from "./proc.mjs"
import { fitTools } from "./tool-budget.mjs"
import { cloakUser, hint, outgoing, turnsAway } from "./cloak.mjs"
import { modelUsageCursor, modelUsageAfter, sessionDbPath } from "./step-usage.mjs"
@@ -2930,9 +2931,7 @@ function withStateLock(file, fn) {
if (Date.now() - fs.statSync(lock).mtimeMs > 5_000) {
const owner = JSON.parse(fs.readFileSync(lock, "utf8"))
if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
try { process.kill(owner.pid, 0) } catch (error) {
if (error.code === "ESRCH") fs.unlinkSync(lock)
}
if (!processExists(owner.pid)) fs.unlinkSync(lock)
}
}
} catch {}
+1
View File
@@ -8,6 +8,7 @@
".": "./opencode2.mjs"
},
"files": [
"proc.mjs",
"index.mjs",
"opencode.mjs",
"opencode2.mjs",
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+3
View File
@@ -40,6 +40,7 @@ export const STEP_USAGE_FILE = path.join(REPO_DIR, "step-usage.mjs")
export const SIGNIN_FILE = path.join(REPO_DIR, "signin.mjs")
export const TOOL_SCHEMA_FILE = path.join(REPO_DIR, "tool-schema.mjs")
export const TOOL_BUDGET_FILE = path.join(REPO_DIR, "tool-budget.mjs")
export const PROC_FILE = path.join(REPO_DIR, "proc.mjs")
export const INSTALL_FILE = path.join(REPO_DIR, "install.mjs")
export const ACCOUNT_FILE = path.join(REPO_DIR, "account.mjs")
export const IMPORT_FILE = path.join(REPO_DIR, "import.mjs")
@@ -563,6 +564,7 @@ export async function createBridgeKit(options = {}) {
const signinUrl = pathToFileURL(SIGNIN_FILE).href
const toolSchemaUrl = pathToFileURL(TOOL_SCHEMA_FILE).href
const toolBudgetUrl = pathToFileURL(TOOL_BUDGET_FILE).href
const procUrl = pathToFileURL(PROC_FILE).href
const installUrl = pathToFileURL(INSTALL_FILE).href
const accountUrl = pathToFileURL(ACCOUNT_FILE).href
const importUrl = pathToFileURL(IMPORT_FILE).href
@@ -583,6 +585,7 @@ export async function createBridgeKit(options = {}) {
else if (key === "./signin.mjs") module = sourceModule(SIGNIN_FILE, "", signinUrl)
else if (key === "./tool-schema.mjs") module = sourceModule(TOOL_SCHEMA_FILE, "", toolSchemaUrl)
else if (key === "./tool-budget.mjs") module = sourceModule(TOOL_BUDGET_FILE, "", toolBudgetUrl)
else if (key === "./proc.mjs") module = sourceModule(PROC_FILE, "", procUrl)
else if (key === "./install.mjs") module = sourceModule(INSTALL_FILE, "", installUrl)
else if (key === "./account.mjs") module = sourceModule(ACCOUNT_FILE, "", accountUrl)
else if (key === "./import.mjs") module = sourceModule(IMPORT_FILE, "", importUrl)
+2 -2
View File
@@ -11,6 +11,7 @@ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises"
import { createHash, randomBytes } from "node:crypto"
import { homedir, tmpdir } from "node:os"
import { join, dirname, resolve } from "node:path"
import { processAlive } from "./proc.mjs"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
@@ -53,8 +54,7 @@ async function claimProfileLock(profilePath) {
// 持锁进程已经死了(上次没来得及清理)就偷走这把锁。
const holder = await readFile(join(lockDir, "pid"), "utf8").then((t) => Number(t.trim())).catch(() => NaN)
if (Number.isFinite(holder) && holder !== process.pid) {
let alive = true
try { process.kill(holder, 0) } catch (e) { alive = e.code === "EPERM" }
const alive = processAlive(holder)
if (!alive) {
await rm(lockDir, { recursive: true, force: true }).catch(() => {})
continue
+2 -1
View File
@@ -1,11 +1,12 @@
{
"name": "@magpie-community/opencode-astudio-auth",
"version": "0.2.3",
"version": "0.2.4",
"description": "AStudio (iFLYTEK Astron Studio) sign-in as an OpenCode/magpie provider: browser sign-in with one account-pool slot per account, or the desktop sign-in, over the Responses model gateway with live model catalog",
"type": "module",
"main": "./opencode.mjs",
"exports": { ".": "./opencode2.mjs" },
"files": [
"proc.mjs",
"index.mjs",
"browser.mjs",
"opencode.mjs",
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+3 -8
View File
@@ -1,5 +1,6 @@
import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises"
import { dirname } from "node:path"
import { processStatus } from "./proc.mjs"
// A lock that holds across processes, not just within one. magpie asks each
// account's row separately and may do it in a process of its own, so an
@@ -16,14 +17,8 @@ import { dirname } from "node:path"
// is still alive. Any other error is not proof either way, and the caller
// falls back to the lock's age.
function alive(pid) {
try {
process.kill(pid, 0)
return true
} catch (error) {
if (error?.code === "ESRCH") return false
if (error?.code === "EPERM") return true
return undefined
}
const state = processStatus(pid).state
return state === "dead" ? false : state === "unknown" ? undefined : true
}
// abandoned says whether the lock at path was left behind by a holder that is
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -1
View File
@@ -1,11 +1,12 @@
{
"name": "@magpie-community/opencode-gcp-ai-auth",
"version": "0.2.2",
"version": "0.2.3",
"description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login",
"type": "module",
"main": "./opencode.mjs",
"exports": { ".": "./opencode2.mjs" },
"files": [
"lib/proc.mjs",
"index.mjs",
"opencode.mjs",
"opencode2.mjs",
+2 -1
View File
@@ -1,11 +1,12 @@
{
"name": "@magpie-community/tools-goanyapi",
"version": "0.1.1",
"version": "0.1.2",
"description": "All GoAnyAPI SEO, ads and web intelligence tools, generated from its live MCP catalog, with OAuth or API key",
"homepage": "https://goanyapi.com/",
"type": "module",
"main": "./index.mjs",
"files": [
"src/proc.mjs",
"index.mjs",
"src",
"README.md",
+2 -5
View File
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { processExists } from "./proc.mjs";
import { refreshToken } from "./oauth.ts";
import {
PROVIDER,
@@ -118,11 +119,7 @@ export class Credentials {
try {
const holder = JSON.parse(raw);
if (Number.isInteger(holder.pid) && holder.pid > 0) {
try {
process.kill(holder.pid, 0);
} catch (error) {
dead = (error as NodeJS.ErrnoException).code === "ESRCH";
}
dead = !processExists(holder.pid);
}
} catch {}
if (
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -2
View File
@@ -15,6 +15,7 @@ import { kernelFamily, runnerGeneration } from './runtime-family.mjs';
import { inspectRolePlugins, disableRolePluginsSync } from './role-plugin-state.mjs';
import { validateModelOptions, applyReasoningOptions } from './model-options.mjs';
import { countContextTokens } from './context-budget.mjs';
import { processExists } from './proc.mjs';
const PROVIDER = 'daimon-kimi-code';
const TOOL_ORIGIN = 'https://agent-gw.kimi.com';
@@ -269,8 +270,7 @@ export class KimiAdapter {
try { owner = JSON.parse(before); } catch { throw Error('adapter_lock_invalid'); }
if (!Number.isSafeInteger(owner?.pid) || owner.pid <= 0 || owner.pid > 2147483647
|| typeof owner.ownerID !== 'string' || !owner.ownerID) throw Error('adapter_lock_invalid');
let alive = true;
try { process.kill(owner.pid, 0); } catch (error) { alive = error.code !== 'ESRCH'; }
const alive = processExists(owner.pid);
if (alive) return false;
try {
if (fs.readFileSync(this.lockFile, 'utf8') !== before) return false;
+2 -1
View File
@@ -1,10 +1,11 @@
{
"name": "@magpie-community/agent-kimi-desktop",
"version": "0.1.6",
"version": "0.1.7",
"description": "Kimi desktop Work as a Magpie agent, using the models configured in Magpie",
"type": "module",
"main": "./index.mjs",
"files": [
"proc.mjs",
"kimi-desktop.agent.js",
"index.mjs",
"adapter.mjs",
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -2
View File
@@ -16,6 +16,7 @@ import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { createHash, randomBytes } from 'node:crypto'
import { homedir, tmpdir } from 'node:os'
import { join, dirname, resolve } from 'node:path'
import { processAlive } from './proc.mjs'
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
@@ -62,8 +63,7 @@ async function claimProfileLock(profilePath) {
// 持锁进程已经死了(上次没来得及清理)就偷走这把锁。
const holder = await readFile(join(lockDir, 'pid'), 'utf8').then((t) => Number(t.trim())).catch(() => NaN)
if (Number.isFinite(holder) && holder !== process.pid) {
let alive = true
try { process.kill(holder, 0) } catch (e) { alive = e.code === 'EPERM' }
const alive = processAlive(holder)
if (!alive) {
await rm(lockDir, { recursive: true, force: true }).catch(() => {})
continue
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-mclaw-auth",
"version": "0.5.3",
"version": "0.5.4",
"description": "OpenCode provider plugin: MClaw (中国移动云 MClaw, ai.yun.139.com)",
"type": "module",
"main": "./opencode.mjs",
@@ -15,6 +15,7 @@
"test": "bun test"
},
"files": [
"proc.mjs",
"index.mjs",
"browser.mjs",
"opencode.mjs",
@@ -33,4 +34,4 @@
"maxConcurrency": 4,
"icon": "data:image/png;base64,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"
}
}
}
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -1
View File
@@ -3,6 +3,7 @@ import path from 'node:path';
import os from 'node:os';
import crypto from 'node:crypto';
import net from 'node:net';
import { processExists } from './proc.mjs';
const VERSION = 1;
// The one provider ID this adapter creates. The paths it lives under, the
@@ -207,7 +208,7 @@ function acquire(paths) {
const held = read(paths.lock)?.data;
if (held) {
if (!Number.isSafeInteger(held.pid) || held.pid <= 0 || typeof held.token !== 'string') fail('invalid_lock');
try { process.kill(held.pid, 0); fail('writer_locked'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
if (processExists(held.pid)) fail('writer_locked');
paths.__fault?.('dead-lock-guarded');
if (!equal(read(paths.lock)?.data, held)) fail('writer_locked');
remove(paths.lock);
+1 -1
View File
@@ -271,7 +271,7 @@ test('declares the standard community Agent entry and ships every module it load
if (!shipped.has(file)) continue;
for (const match of fs.readFileSync(path.join(dir, file), 'utf8').matchAll(/from\s+["'](\.\/[^"']+)["']/g)) loaded.add(match[1].slice(2));
}
expect([...loaded].sort()).toEqual(['bridge.mjs', 'runtime.mjs']);
expect([...loaded].sort()).toEqual(['bridge.mjs', 'proc.mjs', 'runtime.mjs']);
expect([...loaded].every(file => shipped.has(file))).toBe(true);
// Tests are development artifacts and are not published.
expect(shipped.has('nanobot.test.mjs')).toBe(false);
+2 -2
View File
@@ -1,10 +1,10 @@
{
"name": "@magpie-community/agent-nanobot",
"version": "0.1.1",
"version": "0.1.2",
"description": "nanobot (HKUDS/nanobot) as a magpie agent: pick one of magpie's models for it on the Agents page, with Library MCP servers and skills",
"type": "module",
"main": "./index.mjs",
"files": ["nanobot.agent.js", "index.mjs", "runtime.mjs", "bridge.mjs", "cli.mjs", "README.md"],
"files": ["proc.mjs", "nanobot.agent.js", "index.mjs", "runtime.mjs", "bridge.mjs", "cli.mjs", "README.md"],
"bin": { "magpie-nanobot": "./cli.mjs" },
"scripts": { "test": "bun test nanobot.test.mjs" },
"engines": { "node": ">=20" },
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+3 -4
View File
@@ -2,6 +2,7 @@ import fs from "node:fs"
import path from "node:path"
import { createHash, randomUUID } from "node:crypto"
import { pathsFor, reconcile, inspect } from "./bridge.mjs"
import { processExists } from "./proc.mjs"
function configFile(file) {
try {
@@ -54,8 +55,7 @@ function claimRuntime(p) {
catch (error) {
if (error.code !== "EEXIST") throw error
const previous = readOwner()
try { process.kill(previous.pid, 0); return null }
catch (probe) { if (probe.code !== "ESRCH") return null }
if (processExists(previous.pid)) return null
// Serialize stale reclamation separately. Re-reading a nonce alone is not
// a compare-and-delete: another reclaimer could create a live lock between
// the read and unlink. A leftover guard fails closed for manual inspection.
@@ -66,8 +66,7 @@ function claimRuntime(p) {
let current
try { current = readOwner() } catch (probe) { if (probe.code !== "ENOENT") throw probe }
if (current) {
try { process.kill(current.pid, 0); return null }
catch (probe) { if (probe.code !== "ESRCH") return null }
if (processExists(current.pid)) return null
fs.unlinkSync(file)
}
try { fs.writeFileSync(file, JSON.stringify(owner), { mode: 0o600, flag: "wx" }) }
+2 -2
View File
@@ -1,6 +1,7 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { processExists } from './proc.mjs';
export async function readJSON(file) {
try { return JSON.parse(await fs.readFile(file, 'utf8')); }
@@ -30,8 +31,7 @@ export async function withLock(stateFile, run) {
try {
const owner = await readJSON(lock);
if (Number.isSafeInteger(owner?.pid) && owner.pid > 0) {
try { process.kill(owner.pid, 0); }
catch (e) { if (e.code === 'ESRCH') stale = true; }
stale = !processExists(owner.pid);
}
} catch (e) {
if (e.code === 'ENOENT') continue;
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/agent-nowledge-mem",
"version": "0.1.0",
"version": "0.1.1",
"description": "Manage Nowledge Mem Default, AI Now and Background models from Magpie",
"type": "module",
"main": "./index.mjs",
@@ -18,6 +18,7 @@
"index.mjs",
"cli.mjs",
"lib/",
"lib/proc.mjs",
"README.md",
"VALIDATION.md",
"LICENSE",
@@ -35,6 +35,7 @@ import { appendFile, mkdir, open, readFile, rename, stat, unlink } from "node:fs
import { randomUUID } from "node:crypto"
import { basename, dirname } from "node:path"
import { measureTools } from "./lib/measure.mjs"
import { processStatus } from "./lib/proc.mjs"
import { toolsLog } from "./lib/paths.mjs"
import { activity } from "./lib/activity.mjs"
@@ -139,16 +140,8 @@ async function removeLock(path) {
}
function alive(pid) {
if (!Number.isInteger(pid) || pid <= 0) return null
try {
process.kill(pid, 0)
return true
} catch (error) {
// ESRCH: no such process, the owner is gone.
if (error.code === "ESRCH") return false
// EPERM: the process exists but belongs to another user.
return null
}
const state = processStatus(pid).state
return state === "dead" ? false : state === "alive" ? true : null
}
// The lock's owner: undefined when there is no lock, null when it cannot be
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-harnessweight",
"version": "0.4.0",
"version": "0.4.1",
"description": "HarnessWeight: a magpie page that weighs every agent harness behind your gateway, by agent rather than by model: input tokens, cache hit rate, tokens at full price, failures, latency, and the tool definitions each harness re-sends every turn",
"type": "module",
"files": [
@@ -11,6 +11,7 @@
"page",
"app",
"brand/assets",
"lib/proc.mjs",
"README.md",
"LICENSE"
],
+2 -2
View File
@@ -4,6 +4,7 @@ import path from "node:path"
import { randomUUID } from "node:crypto"
import { isDeepStrictEqual } from "node:util"
import { parseTOML, stringify, parseEnv } from "./vendor.mjs"
import { processExists } from "./proc.mjs"
import { agent } from "./reasonix-desktop.agent.js"
export const PROVIDER = "magpie-agent"
@@ -63,8 +64,7 @@ function lock(file) {
if (e.code !== "EEXIST") throw e
const pid = Number(read(file))
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("Invalid bridge lock; inspect .magpie-bridge/lock")
try { process.kill(pid, 0) } catch (error) {
if (error.code !== "ESRCH") throw error
if (!processExists(pid)) {
fs.unlinkSync(file)
return lock(file)
}
+2 -1
View File
@@ -1,10 +1,11 @@
{
"name": "@magpie-community/agent-reasonix-desktop",
"version": "0.1.0",
"version": "0.1.1",
"description": "Reasonix 1.x Desktop and CLI as a Magpie agent, with a reversible TOML and dotenv configuration bridge",
"type": "module",
"main": "./index.mjs",
"files": [
"proc.mjs",
"index.mjs",
"reasonix-desktop.agent.js",
"bridge.mjs",
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+5 -3
View File
@@ -2,11 +2,13 @@ import { mkdir, readdir, writeFile, readFile, unlink, rmdir, lstat } from 'node:
import { join } from 'node:path';
import { randomBytes } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { processStatus } from './proc.mjs';
export function alive(pid) {
export function alive(pid, deps = {}) {
if (!Number.isSafeInteger(pid) || pid <= 0) return true;
try { process.kill(pid, 0); return true; }
catch (error) { if (error.code === 'ESRCH') return false; if (error.code === 'EPERM') return true; throw error; }
const status = processStatus(pid, deps);
if (status.state === 'unknown') throw status.error;
return status.state !== 'dead';
}
async function removeEmpty(path) {
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/gateway-respire-memory",
"version": "0.3.15",
"version": "0.3.16",
"description": "帮助 AI Agent 通过记忆召回、经验积累与后台归档持续自进化",
"type": "module",
"license": "MIT",
@@ -11,6 +11,7 @@
"memory"
],
"files": [
"proc.mjs",
"respire.hooks.mjs",
"runtime.mjs",
"lock.mjs",
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+29
View File
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { alive } from "./lock.mjs";
const err = (code) => () => {
throw Object.assign(new Error(code), { code });
};
const deps = (stat, killImpl = () => {}) => ({
platform: "linux",
procRoot: "/fake-proc",
readFile: () => {
if (stat === undefined) throw Object.assign(new Error("EACCES"), { code: "EACCES" });
return stat;
},
kill: killImpl,
});
test("alive keeps lock ownership semantics while rejecting zombies", () => {
assert.equal(alive(0), true);
assert.equal(alive(123, deps("123 (comm)) Z 1")), false);
assert.equal(alive(123, deps("123 (comm)) X 1")), false);
assert.equal(alive(123, deps("123 (comm) R 1")), true);
assert.equal(alive(123, deps(undefined, err("EPERM"))), true);
assert.equal(alive(123, deps("123 (comm)) Z 1", err("EPERM"))), false);
assert.equal(alive(123, deps(undefined, err("ESRCH"))), false);
const failure = Object.assign(new Error("EIO"), { code: "EIO" });
assert.throws(() => alive(123, deps(undefined, () => { throw failure; })), (error) => error === failure);
});
+2 -2
View File
@@ -1,10 +1,10 @@
{
"name": "@magpie-community/tools-search1api",
"version": "0.1.1",
"version": "0.1.2",
"description": "Search1API web search, news, agentic search, pages, sitemaps and trends for Magpie, with OAuth or API key sign-in",
"type": "module",
"main": "./index.mjs",
"files": ["index.mjs", "src", "README.md", "LICENSE"],
"files": ["src/proc.mjs", "index.mjs", "src", "README.md", "LICENSE"],
"license": "MIT",
"repository": {
"type": "git",
+2 -5
View File
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { processExists } from "./proc.mjs";
import { refreshToken } from "./oauth.ts";
import {
PROVIDER,
@@ -118,11 +119,7 @@ export class Credentials {
try {
const holder = JSON.parse(raw);
if (Number.isInteger(holder.pid) && holder.pid > 0) {
try {
process.kill(holder.pid, 0);
} catch (error) {
dead = (error as NodeJS.ErrnoException).code === "ESRCH";
}
dead = !processExists(holder.pid);
}
} catch {}
if (
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+1 -1
View File
@@ -1,7 +1,7 @@
export const PROVIDER = "search1api";
export const API_BASE = "https://api.search1api.com";
// Identifies Magpie traffic to Search1API; keep in step with package.json.
export const USER_AGENT = "search1api-magpie/0.1.1";
export const USER_AGENT = "search1api-magpie/0.1.2";
export interface StoredOAuth {
type: "oauth";
+68 -21
View File
@@ -1,6 +1,6 @@
// @bun
// src/plugin.ts
import { join as join4 } from "path";
import { join as join5 } from "path";
// src/accounts.ts
var FINGERPRINT_RE = /^[0-9a-f]{10}$/;
@@ -961,9 +961,9 @@ async function send(base, task, pin, effort, signal, timeoutMs = SEND_TIMEOUT_MS
// src/server.ts
import { randomBytes, timingSafeEqual } from "crypto";
import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
import path2, { basename, extname, join as join3, resolve as resolve2 } from "path";
import path2, { basename, extname, join as join4, resolve as resolve2 } from "path";
// package.json
var version = "0.1.4";
var version = "0.1.5";
// src/diagnostics.ts
var DIAGNOSTICS_SCHEMA = "window-warmup-diagnostics/1";
@@ -1853,8 +1853,62 @@ class Scheduler {
// src/store.ts
import { link, mkdir, readdir, readFile as readFile2, rename, unlink, writeFile } from "fs/promises";
import { join as join2 } from "path";
import { join as join3 } from "path";
import { randomUUID as randomUUID2 } from "crypto";
// src/proc.mjs
import { readFileSync } from "fs";
import { join as join2 } from "path";
var errCode = (error) => error && typeof error === "object" ? error.code : undefined;
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8")
} = {}) {
if (!validPid(pid))
return false;
let stat;
try {
stat = readFile(join2(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0)
return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid))
return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH")
return { state: "dead" };
if (code !== "EPERM")
return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps))
return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
// src/store.ts
var RUNS_PER_TASK2 = 50;
var RESET_KEYS_PER_TASK = 20;
var STATE_FILE = "state.json";
@@ -2021,7 +2075,7 @@ class StoreImpl {
}
async function openStore(dir) {
await mkdir(dir, { recursive: true, mode: 448 });
const path = join2(dir, STATE_FILE);
const path = join3(dir, STATE_FILE);
let raw;
try {
raw = await readFile2(path, "utf8");
@@ -2049,7 +2103,7 @@ async function openStore(dir) {
return new StoreImpl(data, path);
}
async function migrateLegacyState(dir, env = process.env) {
const statePath = join2(dir, STATE_FILE);
const statePath = join3(dir, STATE_FILE);
try {
await readFile2(statePath);
return;
@@ -2057,7 +2111,7 @@ async function migrateLegacyState(dir, env = process.env) {
if (e.code !== "ENOENT")
return;
}
const legacy = join2(xdgConfigHome(env), "magpie", LEGACY_DIR_NAME, STATE_FILE);
const legacy = join3(xdgConfigHome(env), "magpie", LEGACY_DIR_NAME, STATE_FILE);
let raw;
try {
raw = await readFile2(legacy, "utf8");
@@ -2079,14 +2133,7 @@ function parsePid(raw) {
} catch {}
return null;
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return e.code === "EPERM";
}
}
var pidAlive = processAlive;
async function releaseLock(path) {
let raw;
try {
@@ -2099,15 +2146,15 @@ async function releaseLock(path) {
}
async function acquireLock(dir, opts = {}) {
await mkdir(dir, { recursive: true, mode: 448 });
const path = join2(dir, LOCK_FILE);
const path = join3(dir, LOCK_FILE);
const leftovers = await readdir(dir).catch(() => []);
for (const name of leftovers) {
if (/^service\.lock\.\d+\.[0-9a-f-]+\.tmp$/.test(name)) {
await unlink(join2(dir, name)).catch(() => {});
await unlink(join3(dir, name)).catch(() => {});
}
}
for (let round = 0;round < 3; round++) {
const tmp = join2(dir, `${LOCK_FILE}.${process.pid}.${randomUUID2()}.tmp`);
const tmp = join3(dir, `${LOCK_FILE}.${process.pid}.${randomUUID2()}.tmp`);
await writeFile(tmp, String(process.pid), { mode: 384 });
try {
await link(tmp, path);
@@ -2149,7 +2196,7 @@ var MARKER_HEADER = "x-window-warmup";
var PROBE_TIMEOUT_MS = 2000;
var BODY_LIMIT = 64 * 1024;
async function loadOrCreateToken(dir) {
const file = join3(dir, TOKEN_FILE);
const file = join4(dir, TOKEN_FILE);
try {
const text = (await readFile3(file, "utf8")).trim();
if (/^[0-9a-f]{64}$/.test(text))
@@ -2393,7 +2440,7 @@ async function startService(opts) {
const boot = JSON.stringify(bootData).replaceAll("<", "\\u003c");
let html;
try {
html = await readFile3(join3(uiDir, "index.html"), "utf8");
html = await readFile3(join4(uiDir, "index.html"), "utf8");
} catch {
html = "<!doctype html><title>\u7A97\u53E3\u9884\u70ED</title><p>\u754C\u9762\u8FD8\u6CA1\u6784\u5EFA\uFF1A\u5148\u5728\u5305\u76EE\u5F55\u8FD0\u884C bun run build\u3002</p>";
}
@@ -2474,7 +2521,7 @@ function defaultDir(env = process.env) {
const custom = env.WINDOW_WARMUP_DIR?.trim();
if (custom)
return custom;
return join4(xdgConfigHome(env), "magpie", "window-warmup");
return join5(xdgConfigHome(env), "magpie", "window-warmup");
}
var instances = new Map;
var plugin_default = {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-window-warmup",
"version": "0.1.4",
"version": "0.1.5",
"description": "窗口预热 Window Warmup:定时消息插件,定时给指定供应商/账号/模型发一条短消息,在额度窗口重置后、每天定时或每隔几小时自动预热保活,提前开启5小时/每周订阅额度(配额)窗口,适用 Codex、Claude、GLM 智谱、ZCode 等。Scheduled keep-alive message to warm up quota / usage / rate limit windows after reset (cron-like).",
"author": "YangHonghang (https://github.com/YangHonghang)",
"type": "module",
+8
View File
@@ -0,0 +1,8 @@
export type ProcessAliveDeps = {
kill?: (pid: number, signal: 0) => unknown;
platform?: NodeJS.Platform;
procRoot?: string;
readFile?: (file: string) => string;
};
export declare function processAlive(pid: number, deps?: ProcessAliveDeps): boolean;
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+2 -9
View File
@@ -5,6 +5,7 @@
import { link, mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
import { processAlive } from "./proc.mjs";
import { xdgConfigHome } from "./magpie-files";
import { errText, type Run, type Task } from "./types";
@@ -283,15 +284,7 @@ function parsePid(raw: string): number | null {
return null;
}
function pidAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (e) {
// EPERM 说明进程存在但属于别人,同样算活着
return (e as NodeJS.ErrnoException).code === "EPERM";
}
}
const pidAlive = processAlive;
/** 只在自己仍是持有者时删除锁文件;锁已被别人接管/换内容时不动它 */
async function releaseLock(path: string): Promise<void> {
+59
View File
@@ -0,0 +1,59 @@
// GENERATED by scripts/sync-proc.mjs from scripts/proc.mjs. Do not edit package copies.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const errCode = (error) => (error && typeof error === "object" ? error.code : undefined);
function validPid(pid) {
return Number.isSafeInteger(pid) && pid > 0;
}
export function processZombie(pid, {
procRoot = "/proc",
readFile = (file) => readFileSync(file, "utf8"),
} = {}) {
if (!validPid(pid)) return false;
let stat;
try {
stat = readFile(join(procRoot, String(pid), "stat"));
} catch {
return false;
}
const commEnd = typeof stat === "string" ? stat.lastIndexOf(")") : -1;
if (commEnd < 0) return false;
const state = stat.slice(commEnd + 1).trim()[0];
return state === "Z" || state === "X";
}
export function processAlive(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state === "alive" || state === "permission";
}
export function processExists(pid, deps = {}) {
const state = processStatus(pid, deps).state;
return state !== "dead" && state !== "invalid";
}
export function processStatus(pid, deps = {}) {
const kill = deps.kill ?? ((target, signal) => process.kill(target, signal));
if (!validPid(pid)) return { state: "invalid" };
let permission = false;
try {
kill(pid, 0);
} catch (error) {
const code = errCode(error);
if (code === "ESRCH") return { state: "dead" };
if (code !== "EPERM") return { state: "unknown", error };
permission = true;
}
if ((deps.platform ?? process.platform) !== "linux") {
return permission ? { state: "permission" } : { state: "alive" };
}
if (processZombie(pid, deps)) return { state: "dead" };
return permission ? { state: "permission" } : { state: "alive" };
}
export function processProbe(pid, deps = {}) {
return processStatus(pid, deps).state;
}
+118
View File
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { processAlive, processExists, processProbe, processStatus, processZombie } from "./proc.mjs";
import { procTargets } from "./sync-proc.mjs";
const root = fileURLToPath(new URL("..", import.meta.url));
const canonical = readFileSync(new URL("./proc.mjs", import.meta.url), "utf8");
const err = (code) => {
throw Object.assign(new Error(code), { code });
};
const deps = (content, killImpl = () => {}) => ({
procRoot: "/fake-proc",
platform: "linux",
readFile: (file) => {
if (content === undefined) err("EACCES");
if (file === "/fake-proc/123/stat") return content;
err("ENOENT");
},
kill: killImpl,
});
const stat = (comm, state) => `123 (${comm}) ${state} 1 2 3 4 5 6 7 8 9`;
test("zombie detection accepts every proc comm spelling", () => {
assert.equal(processZombie(123, deps(stat("comm)", "Z"))), true);
assert.equal(processZombie(123, deps(stat("a ) b ) c", "X"))), true);
assert.equal(processZombie(123, deps(stat("(weird)", "R"))), false);
assert.equal(processZombie(123, deps("123 (comm R")), false);
});
test("invalid pids and unreadable proc states never report zombie", () => {
for (const pid of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {
assert.equal(processZombie(pid, deps(stat("comm", "Z"))), false);
assert.equal(processAlive(pid, deps(stat("comm", "Z"))), false);
assert.equal(processExists(pid, deps(stat("comm", "Z"))), false);
}
assert.equal(processZombie(123, deps(undefined, err)), false);
});
test("processProbe keeps unknown outcomes separate from invalid and dead", () => {
assert.equal(processProbe(0, deps(stat("comm", "R"))), "invalid");
assert.equal(processProbe(123, deps(stat("comm)", "Z"))), "dead");
assert.equal(processProbe(123, deps(stat("comm", "X"))), "dead");
assert.equal(processProbe(123, deps(stat("comm", "R"))), "alive");
assert.equal(processProbe(123, deps(stat("comm", "R"), () => err("EPERM"))), "permission");
assert.equal(processProbe(123, deps(stat("comm)", "Z"), () => err("EPERM"))), "dead");
assert.equal(processProbe(123, deps(undefined, () => err("EPERM"))), "permission");
assert.equal(processProbe(123, deps("123 (comm R", () => err("EPERM"))), "permission");
assert.equal(processProbe(123, deps(undefined, () => err("ESRCH"))), "dead");
assert.equal(processProbe(123, deps(undefined, () => err("EIO"))), "unknown");
});
test("processStatus preserves the original unexpected kill error", () => {
const failure = Object.assign(new Error("EIO"), { code: "EIO" });
const status = processStatus(123, deps(stat("comm", "R"), () => { throw failure; }));
assert.equal(status.state, "unknown");
assert.equal(status.error, failure);
});
test("processAlive keeps boolean semantics and rejects zombies", () => {
assert.equal(processAlive(123, deps(stat("comm)", "Z"))), false);
assert.equal(processAlive(123, deps(stat("comm", "X"))), false);
assert.equal(processAlive(123, deps(stat("comm", "R"))), true);
assert.equal(processAlive(123, deps(stat("comm", "R"), () => err("EPERM"))), true);
assert.equal(processAlive(123, deps(undefined, () => err("EPERM"))), true);
assert.equal(processAlive(123, deps(undefined, () => err("ESRCH"))), false);
assert.equal(processAlive(123, deps(undefined, () => err("EIO"))), false);
});
test("processExists is conservative except for ESRCH", () => {
assert.equal(processExists(123, deps(stat("comm)", "Z"))), false);
assert.equal(processExists(123, deps(stat("comm", "X"))), false);
assert.equal(processExists(123, deps(stat("comm", "R"))), true);
assert.equal(processExists(123, deps(undefined, () => err("EPERM"))), true);
assert.equal(processExists(123, deps(undefined, () => err("ESRCH"))), false);
assert.equal(processExists(123, deps(undefined, () => err("EIO"))), true);
});
test("non-Linux platforms do not require procfs", () => {
const darwin = { ...deps(stat("comm", "Z")), platform: "darwin" };
assert.equal(processAlive(123, darwin), true);
assert.equal(processExists(123, darwin), true);
assert.equal(processProbe(123, { ...deps(undefined, () => err("EPERM")), platform: "darwin" }), "permission");
});
test("runtime proc copies match the canonical implementation", () => {
assert.equal(procTargets.length, 15);
for (const relative of procTargets) {
const target = `${root}${relative}`;
assert.deepEqual(readFileSync(target, "utf8"), canonical, relative);
const name = relative.split("/")[1];
const importers = {
"agent-console": ["index.mjs", "daemon/src/util/proc.ts"],
"agent-office": ["lib/scan.mjs", "lib/jump.mjs"],
"agy-cli": ["index.mjs"],
astudio: ["browser.mjs"],
"gcp-ai": ["lib/lock.mjs"],
goanyapi: ["src/auth.ts"],
"kimi-desktop": ["adapter.mjs"],
mclaw: ["browser.mjs"],
nanobot: ["runtime.mjs", "bridge.mjs"],
"nowledge-mem-agent": ["lib/files.mjs"],
"page-harnessweight": ["harnessweight.hooks.mjs"],
"reasonix-desktop": ["bridge.mjs"],
"respire-memory": ["lock.mjs"],
search1api: ["src/auth.ts"],
"window-warmup": ["src/store.ts"],
};
for (const importer of importers[name]) {
assert.match(
readFileSync(`${root}packages/${name}/${importer}`, "utf8"),
/["'](?:\.\/proc\.mjs|\.\/lib\/proc\.mjs|\.\.\/\.\.\/\.\.\/lib\/proc\.mjs)["']/,
`packages/${name}/${importer}`,
);
}
}
});
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env node
import { copyFileSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
const root = resolve(new URL("..", import.meta.url).pathname);
const source = "scripts/proc.mjs";
export const procTargets = [
"packages/agent-console/lib/proc.mjs",
"packages/agent-office/lib/proc.mjs",
"packages/agy-cli/proc.mjs",
"packages/astudio/proc.mjs",
"packages/gcp-ai/lib/proc.mjs",
"packages/goanyapi/src/proc.mjs",
"packages/kimi-desktop/proc.mjs",
"packages/mclaw/proc.mjs",
"packages/nanobot/proc.mjs",
"packages/nowledge-mem-agent/lib/proc.mjs",
"packages/page-harnessweight/lib/proc.mjs",
"packages/reasonix-desktop/proc.mjs",
"packages/respire-memory/proc.mjs",
"packages/search1api/src/proc.mjs",
"packages/window-warmup/src/proc.mjs",
];
const check = process.argv.includes("--check");
const bytes = readFileSync(resolve(root, source));
for (const relative of procTargets) {
const target = resolve(root, relative);
if (check) {
try {
if (!readFileSync(target).equals(bytes)) {
console.error(`Out of sync: ${relative}`);
process.exitCode = 1;
}
} catch (error) {
console.error(`Missing sync target: ${relative} (${error?.code ?? error})`);
process.exitCode = 1;
}
continue;
}
mkdirSync(dirname(target), { recursive: true });
copyFileSync(resolve(root, source), target);
}