From fc965d7ab43713aba6a09bf1eecbe615b6b84da9 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Wed, 11 Nov 2026 23:38:09 +0200 Subject: [PATCH 1/2] fix(node): recreate a deleted default task folder at startup A node whose default task folder (`/../tasks`) was deleted, for example by a machine migration, refused to start with "node policy is invalid at workspace". That folder belongs to the node, so startup now makes it again. A missing custom workspace still fails startup, and the error now names the path and the reason. Co-Authored-By: Claude Opus 5.5 --- crates/aether/src/node_builder.rs | 86 +++++++++++++++++++++++++++++-- crates/aether/src/policy.rs | 4 ++ 2 files changed, 85 insertions(+), 5 deletions(-) diff --git a/crates/aether/src/node_builder.rs b/crates/aether/src/node_builder.rs index 32cc0ad..3bc059f 100644 --- a/crates/aether/src/node_builder.rs +++ b/crates/aether/src/node_builder.rs @@ -183,11 +183,7 @@ fn build( .initialize_access_groups(&initial_members) .map_err(|_| PolicyError::Invalid)?; let trust = RosterClaims::new(signed_claims, layout.clone()); - // The folder must exist; say which field names it. - let workspace = policy - .workspace - .canonicalize() - .map_err(|_| PolicyError::InvalidField("workspace".to_owned()))?; + let workspace = resolve_workspace(&policy.workspace, &layout)?; let agent = match sandbox { Some(sandbox) => NodeAgent::Codex(codex_agent( data_dir, @@ -266,6 +262,46 @@ fn build( Ok(service) } +/// The canonical policy workspace. The default task-folder root beside the +/// data directory belongs to the node, so it is made again when it is gone +/// (a cleaned home directory, a migrated machine). Any other folder belongs +/// to the owner: a missing one fails startup and the error names it. +fn resolve_workspace( + workspace: &Path, + layout: &DataDir, +) -> Result { + let error = |reason: std::io::Error| PolicyError::Workspace { + path: workspace.display().to_string(), + reason: reason.kind().to_string(), + }; + match workspace.canonicalize() { + Ok(path) => Ok(path), + Err(reason) + if reason.kind() == std::io::ErrorKind::NotFound + && is_default_tasks_root(workspace, layout) => + { + fs::create_dir_all(workspace).map_err(error)?; + workspace.canonicalize().map_err(error) + } + Err(reason) => Err(error(reason)), + } +} + +/// Whether `workspace` is the default task-folder root. The policy stores +/// that root canonicalized, so the data directory's parent is resolved too. +fn is_default_tasks_root(workspace: &Path, layout: &DataDir) -> bool { + let default = layout.default_tasks_root(); + if workspace == default { + return true; + } + match (default.parent(), default.file_name()) { + (Some(parent), Some(name)) => { + parent.canonicalize().is_ok_and(|parent| parent.join(name) == workspace) + } + _ => false, + } +} + /// The Codex adapter of a node: its own Codex home, which shares only the /// owner's login, and the allowlisted environment. fn codex_agent( @@ -537,6 +573,46 @@ mod tests { assert!(service.task_folder_mode()); } + #[test] + fn a_deleted_default_task_folder_is_made_again_on_the_next_start() { + let directory = tempfile::tempdir().expect("directory must create"); + let data_dir = directory.path().join("host"); + let import = directory.path().join("missing-policy.json"); + let tasks = directory.path().join("tasks"); + let service = load_or_create_service( + &import, + &data_dir, + "codex".into(), + Some(AgentAdapter::Connected), + ) + .expect("node must start"); + drop(service); + fs::remove_dir_all(&tasks).expect("task folder must delete"); + load_or_create_service(&import, &data_dir, "codex".into(), None) + .expect("node must start without its task folder"); + assert!(tasks.is_dir()); + } + + #[test] + fn a_missing_owner_workspace_fails_startup_and_names_the_path() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = minimal_policy(directory.path()); + let workspace = directory.path().join("workspace"); + fs::remove_dir_all(&workspace).expect("workspace must delete"); + let Err(error) = load_service(&path, directory.path(), "codex".into()) else { + panic!("a missing owner workspace must fail startup"); + }; + assert_eq!( + error, + PolicyError::Workspace { + path: workspace.display().to_string(), + reason: std::io::ErrorKind::NotFound.to_string(), + } + ); + assert!(!workspace.exists()); + assert!(error.to_string().contains(&workspace.display().to_string())); + } + #[test] fn a_connected_adapter_refuses_the_codex_settings() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/policy.rs b/crates/aether/src/policy.rs index dce70bc..8b721f7 100644 --- a/crates/aether/src/policy.rs +++ b/crates/aether/src/policy.rs @@ -52,6 +52,10 @@ pub enum PolicyError { Invalid, #[error("node policy is invalid at {0}")] InvalidField(String), + #[error( + "node policy workspace {path} cannot be opened ({reason}); create the folder or change workspace in the policy" + )] + Workspace { path: String, reason: String }, } #[derive(Deserialize, Serialize)] From 3258bcda71a3d9e576756ec02591062931313407 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Wed, 11 Nov 2026 23:38:09 +0200 Subject: [PATCH 2/2] fix(grokbot): share one node between connector processes A client can start the stdio connector more than once, for example to list tools on a second connection. The second bridge found the runtime lock held and exited with "Node runtime is locked", so tool calls failed. The first bridge now owns the node and serves the executor tools on `grokbot-bridge/bridge.sock`. Later bridges forward their calls to it. The owner keeps the node while any connector uses it, and a remaining connector takes over when the owner exits. The lock records the owner and node process IDs, so a lock left by a crashed bridge is taken over; on Linux its orphaned node is stopped first. "Local Aether node exited" now ends with the node's last stderr line and its exit status, so the real cause reaches the client. Co-Authored-By: Claude Opus 5.5 --- integrations/grokbot-bridge/INSTALL.md | 19 +- integrations/grokbot-bridge/src/main.mjs | 151 +++++++++--- integrations/grokbot-bridge/src/runtime.mjs | 228 ++++++++++++++++++ integrations/grokbot-bridge/src/server.mjs | 44 ++-- .../grokbot-bridge/test/runtime.test.mjs | 193 +++++++++++++++ 5 files changed, 587 insertions(+), 48 deletions(-) create mode 100644 integrations/grokbot-bridge/src/runtime.mjs create mode 100644 integrations/grokbot-bridge/test/runtime.test.mjs diff --git a/integrations/grokbot-bridge/INSTALL.md b/integrations/grokbot-bridge/INSTALL.md index 5134658..008c2a6 100644 --- a/integrations/grokbot-bridge/INSTALL.md +++ b/integrations/grokbot-bridge/INSTALL.md @@ -52,9 +52,22 @@ before starting new work. Do not report completion merely because the connector is listed. Installation is verified only after these real tool calls succeed. The MCP command's startup lock is `/grokbot-bridge/runtime.lock`. -Normal shutdown removes it. After a crash, verify that the old bridge and its -Aether child are stopped before removing this lock. The separate active-claim -marker has stricter recovery requirements; keep it until old task work is stopped. +The first connector process takes it and owns the Aether node. If Grok opens +the connector again while that process runs, the new process forwards its +tool calls to the owner over `grokbot-bridge/bridge.sock` instead of starting +a second node. The owner keeps the node while any connector still uses it; +when the owner exits, a remaining connector takes over and starts the node again. +Normal shutdown removes the lock. A lock left by a crashed bridge is taken over +automatically. On Linux the new bridge first stops the node the crashed bridge +left running. Elsewhere it reports that node's process ID for you to stop. +Remove the lock by hand only when the error asks you to, after verifying the +old bridge and its Aether child are stopped. The separate active-claim marker +has stricter recovery requirements; keep it until old task work is stopped. + +If the bridge exits with `Local Aether node exited`, the text after the colon +is the node's own last error line. A deleted default task folder +(`/../tasks`) is made again at startup. A missing custom +`workspace` in the policy is reported with its path. ## 3. Connect the owner and receive tasks diff --git a/integrations/grokbot-bridge/src/main.mjs b/integrations/grokbot-bridge/src/main.mjs index 68f0f69..7257c3f 100644 --- a/integrations/grokbot-bridge/src/main.mjs +++ b/integrations/grokbot-bridge/src/main.mjs @@ -1,4 +1,4 @@ -import { readFileSync, statSync, mkdirSync, rmdirSync } from 'node:fs'; +import { readFileSync, statSync, mkdirSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { once } from 'node:events'; @@ -6,7 +6,8 @@ import { spawn } from 'node:child_process'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { Mailbox } from './mailbox.mjs'; import { NodeLink, contract } from './node-link.mjs'; -import { createBridgeServer, createMcpServer } from './server.mjs'; +import { createBridgeServer, createMcpServer, localExecutor } from './server.mjs'; +import { UNAVAILABLE, acquireRuntime } from './runtime.mjs'; function secret(file) { const stat = statSync(file); @@ -16,6 +17,22 @@ function secret(file) { return value; } +// Keeps the last non-empty line a child wrote to stderr, so its exit can be +// reported with its own reason. +function lastLine() { + let partial = ''; + let last = ''; + return { + push(chunk) { + const lines = (partial + chunk.toString('utf8')).split('\n'); + partial = lines.pop().slice(-4096); + const line = lines.map(value => value.trim()).filter(Boolean).at(-1); + if (line) last = line; + }, + get value() { return (partial.trim() || last).slice(0, 500); }, + }; +} + async function main() { if (process.env.GROKBOT_EXPERIMENTAL !== '1') throw new Error('Set GROKBOT_EXPERIMENTAL=1 to acknowledge that hosted Bot stopping is cooperative, not guaranteed'); const transport = process.env.GROKBOT_TRANSPORT || 'http'; @@ -47,57 +64,131 @@ async function main() { } catch { console.error('Grok routine wake failed; tasks remain queued until their deadlines'); } finally { waking = false; } }; - let link; - const mailbox = new Mailbox({ marker: path.join(stateDir, 'active-claim.json'), send: message => link.send(message), wake }); - link = new NodeLink(path.join(dataDir, contract.socket_file), message => mailbox.receive(message), status => mailbox.setConnected(status)); + const controller = new AbortController(); + const { signal } = controller; + // The tools call whichever executor this process has: its own mailbox, or + // the bridge that owns the node. Before either exists they ask for a retry. + let executor; + const current = () => { + if (!executor) throw new Error(UNAVAILABLE); + return executor; + }; + const tools = { + status: () => current().status(), + claim: claimId => current().claim(claimId), + progress: (id, lease) => current().progress(id, lease), + finish: (id, lease, outcome, text) => current().finish(id, lease, outcome, text), + }; let server; let child; + let runtime; + let proxy; + let timer; + let clientOpen = true; + let proxies = 0; const stop = () => { - if (controller.signal.aborted) return; + if (signal.aborted) return; controller.abort(); + clearInterval(timer); if (transport === 'http') { server?.close(); server?.closeAllConnections(); } else { void server?.close(); process.stdin.pause(); } + proxy?.close(); if (child && child.exitCode === null && child.signalCode === null) { child.kill('SIGTERM'); const kill = setTimeout(() => child.kill('SIGKILL'), 5000); kill.unref(); child.once('exit', () => clearTimeout(kill)); + } else { + runtime?.release(); } }; + // The owner keeps the node while any connector still uses it. + const idle = () => { if (!clientOpen && proxies === 0) stop(); }; process.once('SIGINT', stop); process.once('SIGTERM', stop); + + const openMailbox = () => { + let link; + const mailbox = new Mailbox({ marker: path.join(stateDir, 'active-claim.json'), send: message => link.send(message), wake }); + link = new NodeLink(path.join(dataDir, contract.socket_file), message => mailbox.receive(message), status => mailbox.setConnected(status)); + if (mailbox.active) console.error('Prior claim requires stop acknowledgement; no new work can be claimed'); + timer = setInterval(() => { + mailbox.tick(); + if (mailbox.connected && mailbox.pending.size && !mailbox.active) void wake(); + }, 1000); + void link.run(signal); + return localExecutor(mailbox); + }; + + const startNode = () => { + const stderr = lastLine(); + child = spawn(process.env.AETHER_BIN || 'aether', ['node', 'serve', '--adapter', 'connected', '--data-dir', dataDir, + '--policy', path.join(dataDir, 'policy.json')], { stdio: ['ignore', 2, 'pipe'] }); + child.stderr.on('data', chunk => { process.stderr.write(chunk); stderr.push(chunk); }); + if (child.pid) runtime.recordNode(child.pid); + let ended = false; + const end = message => { + if (ended) return; + ended = true; + runtime.release(); + if (!signal.aborted) { process.exitCode = 1; console.error(message); stop(); } + }; + child.once('error', () => end('Could not start the local Aether binary')); + // `close` follows the last stderr chunk, so the reason is complete. + child.once('close', (code, exitSignal) => { + const status = exitSignal ? `signal ${exitSignal}` : `code ${code}`; + const reason = stderr.value; + end(`Local Aether node exited (${status})${reason ? `: ${reason}` : ''}; closing the executor`); + }); + }; + + // Own the node, or forward to the bridge that does. When that bridge goes + // away, try again: this process may become the owner. + const attach = async () => { + const claim = await acquireRuntime({ stateDir, dataDir, signal }); + if (signal.aborted) { if (claim.role === 'owner') claim.release(); else claim.executor.close(); return; } + if (claim.role === 'proxy') { + proxy = claim.executor; + executor = proxy; + console.error('Another bridge owns the local Aether node; forwarding executor tools to it'); + void proxy.closed.then(() => { + if (executor === proxy) executor = undefined; + proxy = undefined; + if (!signal.aborted) void attachOrStop(); + }); + return; + } + runtime = claim; + executor = openMailbox(); + await runtime.serve(executor, count => { proxies = count; idle(); }); + startNode(); + }; + const attachOrStop = () => attach().catch(error => { + if (signal.aborted) return; + process.exitCode = 1; + console.error(error.code ? `Bridge startup failed (${error.code})` : error.message); + stop(); + }); + if (transport === 'stdio') { - server = createMcpServer(mailbox); + server = createMcpServer(tools); await server.connect(new StdioServerTransport()); - process.stdin.once('end', stop); - process.stdin.once('close', stop); + const closed = () => { clientOpen = false; idle(); }; + process.stdin.once('end', closed); + process.stdin.once('close', closed); } else { - server = createBridgeServer({ mailbox, token, publicUrl }); + server = createBridgeServer({ executor: tools, token, publicUrl }); server.listen(port, '127.0.0.1'); await once(server, 'listening'); } - if (process.env.GROKBOT_START_NODE === '1' && !controller.signal.aborted) { - const lock = path.join(stateDir, 'runtime.lock'); - try { mkdirSync(lock, { mode: 0o700 }); } - catch { stop(); throw new Error('Node runtime is locked; stop any prior bridge and node before removing grokbot-bridge/runtime.lock'); } - child = spawn(process.env.AETHER_BIN || 'aether', ['node', 'serve', '--adapter', 'connected', '--data-dir', dataDir, - '--policy', path.join(dataDir, 'policy.json')], { stdio: ['ignore', 2, 2] }); - const release = () => { rmdirSync(lock); }; - child.once('error', () => { release(); process.exitCode = 1; console.error('Could not start the local Aether binary'); stop(); }); - child.once('exit', () => { - release(); - if (!controller.signal.aborted) { process.exitCode = 1; console.error('Local Aether node exited; closing the executor'); stop(); } - }); + if (process.env.GROKBOT_START_NODE === '1') { + if (!signal.aborted) await attachOrStop(); + } else { + executor = openMailbox(); } - console.error(`Experimental Grok Bot executor ready (${transport}); remote stop is cooperative`); - if (mailbox.active) console.error('Prior claim requires stop acknowledgement; no new work can be claimed'); - const timer = setInterval(() => { - mailbox.tick(); - if (mailbox.connected && mailbox.pending.size && !mailbox.active) void wake(); - }, 1000); - try { await link.run(controller.signal); } - finally { clearInterval(timer); stop(); } + if (!signal.aborted) console.error(`Experimental Grok Bot executor ready (${transport}); remote stop is cooperative`); + if (!signal.aborted) await once(signal, 'abort'); } main().catch(error => { console.error(error.code ? `Bridge startup failed (${error.code})` : error.message); process.exitCode = 1; }); diff --git a/integrations/grokbot-bridge/src/runtime.mjs b/integrations/grokbot-bridge/src/runtime.mjs new file mode 100644 index 0000000..158f420 --- /dev/null +++ b/integrations/grokbot-bridge/src/runtime.mjs @@ -0,0 +1,228 @@ +import net from 'node:net'; +import path from 'node:path'; +import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { publicError } from './server.mjs'; + +// One bridge owns the local node: it holds `runtime.lock`, runs the node and +// its mailbox, and serves the executor tools on `bridge.sock`. A client can +// open more than one command connector; every later bridge forwards its tool +// calls to the owner instead of starting a second node. + +export const UNAVAILABLE = 'Bridge is not connected to its node runtime yet; retry shortly'; +const OWNER = 'owner.json'; +const MAX_LINE = 256 * 1024; + +export function alive(pid) { + try { process.kill(pid, 0); return true; } + catch (error) { return error.code === 'EPERM'; } +} + +function readOwner(lock) { + try { + const owner = JSON.parse(readFileSync(path.join(lock, OWNER), 'utf8')); + return Number.isInteger(owner?.pid) && owner.pid > 0 ? owner : undefined; + } catch { return undefined; } +} + +function writeOwner(lock, owner) { + const file = path.join(lock, OWNER); + // Rename so a reader never sees a half-written file. + writeFileSync(`${file}.tmp`, JSON.stringify(owner), { mode: 0o600 }); + renameSync(`${file}.tmp`, file); +} + +// Whether `pid` is still the node a stopped bridge started. On Linux its +// command line must name `serve` and this data directory, so a reused pid is +// never signalled. Elsewhere a live pid is reported as unknown. +function orphanNode(pid, dataDir) { + if (!Number.isInteger(pid) || pid <= 0 || !alive(pid)) return false; + try { + const args = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0'); + return args.includes('serve') && args.includes(dataDir) ? true : false; + } catch { return undefined; } +} + +async function stopOrphanNode(pid, dataDir) { + const orphan = orphanNode(pid, dataDir); + if (orphan === false) return; + if (orphan === undefined) { + throw new Error(`Aether node process ${pid} from a stopped bridge may still be running; stop it, then restart the connector`); + } + const kill = name => { try { process.kill(pid, name); } catch {} }; + kill('SIGTERM'); + for (let waited = 0; alive(pid); waited += 100) { + if (waited === 5000) kill('SIGKILL'); + if (waited > 10_000) throw new Error(`Aether node process ${pid} from a stopped bridge did not stop; stop it, then restart the connector`); + await sleep(100); + } +} + +// Removes a lock whose owner process is gone. The lock is renamed first and +// checked again, so two bridges taking over at once cannot remove the lock +// the faster one has just made. +async function takeOver(lock, stale, dataDir) { + await stopOrphanNode(stale.node, dataDir); + const moved = `${lock}.stale-${process.pid}`; + try { renameSync(lock, moved); } catch { return; } + if (readOwner(moved)?.pid === stale.pid) { rmSync(moved, { recursive: true, force: true }); return; } + try { renameSync(moved, lock); } catch {} +} + +/** + * Becomes the node owner or a proxy to the bridge that already is. + * Owner: `{ role: 'owner', serve, recordNode, release }`. + * Proxy: `{ role: 'proxy', executor }`; `executor.closed` settles when the owner goes away. + */ +export async function acquireRuntime({ stateDir, dataDir, waitMs = 10_000, signal }) { + const lock = path.join(stateDir, 'runtime.lock'); + const socketPath = path.join(stateDir, 'bridge.sock'); + const deadline = Date.now() + waitMs; + for (;;) { + signal?.throwIfAborted(); + try { + mkdirSync(lock, { mode: 0o700 }); + writeOwner(lock, { pid: process.pid }); + return ownerLease(lock, socketPath); + } catch (error) { + if (error.code !== 'EEXIST') throw error; + } + const owner = readOwner(lock); + if (owner && !alive(owner.pid)) { + await takeOver(lock, owner, dataDir); + continue; + } + if (owner) { + const executor = await connectExecutor(socketPath).catch(() => undefined); + if (executor) return { role: 'proxy', executor }; + } + if (Date.now() >= deadline) { + throw new Error(owner + ? `Bridge process ${owner.pid} holds grokbot-bridge/runtime.lock but does not answer; stop it and its Aether node, then restart the connector` + : 'Node runtime is locked by a bridge that did not record its process; stop any prior bridge and node before removing grokbot-bridge/runtime.lock'); + } + // The owner may still be starting: it makes the lock before its socket. + await sleep(250, undefined, signal ? { signal } : undefined); + } +} + +function ownerLease(lock, socketPath) { + let released = false; + let server; + return { + role: 'owner', + recordNode(pid) { if (!released) writeOwner(lock, { pid: process.pid, node: pid }); }, + async serve(executor, onClients) { + server = await serveExecutor(socketPath, executor, onClients); + return server; + }, + release() { + if (released) return; + released = true; + server?.close(); + // The socket goes before the lock: a new owner listens only after taking the lock. + rmSync(socketPath, { force: true }); + rmSync(lock, { recursive: true, force: true }); + }, + }; +} + +function lines(socket, receive) { + let buffer = ''; + socket.setEncoding('utf8'); + socket.on('data', chunk => { + buffer += chunk; + let end; + while ((end = buffer.indexOf('\n')) >= 0) { + const line = buffer.slice(0, end); + buffer = buffer.slice(end + 1); + let message; + try { message = JSON.parse(line); } catch { socket.destroy(); return; } + receive(message); + } + if (buffer.length > MAX_LINE) socket.destroy(); + }); + socket.on('error', () => {}); +} + +const METHODS = { + status: executor => executor.status(), + claim: (executor, { claim_id }) => executor.claim(claim_id), + progress: (executor, { id, lease }) => executor.progress(id, lease), + finish: (executor, { id, lease, outcome, text }) => executor.finish(id, lease, outcome, text), +}; + +async function answer(executor, request) { + const id = request?.id; + if (!Object.hasOwn(METHODS, request?.method)) return { id, error: 'Unknown bridge request' }; + try { return { id, result: await METHODS[request.method](executor, request.params ?? {}) }; } + catch (error) { return { id, error: publicError(error) }; } +} + +export async function serveExecutor(socketPath, executor, onClients = () => {}) { + rmSync(socketPath, { force: true }); + const clients = new Set(); + const server = net.createServer(socket => { + clients.add(socket); + onClients(clients.size); + lines(socket, request => { + void answer(executor, request).then(reply => { + if (!socket.destroyed) socket.write(JSON.stringify(reply) + '\n'); + }); + }); + socket.on('close', () => { clients.delete(socket); onClients(clients.size); }); + }); + server.listen(socketPath); + await new Promise((resolve, reject) => { + server.once('listening', resolve); + server.once('error', reject); + }); + chmodSync(socketPath, 0o600); + const close = server.close.bind(server); + server.close = callback => { + for (const socket of clients) socket.destroy(); + return close(callback); + }; + return server; +} + +export function connectExecutor(socketPath) { + return new Promise((resolve, reject) => { + const socket = net.createConnection(socketPath); + socket.once('error', reject); + socket.once('connect', () => { socket.off('error', reject); resolve(remoteExecutor(socket)); }); + }); +} + +function remoteExecutor(socket) { + const waiting = new Map(); + let next = 0; + let closed; + const done = new Promise(resolve => { closed = resolve; }); + lines(socket, reply => { + const call = waiting.get(reply?.id); + if (!call) return; + waiting.delete(reply.id); + if (typeof reply.error === 'string') call.reject(new Error(reply.error)); + else call.resolve(reply.result); + }); + socket.on('close', () => { + for (const call of waiting.values()) call.reject(new Error(UNAVAILABLE)); + waiting.clear(); + closed(); + }); + const call = (method, params) => new Promise((resolve, reject) => { + if (socket.destroyed) { reject(new Error(UNAVAILABLE)); return; } + next += 1; + waiting.set(next, { resolve, reject }); + socket.write(JSON.stringify({ id: next, method, params }) + '\n'); + }); + return { + status: () => call('status'), + claim: claim_id => call('claim', { claim_id }), + progress: (id, lease) => call('progress', { id, lease }), + finish: (id, lease, outcome, text) => call('finish', { id, lease, outcome, text }), + closed: done, + close: () => socket.destroy(), + }; +} diff --git a/integrations/grokbot-bridge/src/server.mjs b/integrations/grokbot-bridge/src/server.mjs index 5a34d01..0534056 100644 --- a/integrations/grokbot-bridge/src/server.mjs +++ b/integrations/grokbot-bridge/src/server.mjs @@ -4,40 +4,54 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; import { z } from 'zod'; -export function createMcpServer(mailbox) { +// Task text, credentials and internal filesystem paths never enter errors. +export function publicError(error) { + return error?.code ? 'Bridge storage unavailable; stop work and contact the owner' : String(error?.message ?? error); +} + +// The four executor operations on this process's own mailbox. A bridge that +// does not own the node uses the same operations forwarded to the owner. +export function localExecutor(mailbox) { + return { + status() { + mailbox.tick(); + return { connected: mailbox.connected, waiting: mailbox.pending.size, + executor: mailbox.active ? (mailbox.active.stopped ? 'stop_required' : 'busy') : 'idle' }; + }, + claim: claimId => mailbox.claim(claimId), + progress: (id, lease) => mailbox.progress(id, lease), + finish: (id, lease, outcome, text) => mailbox.finish(id, lease, outcome, text), + }; +} + +export function createMcpServer(executor) { const server = new McpServer({ name: 'aether-grokbot-executor', version: '0.1.0' }); const claim = { id: z.string().min(1).max(256), lease: z.string().uuid() }; const register = (name, description, inputSchema, run) => server.registerTool(name, { description, inputSchema, }, async args => { try { - return { content: [{ type: 'text', text: JSON.stringify(run(args)) }] }; + return { content: [{ type: 'text', text: JSON.stringify(await run(args)) }] }; } catch (error) { - // Task text, credentials and internal filesystem paths never enter errors. - const message = error?.code ? 'Bridge storage unavailable; stop work and contact the owner' : error.message; - return { isError: true, content: [{ type: 'text', text: message }] }; + return { isError: true, content: [{ type: 'text', text: publicError(error) }] }; } }); register('bridge_status', 'Check local node connectivity and whether a prior claim needs stopping. This does not claim or execute work.', - {}, () => { - mailbox.tick(); - return { connected: mailbox.connected, waiting: mailbox.pending.size, - executor: mailbox.active ? (mailbox.active.stopped ? 'stop_required' : 'busy') : 'idle' }; - }); + {}, () => executor.status()); register('claim_task', 'Claim at most one untrusted Aether task. Generate a fresh UUID claim_id before calling; reuse it only to retry this claim after a lost response. Never run overlapping claims.', - { claim_id: z.string().uuid() }, ({ claim_id }) => mailbox.claim(claim_id)); + { claim_id: z.string().uuid() }, ({ claim_id }) => executor.claim(claim_id)); register('report_progress', 'Check whether this task may continue and renew its lease. Call before work, at least every 30 seconds, and before external actions. On stop_required stop all work and acknowledge with finish_task outcome stopped.', - claim, ({ id, lease }) => mailbox.progress(id, lease)); + claim, ({ id, lease }) => executor.progress(id, lease)); register('finish_task', 'Return the final plain-text answer, report failure, or acknowledge that all task work has stopped. A stopped acknowledgement must include tools and background jobs. Reuse identical arguments when retrying a lost response.', { ...claim, outcome: z.enum(['result', 'failed', 'stopped']), text: z.string().max(32 * 1024) .refine(value => Buffer.byteLength(value) <= 32 * 1024, 'Answer must be at most 32 KiB UTF-8').default('') }, - ({ id, lease, outcome, text }) => mailbox.finish(id, lease, outcome, text)); + ({ id, lease, outcome, text }) => executor.finish(id, lease, outcome, text)); return server; } // Authentication is outside MCP, before parsing or discovery. Only the executor // role is exposed: none of Aether's owner or caller tools are registered here. -export function createBridgeServer({ mailbox, token, publicUrl }) { +export function createBridgeServer({ mailbox, executor = localExecutor(mailbox), token, publicUrl }) { const digest = value => createHash('sha256').update(value).digest(); const expected = digest(`Bearer ${token}`); const publicHost = publicUrl ? new URL(publicUrl).host : undefined; @@ -72,7 +86,7 @@ export function createBridgeServer({ mailbox, token, publicUrl }) { let body; try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return deny(400, 'Invalid JSON'); } - server = createMcpServer(mailbox); + server = createMcpServer(executor); transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); res.setHeader('Cache-Control', 'no-store'); res.once('close', () => { void transport.close(); void server.close(); }); diff --git a/integrations/grokbot-bridge/test/runtime.test.mjs b/integrations/grokbot-bridge/test/runtime.test.mjs new file mode 100644 index 0000000..f8b3f33 --- /dev/null +++ b/integrations/grokbot-bridge/test/runtime.test.mjs @@ -0,0 +1,193 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import path from 'node:path'; +import os from 'node:os'; +import { fileURLToPath } from 'node:url'; +import { randomUUID } from 'node:crypto'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { acquireRuntime, alive } from '../src/runtime.mjs'; + +const installer = fileURLToPath(new URL('../install.mjs', import.meta.url)); +const bridge = fileURLToPath(new URL('../src/main.mjs', import.meta.url)); + +function directory(t) { + const dir = mkdtempSync(path.join(os.tmpdir(), 'ae-runtime-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + return dir; +} + +async function until(check, message, ms = 7000) { + const deadline = Date.now() + ms; + for (;;) { + const value = await check(); + if (value) return value; + assert.ok(Date.now() < deadline, message); + await sleep(20); + } +} + +async function deadPid() { + const child = spawn(process.execPath, ['-e', '']); + await once(child, 'exit'); + return child.pid; +} + +function staleLock(stateDir, owner) { + const lock = path.join(stateDir, 'runtime.lock'); + mkdirSync(lock, { recursive: true }); + if (owner) writeFileSync(path.join(lock, 'owner.json'), JSON.stringify(owner)); + return lock; +} + +test('a second bridge forwards to the owner, and becomes the owner once it is gone', async t => { + const stateDir = directory(t); + const owner = await acquireRuntime({ stateDir, dataDir: stateDir }); + assert.equal(owner.role, 'owner'); + t.after(() => owner.release()); + await owner.serve({ + status: () => ({ connected: true, waiting: 2, executor: 'idle' }), + claim: () => { throw new Error('Claim is blocked'); }, + progress: async (id, lease) => ({ id, lease, status: 'running' }), + finish: () => { throw Object.assign(new Error('/private/path'), { code: 'EACCES' }); }, + }); + const proxy = await acquireRuntime({ stateDir, dataDir: stateDir }); + assert.equal(proxy.role, 'proxy'); + t.after(() => proxy.executor.close()); + assert.deepEqual(await proxy.executor.status(), { connected: true, waiting: 2, executor: 'idle' }); + assert.deepEqual(await proxy.executor.progress('a', 'b'), { id: 'a', lease: 'b', status: 'running' }); + await assert.rejects(proxy.executor.claim(randomUUID()), { message: 'Claim is blocked' }); + // Storage errors keep their public form across the socket: no paths. + await assert.rejects(proxy.executor.finish('a', 'b', 'result', ''), { message: /^Bridge storage unavailable/ }); + owner.release(); + await proxy.executor.closed; + const next = await acquireRuntime({ stateDir, dataDir: stateDir }); + assert.equal(next.role, 'owner'); + next.release(); +}); + +test('a lock left by a bridge that is gone is taken over', async t => { + const stateDir = directory(t); + staleLock(stateDir, { pid: await deadPid() }); + const runtime = await acquireRuntime({ stateDir, dataDir: stateDir, waitMs: 500 }); + assert.equal(runtime.role, 'owner'); + assert.equal(JSON.parse(readFileSync(path.join(stateDir, 'runtime.lock', 'owner.json'), 'utf8')).pid, process.pid); + runtime.release(); + assert.equal(existsSync(path.join(stateDir, 'runtime.lock')), false); +}); + +test('taking over a stale lock stops the node its bridge left running', { skip: !existsSync('/proc/self/cmdline') }, async t => { + const stateDir = directory(t); + const dataDir = path.join(stateDir, 'data'); + const orphan = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)', 'node', 'serve', '--data-dir', dataDir]); + t.after(() => orphan.kill('SIGKILL')); + staleLock(stateDir, { pid: await deadPid(), node: orphan.pid }); + const runtime = await acquireRuntime({ stateDir, dataDir, waitMs: 500 }); + assert.equal(runtime.role, 'owner'); + assert.equal(alive(orphan.pid), false); + runtime.release(); +}); + +test('a live process that is not the stale bridge\'s node is never signalled', async t => { + const stateDir = directory(t); + const other = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']); + t.after(() => other.kill('SIGKILL')); + staleLock(stateDir, { pid: await deadPid(), node: other.pid }); + const runtime = await acquireRuntime({ stateDir, dataDir: path.join(stateDir, 'data'), waitMs: 500 }); + assert.equal(runtime.role, 'owner'); + assert.equal(alive(other.pid), true); + runtime.release(); +}); + +test('a lock without an owner record, or whose live owner does not answer, is reported', async t => { + const stateDir = directory(t); + const lock = staleLock(stateDir); + await assert.rejects(acquireRuntime({ stateDir, dataDir: stateDir, waitMs: 300 }), { message: /did not record its process/ }); + writeFileSync(path.join(lock, 'owner.json'), JSON.stringify({ pid: process.pid })); + await assert.rejects(acquireRuntime({ stateDir, dataDir: stateDir, waitMs: 300 }), { message: new RegExp(`Bridge process ${process.pid} .* does not answer`) }); + assert.equal(existsSync(lock), true); +}); + +test('the exit message carries the node\'s last stderr line and the lock is released', async t => { + const dir = directory(t); + const binary = path.join(dir, 'fake-aether'); + const data = path.join(dir, 'data'); + writeFileSync(binary, `#!${process.execPath} +process.stderr.write('aether: starting\\n'); +process.stderr.write('aether: node policy workspace /gone cannot be opened (entity not found)\\n'); +process.exit(1); +`, { mode: 0o700 }); + const child = spawn(process.execPath, [bridge], { + env: { ...process.env, AETHER_DATA_DIR: data, AETHER_BIN: binary, GROKBOT_TRANSPORT: 'stdio', GROKBOT_START_NODE: '1', GROKBOT_EXPERIMENTAL: '1' }, + stdio: ['pipe', 'ignore', 'pipe'], + }); + t.after(() => child.kill('SIGKILL')); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk; }); + const [code] = await once(child, 'exit'); + assert.equal(code, 1); + assert.match(stderr, /Local Aether node exited \(code 1\): aether: node policy workspace \/gone cannot be opened \(entity not found\); closing the executor/); + assert.equal(existsSync(path.join(data, 'grokbot-bridge', 'runtime.lock')), false); +}); + +test('two command connectors share one node; the survivor restarts it when the owner closes', async t => { + const dir = directory(t); + const binary = path.join(dir, 'fake-aether'); + const data = path.join(dir, 'data'); + const starts = path.join(dir, 'starts'); + writeFileSync(binary, `#!${process.execPath} +import net from 'node:net'; +import fs from 'node:fs'; +import path from 'node:path'; +if (process.argv.includes('--help')) { console.log('--adapter'); process.exit(0); } +fs.appendFileSync(${JSON.stringify(starts)}, process.pid + '\\n'); +const socket = path.join(process.env.AETHER_DATA_DIR, 'agent.sock'); +fs.rmSync(socket, { force: true }); +net.createServer(peer => { + let buffer = ''; + peer.setEncoding('utf8'); + peer.on('data', chunk => { + buffer += chunk; + let end; + while ((end = buffer.indexOf('\\n')) !== -1) { + const message = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1); + if (message.type === 'ready') peer.write(JSON.stringify({ type: 'task', id: 'task-' + process.pid, instructions: 'Be brief.', text: 'Name a colour.' }) + '\\n'); + } + }); +}).listen(socket); +process.on('SIGTERM', () => process.exit(0)); +`, { mode: 0o700 }); + const install = spawnSync(process.execPath, [installer, '--data-dir', data, '--aether-bin', binary], { encoding: 'utf8' }); + assert.equal(install.status, 0, install.stdout + install.stderr); + const config = JSON.parse(install.stdout).mcpServers['aether-executor']; + const connect = async () => { + const transport = new StdioClientTransport({ ...config, stderr: 'pipe' }); + transport.stderr?.resume(); + const client = new Client({ name: 'command-host', version: '1.0.0' }); + await client.connect(transport); + t.after(() => client.close()); + const call = async (name, args = {}) => { + const response = await client.callTool({ name, arguments: args }); + return response.isError ? { error: response.content[0].text } : JSON.parse(response.content[0].text); + }; + return { client, call }; + }; + const nodes = () => existsSync(starts) ? readFileSync(starts, 'utf8').trim().split('\n').map(Number) : []; + const first = await connect(); + await until(async () => { const s = await first.call('bridge_status'); return s.connected && s.waiting; }, 'owner node must connect'); + const second = await connect(); + // The second connector reads the owner's mailbox; it does not start a node. + assert.deepEqual(await second.call('bridge_status'), { connected: true, waiting: 1, executor: 'idle' }); + assert.equal(nodes().length, 1); + const assignment = await second.call('claim_task', { claim_id: randomUUID() }); + assert.equal(assignment.id, `task-${nodes()[0]}`); + assert.equal((await first.call('finish_task', { id: assignment.id, lease: assignment.lease, outcome: 'result', text: 'Blue' })).status, 'recorded'); + await first.client.close(); + await until(() => nodes().length === 2 && !alive(nodes()[0]), 'the survivor must start a new node after the old one stops'); + await until(async () => { const s = await second.call('bridge_status'); return s.connected && s.waiting; }, 'survivor node must connect'); + assert.equal((await second.call('claim_task', { claim_id: randomUUID() })).id, `task-${nodes()[1]}`); +});