// Agent Console — Magpie plugin entry (loaded by Magpie's Bun plugin host). // // Lifecycle and token handoff (design after the PR #535 review): // - Importing this module has no side effects: no port, no process, no file writes. // - When Magpie calls server(input, options): generate two random secrets for this host — the gate key (written to // page/session.js) and the daemon token (handed to the daemon page only via the # fragment of the gate's 302, never written to any static file) — // and bind a tiny "gate" (lib/gate.mjs) on 127.0.0.1: (default 3488). Only after a successful bind is // page/session.js written atomically; the plugin page (sandbox iframe) reads it from the page directory Magpie serves. If the bind fails (port in use) // it retries every 2 seconds in the background; server() itself returns immediately and never blocks the plugin host from loading. // - The daemon is started only when the plugin page navigates to the gate's /open?k= ("start on page open"): a non-detached child, // stdin is a lifeline pipe and it gets --parent-pid; later /open calls reuse the same child. // - The daemon exits by itself when the host exits (stdin closes or the parent disappears) or after an idle timeout (60 minutes); // stop() closes the gate, ends the daemon and deletes session.js. // - Note: Magpie's plugin host treats the return value of server() as an OpenCode hooks object and never calls stop(); // the host calls process.exit() after Magpie closes its stdin. So what really runs is the synchronous exit safety net: // close the daemon's lifeline pipe and delete the session.js this host wrote. // - No SIGINT/SIGTERM handlers (they would swallow the host's default termination behavior). import { execFile, spawn } from "node:child_process"; import { randomBytes } from "node:crypto"; import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs"; import http from "node:http"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { createGate } from "./lib/gate.mjs"; import { NODE_TOO_OLD_MESSAGE, requireNode } from "./lib/pathscan.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const DEFAULT_PORT = 3488; // Longest wait for the daemon's ready line (Windows cold start + antivirus scanning can be slow) const READY_TIMEOUT_MS = 15000; const BIND_RETRY_MS = 2000; const SESSION_BEAT_MS = 4000; // A port still busy after this many tries (~10 s) is worth a log line (see bindLoop) const BUSY_LOG_AFTER = 5; function bindDelayMs() { const v = Number(process.env.AGENT_CONSOLE_BIND_DELAY_MS); return Number.isFinite(v) && v >= 0 ? v : 1200; } // Paths are computed again inside server(): tests change environment variables after import function paths() { const dataRoot = process.env.XDG_CONFIG_HOME || join(homedir(), ".config"); const dataDir = join(dataRoot, "magpie", "agent-console"); return { dataRoot, dataDir, logsDir: join(dataDir, "logs"), spawnLog: join(dataDir, "logs", "daemon-spawn.log"), daemonJson: join(dataDir, "daemon.json"), // pid of the host that wrote page/session.js (kept out of the page directory, which any page can read) sessionOwner: join(dataDir, "session-owner.json"), pageDir: process.env.AGENT_CONSOLE_PAGE_DIR || join(here, "page"), }; } 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"; } } // A failed log write (directory deleted, disk full) must never make the host's flow throw function makeLogger(p) { return (message) => { try { mkdirSync(p.logsDir, { recursive: true }); appendFileSync(p.spawnLog, `[${new Date().toISOString()}] ${message}\n`); } catch {} }; } function readDaemonInfo(p) { try { return JSON.parse(readFileSync(p.daemonJson, "utf8")); } catch { return null; } } function ping(port, token) { return new Promise((resolve) => { const request = http.get( { host: "127.0.0.1", port, path: "/api/ping", headers: { "x-agent-console": token }, timeout: 1500, }, (response) => { let body = ""; response.on("data", (chunk) => { body += chunk; }); response.on("end", () => { try { resolve(JSON.parse(body)); } catch { resolve(null); } }); }, ); request.on("error", () => resolve(null)); request.on("timeout", () => { request.destroy(); resolve(null); }); }); } async function killPid(pid) { if (process.platform === "win32") { await new Promise((resolve) => execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve()), ); return; } try { process.kill(pid, "SIGTERM"); } catch {} for (let i = 0; i < 20 && pidAlive(pid); i++) await sleep(100); if (pidAlive(pid)) { try { process.kill(pid, "SIGKILL"); } catch {} } } // The 0.1.0 daemon was detached and may still hold 3488 after an upgrade. // Only after it answered a ping with the token from daemon.json (confirming it really is our daemon, guarding against pid reuse) // do we first shut it down gracefully via WS app.shutdown, then force-kill it if it's still there. async function shutdownLegacy(info, log) { if (!info?.pid || !info?.port || !info?.token || !pidAlive(info.pid)) return; const answer = await ping(info.port, info.token); if (!answer?.ok || answer.pid !== info.pid) return; log(`stopping legacy daemon pid ${info.pid} on port ${info.port}`); try { const { WebSocket } = await import("ws"); await new Promise((resolve) => { const socket = new WebSocket(`ws://127.0.0.1:${info.port}/ws`); const timer = setTimeout(() => { socket.terminate(); resolve(); }, 3000); socket.on("open", () => socket.send(JSON.stringify({ t: "hello", token: info.token, v: 1 }))); socket.on("message", (data) => { let message; try { message = JSON.parse(String(data)); } catch { return; } if (message.t === "hello.ok") { socket.send(JSON.stringify({ t: "req", id: 1, m: "app.shutdown", p: {} })); } if (message.t === "res" && message.id === 1) { clearTimeout(timer); socket.close(); resolve(); } }); socket.on("error", () => { clearTimeout(timer); resolve(); }); }); } catch {} for (let i = 0; i < 30 && pidAlive(info.pid); i++) await sleep(100); if (pidAlive(info.pid)) await killPid(info.pid); } // session.js is a script file holding only the gate port (a number) and the gate key (hex); "<" is still escaped just in case. // Any page that knows Magpie's page path can read it with