Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 81 additions & 5 deletions crates/aether/src/node_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<PathBuf, PolicyError> {
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(
Expand Down Expand Up @@ -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");
Expand Down
4 changes: 4 additions & 0 deletions crates/aether/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
19 changes: 16 additions & 3 deletions integrations/grokbot-bridge/INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<data-dir>/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
(`<data-dir>/../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

Expand Down
151 changes: 121 additions & 30 deletions integrations/grokbot-bridge/src/main.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
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';
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);
Expand All @@ -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';
Expand Down Expand Up @@ -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; });
Loading
Loading