Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(lending): a lent computer's command returns its output when it hits its limit, and may run up to 15 minutes (#4018)

Aditya Umale9dd48816ee52
diff --git a/electron/cloud-lending.node-test.mjs b/electron/cloud-lending.node-test.mjs
index 9ab3f97b4b..c9d0b67394 100644
--- a/electron/cloud-lending.node-test.mjs
+++ b/electron/cloud-lending.node-test.mjs
@@ -35,7 +35,7 @@ async function scratch(t) {
return dir;
}
-function cloudHome({ cloudHome = true, scopes = ["admin", "client"], details = false, timeouts = false } = {}) {
+function cloudHome({ cloudHome = true, scopes = ["admin", "client"], details = false, timeouts = false, long = false } = {}) {
const json = (value, status = 200) => ({ ok: status < 400, status, body: (async function* () { yield Buffer.from(JSON.stringify(value)); })() });
const state = { paired: true, environmentId: randomUUID(), sessionId: randomUUID(), connects: [], disconnects: 0, disconnectBodies: [], results: [], queue: [], waiting: null };
const nextJob = () => new Promise(resolve => { state.waiting = resolve; });
@@ -46,7 +46,7 @@ function cloudHome({ cloudHome = true, scopes = ["admin", "client"], details = f
state.fetch = async (url, init) => {
const route = new URL(url).pathname;
if (route === "/api/auth/session") return state.paired ? json({ kind: "session", id: state.sessionId, scopes, ...(cloudHome ? { cloudHome: true } : {}) }) : json({ error: "unauthorized" }, 401);
- if (route === "/.well-known/openmausbot/environment") return json({ environmentId: state.environmentId, capabilities: { sharedComputers: true, ...(details ? { lendingDetails: true } : {}), ...(timeouts ? { commandTimeouts: true } : {}) } });
+ if (route === "/.well-known/openmausbot/environment") return json({ environmentId: state.environmentId, capabilities: { sharedComputers: true, ...(details ? { lendingDetails: true } : {}), ...(timeouts ? { commandTimeouts: true } : {}), ...(long ? { longCommands: true } : {}) } });
const body = init?.body ? JSON.parse(init.body) : {};
if (route === "/api/shared-computers/connect") { state.connects.push(body); return json({ ok: true }); }
if (route.endsWith("/poll")) {
@@ -454,3 +454,12 @@ test("another Cloud of the person's own is lent at its own address, apart from M
sharing.cloudChanged();
assert.deepEqual([sharing.cloudState(other).enabled, sharing.cloudState(other).problem], [false, "machine-changed"]);
});
+
+test("says it runs commands up to 900 seconds only to a Cloud that takes it, since an older Cloud refuses fields it does not know", async t => {
+ for (const long of [true, false]) {
+ const { folderPath, home, sharing } = await lendingFixture(t, { home: { timeouts: true, long } });
+ await sharing.saveCloud(env, { folders: [{ id: randomUUID(), path: folderPath, write: false }], screen: false });
+ await connected(sharing, 1, home);
+ assert.equal(home.connects[0].longCommands, long ? true : undefined);
+ }
+});
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index 9ec41e6dba..8131136eee 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -347,7 +347,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
.catch(error => { throw error.status === 401 || error.status === 403 ? Object.assign(error, { problem: "connect-first" }) : error; });
if (auth.kind !== "session" || !uuid(auth.id) || !uuid(descriptor.environmentId)) throw Object.assign(new Error("Complete server pairing or sign-in first"), { problem: "connect-first" });
if (descriptor.capabilities?.sharedComputers !== true) throw new Error("Update this server to enable computer sharing");
- return { auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: descriptor.capabilities?.lendingDetails === true, link: descriptor.capabilities?.deviceLink === true, chrome: descriptor.capabilities?.myChromeLink === true, timeouts: descriptor.capabilities?.commandTimeouts === true, edits: descriptor.capabilities?.fileEdits === true, asks: descriptor.capabilities?.computerAsks === true };
+ return { auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: descriptor.capabilities?.lendingDetails === true, link: descriptor.capabilities?.deviceLink === true, chrome: descriptor.capabilities?.myChromeLink === true, timeouts: descriptor.capabilities?.commandTimeouts === true, long: descriptor.capabilities?.longCommands === true, edits: descriptor.capabilities?.fileEdits === true, asks: descriptor.capabilities?.computerAsks === true };
};
const identity = async env => {
await requireEnabled();
@@ -360,7 +360,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
* server the move chose (lending-target.mjs `own:<environment id>`). */
const ownHomeId = env => { const current = cloud(env); return current?.origin === env.origin && current.accountId?.startsWith("own:") ? current.accountId.slice(4) : null; };
const cloudIdentity = async env => {
- const { auth, info, details, link, chrome: takesChrome, timeouts, edits } = await describe(env);
+ const { auth, info, details, link, chrome: takesChrome, timeouts, long, edits } = await describe(env);
const own = ownHomeId(env);
if (own !== null && (auth.own !== true || info.environmentId !== own)) throw Object.assign(new Error("This server is not your bots' home any more"), { problem: "not-cloud" });
if ((own === null && auth.cloudHome !== true) || !Array.isArray(auth.scopes) || !auth.scopes.includes("admin")) throw Object.assign(new Error("This server is not My Cloud"), { problem: "not-cloud" });
@@ -368,6 +368,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
if (link) supportsLink.add(env.id); else supportsLink.delete(env.id);
if (takesChrome) supportsChrome.add(env.id); else supportsChrome.delete(env.id);
if (timeouts) supportsTimeouts.add(env.id); else supportsTimeouts.delete(env.id);
+ if (long) supportsLong.add(env.id); else supportsLong.delete(env.id);
if (edits) supportsEdits.add(env.id); else supportsEdits.delete(env.id);
return info;
};
@@ -376,6 +377,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
/** The Clouds that take the person's Chrome over the device link. */
const supportsChrome = new Set();
const supportsTimeouts = new Set();
+ const supportsLong = new Set();
const supportsEdits = new Set();
/** My Cloud's browsers reach the web through this computer while lending runs; never while My Cloud sleeps, so a
* sleeping Cloud is never dialled. */
@@ -445,6 +447,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
...(grant.cloud && supportsLink.has(env.id) ? { internet: lendsInternet(grant) } : {}),
...(grant.cloud && supportsChrome.has(env.id) ? { chrome: grant.chrome === true } : {}),
...(supportsTimeouts.has(env.id) ? { commandTimeouts: true } : {}),
+ ...(supportsLong.has(env.id) ? { longCommands: true } : {}),
...(supportsEdits.has(env.id) ? { fileEdits: true } : {}),
}, signal, grant.secret);
if (signal.aborted) break;
diff --git a/electron/shared-computer-access.mjs b/electron/shared-computer-access.mjs
index 358048e51b..5433932203 100644
--- a/electron/shared-computer-access.mjs
+++ b/electron/shared-computer-access.mjs
@@ -18,8 +18,7 @@ const OUTPUT_LIMIT = 256 * 1024;
// and on Windows a grandchild whose parent has exited is outside the tree taskkill /T ends. A command's result is
// therefore what it wrote by shortly after it exited, and a stopped command ends shortly after the stop.
const COMMAND_SECONDS = 120;
-/** Below the 300-second wait for response headers in Node's fetch (undici), which carries the result back to the bot. */
-const MAX_COMMAND_SECONDS = 240;
+const MAX_COMMAND_SECONDS = 900;
const PIPE_GRACE_MS = 1000;
const STOP_GRACE_MS = 5000;
/** The server reads a result body of at most 4,000,000 bytes. */
@@ -196,7 +195,7 @@ export async function sharedCommand(command, cwd, signal, seconds = COMMAND_SECO
// Without PATHEXT, PowerShell treats even .exe files as documents.
env: { ...hostEnvironment(), ...(PATH ? { PATH } : {}) },
});
- const chunks = []; let bytes = 0; let reason; let settled = false;
+ const chunks = []; let bytes = 0; let reason; let keepOutput = false; let settled = false;
const graces = [];
const settle = (code, error) => {
if (settled) return;
@@ -204,22 +203,24 @@ export async function sharedCommand(command, cwd, signal, seconds = COMMAND_SECO
clearTimeout(timer); for (const grace of graces) clearTimeout(grace);
signal.removeEventListener("abort", abort);
child.stdout.destroy(); child.stderr.destroy();
+ const output = Buffer.concat(chunks).toString("utf8");
if (error) reject(error);
+ else if (keepOutput) resolve({ ...text({ exitCode: null, stopped: reason, output }), isError: true });
else if (reason) reject(new Error(reason));
- else resolve(text({ exitCode: code, output: Buffer.concat(chunks).toString("utf8") }));
+ else resolve(text({ exitCode: code, output }));
};
- const stop = message => {
+ const stop = (message, withOutput = false) => {
if (settled || reason) return;
- reason = message;
+ reason = message; keepOutput = withOutput;
killTree(child);
graces.push(setTimeout(() => settle(null), STOP_GRACE_MS));
};
const abort = () => stop("Computer access was revoked or the requesting turn ended. Inspect the result before retrying.");
signal.addEventListener("abort", abort, { once: true });
- const timer = setTimeout(() => stop(`Command timed out after ${seconds} second${seconds === 1 ? "" : "s"}; inspect before retrying, or give a longer timeout_seconds.`), seconds * 1000);
+ const timer = setTimeout(() => stop(`Stopped at its ${seconds}-second limit; output is what it printed until then. Inspect before retrying, or give a longer timeout_seconds.`, true), seconds * 1000);
for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => {
bytes += chunk.length;
- if (bytes <= OUTPUT_LIMIT) chunks.push(chunk); else stop("Command output exceeded the limit");
+ if (bytes <= OUTPUT_LIMIT) chunks.push(chunk); else stop(`Stopped after ${OUTPUT_LIMIT / 1024} KB of output; output is its first ${OUTPUT_LIMIT / 1024} KB. Send long output to a file and read it.`, true);
});
child.once("error", error => settle(null, error));
child.once("close", code => settle(code));
diff --git a/electron/shared-computer-access.node-test.mjs b/electron/shared-computer-access.node-test.mjs
index 4236ec6185..0dbb2af76f 100644
--- a/electron/shared-computer-access.node-test.mjs
+++ b/electron/shared-computer-access.node-test.mjs
@@ -299,15 +299,40 @@ test("a command runs up to the time the call asks for, and a time out of range i
const run = operation => executeSharedOperation(grant, { folder_id: folder.id, action: "run_command", ...operation }, new AbortController().signal);
const command = process.platform === "win32" ? "Start-Sleep -Seconds 5" : "sleep 5";
const started = Date.now();
- await assert.rejects(run({ command, timeout_seconds: 1 }), /timed out after 1 second/);
+ assert.match(payload(await run({ command, timeout_seconds: 1 })).stopped, /1-second limit/);
assert.ok(Date.now() - started < 4_000, `took ${Date.now() - started} ms`);
- for (const timeout_seconds of [0, 241, 1.5, "60"]) {
- await assert.rejects(run({ command: "echo no", timeout_seconds }), /from 1 to 240/);
+ for (const timeout_seconds of [0, 901, 1.5, "60"]) {
+ await assert.rejects(run({ command: "echo no", timeout_seconds }), /from 1 to 900/);
}
assert.equal(payload(await run({ command: "echo fixture-default" })).exitCode, 0);
+ assert.equal(payload(await run({ command: "echo fixture-long", timeout_seconds: 900 })).exitCode, 0);
void dir;
});
+test("a command stopped at its time limit returns what it printed and says it was stopped", async t => {
+ const { grant, folder } = await fixture(t);
+ grant.terminal = true;
+ const command = process.platform === "win32"
+ ? "Write-Output first-line; [Console]::Error.WriteLine('second-line'); Start-Sleep -Seconds 20"
+ : "echo first-line; echo second-line >&2; sleep 20";
+ const stopped = await executeSharedOperation(grant, { folder_id: folder.id, action: "run_command", command, timeout_seconds: 2 }, new AbortController().signal);
+ assert.equal(stopped.isError, true);
+ const result = payload(stopped);
+ assert.equal(result.exitCode, null);
+ assert.match(result.output, /first-line[\s\S]*second-line/);
+ assert.match(result.stopped, /Stopped at its 2-second limit/);
+});
+
+test("a command stopped for too much output returns the output it kept", { skip: process.platform === "win32" }, async t => {
+ const { grant, folder } = await fixture(t);
+ grant.terminal = true;
+ const stopped = await executeSharedOperation(grant, { folder_id: folder.id, action: "run_command", command: "echo first-line; head -c 300000 /dev/zero | tr '\\0' a; sleep 20", timeout_seconds: 30 }, new AbortController().signal);
+ assert.equal(stopped.isError, true);
+ const result = payload(stopped);
+ assert.match(result.output, /^first-line/);
+ assert.match(result.stopped, /Stopped after 256 KB of output/);
+});
+
/** A command that starts a process which outlives it, outside its process tree, holding its output; and that process's pid. */
async function backgroundHolder(dir, then) {
const script = path.join(dir, "holder.mjs");
diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json
index 3c81910331..96bd242408 100644
--- a/server/drivers/agents-catalog-goldens/full.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json
@@ -44,7 +44,7 @@
},
{
"name": "shared_computer",
- "description": "Use a desktop the user explicitly shared. Get computer_id and folder_id from list_shared_computers. File actions stay in chosen folders; paths are relative. read_file returns sha256, needed as expected_sha256 to overwrite or delete_file. edit_file swaps old_text (once) for new_text; append_file adds content. Binary files: base64 encoding. run_command requires a SEPARATE unrestricted terminal grant and stops after timeout_seconds (default 120, at most 240): run longer jobs in the background with output to a file, then read it. computer_tools lists the native computer-control tools; computer_call invokes one with arguments and needs a SEPARATE computer-control grant. To browse there, open pages with launch_app urls (the person's own browser) and use get_window_state, click and type_text: the browser_* tools need a DevTools endpoint most browsers lack. Never substitute the server's filesystem when this desktop is offline. Actions are not retried: inspect an uncertain outcome before retrying.",
+ "description": "Use a desktop the user explicitly shared. Get computer_id and folder_id from list_shared_computers. File actions stay in chosen folders; paths are relative. read_file returns sha256, needed as expected_sha256 to overwrite or delete_file. edit_file swaps old_text (once) for new_text; append_file adds content. Binary files: base64 encoding. run_command requires a SEPARATE unrestricted terminal grant and stops after timeout_seconds (default 120, at most 900), returning what it printed so far: run longer jobs in the background with output to a file, then read it. computer_tools lists the native computer-control tools; computer_call invokes one with arguments and needs a SEPARATE computer-control grant. To browse there, open pages with launch_app urls (the person's own browser) and use get_window_state, click and type_text: the browser_* tools need a DevTools endpoint most browsers lack. Never substitute the server's filesystem when this desktop is offline. Actions are not retried: inspect an uncertain outcome before retrying.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json
index 6e72012fe1..467f77e17f 100644
--- a/server/drivers/agents-catalog-goldens/profiles.json
+++ b/server/drivers/agents-catalog-goldens/profiles.json
@@ -99,8 +99,8 @@
]
},
"shared": {
- "bytes": 59538,
- "sha256": "f17a59a31d5e955a46612e8ad88bef57f7dcf2c31f7710626de648c5494ba7b3",
+ "bytes": 59572,
+ "sha256": "c8b8e61434260968357288e072cb5cfad0a55ae8f2e59c503a6c817c51299b97",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -150,8 +150,8 @@
]
},
"shared+voice": {
- "bytes": 60319,
- "sha256": "cf89c21944e440ea41cf2ecda8e3b08a3899df0808150eaccbc1c205f3ee68da",
+ "bytes": 60353,
+ "sha256": "a1a2ec30d77a4a7ceb937ace63936cf047a085c9eff02062fc9b77b7e24dfbf7",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -305,8 +305,8 @@
]
},
"skills+shared": {
- "bytes": 62357,
- "sha256": "6bf092b0dea6d0f68e6adf66088c35ed81cf4c1ffea2b05dc1c7b6b0c549f02a",
+ "bytes": 62391,
+ "sha256": "7d7b5870dba3c6b092150bc5160fd941589a3cd589e24d24e688e96799aa10bd",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -358,8 +358,8 @@
]
},
"skills+shared+voice": {
- "bytes": 63138,
- "sha256": "a480f3a26689d7ea87930b5bf223270034cd509a66ab3f41b450f90d3b46c84e",
+ "bytes": 63172,
+ "sha256": "b258f4c3812237f39033b60674a56789903aa9b7fff4aeba166a13867c101693",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -497,8 +497,8 @@
]
},
"shared+non-chief": {
- "bytes": 50481,
- "sha256": "449e75d37826036c5fa8b0b24332815a4e2224fdc807584badab31352e9c2597",
+ "bytes": 50515,
+ "sha256": "3c01e0bfa051563336965e7e2173c0d3461a360437f213bf70b1fdc201f89b0b",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -541,8 +541,8 @@
]
},
"shared+voice+non-chief": {
- "bytes": 51262,
- "sha256": "b25c2a16d30c9318f147fd5a67a0160f4cf1041c0b563b34a3e2c4826afb722a",
+ "bytes": 51296,
+ "sha256": "043c1a16c195b50bdead36dc4bfac211c222dd47e8a548e7b5e137b5202578c9",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -675,8 +675,8 @@
]
},
"skills+shared+non-chief": {
- "bytes": 53300,
- "sha256": "3a865dc00aac02fcd9fba8ba84f5031fdf88c88246aaa09f40e21918beea5c06",
+ "bytes": 53334,
+ "sha256": "9a4f31d131755a2786e95b0e0e3743fce60dcf0c816b172175c1854bff5a5234",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -721,8 +721,8 @@
]
},
"skills+shared+voice+non-chief": {
- "bytes": 54081,
- "sha256": "8d7550b4e69303be2593d7277c26f0a478cffbcee9b987150f581212ece6d8e7",
+ "bytes": 54115,
+ "sha256": "e00c87532000e3236fc583809d057ce726debd738d28689626e5f2b313ccf2ac",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -768,8 +768,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 62904,
- "sha256": "6b48b6ad4cb69d56e21889591ab1d160f6f86f1e5ae2b2e70d9b6f75cbb6b78d",
+ "bytes": 62938,
+ "sha256": "564541e28cf6b432cd194817972ed34f0686070d892cebf4ddb59143bec362b7",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -822,8 +822,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 53847,
- "sha256": "854139d34d9fa538a582b9f0b08263711de494d9164ab525e3f59f11f8f64a7d",
+ "bytes": 53881,
+ "sha256": "60473428d0887aab07f7fade78f3f94e3e6496d6b0985b8bae242f6ebb5bdda8",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -869,8 +869,8 @@
]
},
"skills+shared+voice+escalations": {
- "bytes": 63968,
- "sha256": "4ab1278694a9cd40243cd5d84f1fd0b1640cabcb44aadf64cfd22c8b822d5042",
+ "bytes": 64002,
+ "sha256": "6c1dad4d7a60cef295bb23ccc1437a4dc6f29e3f3f1b53cab113e676ecf6e9e4",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -924,8 +924,8 @@
]
},
"skills+shared+voice+escalations+x": {
- "bytes": 67807,
- "sha256": "4c58536dc5ccca7db33fc56fbc0b3eab2cbe90a1c48d9fa01f7ac1fc260631ec",
+ "bytes": 67841,
+ "sha256": "1d0fd1cce84b7b59faa74f3810a359b71bac0d53c3b7727aaefbfda337669548",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -983,8 +983,8 @@
]
},
"skills+shared+voice+escalations+x+team": {
- "bytes": 68439,
- "sha256": "f003c6b8571fb7b3442568f0f1b9cb2e101ef02b3d075492a14d35f4a00c875a",
+ "bytes": 68473,
+ "sha256": "213156daba01fd402264ee1ac6a2351bf7f476a1e7793fbaa72bf8cfa84b80e5",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1143,8 +1143,8 @@
]
},
"skills+shared+voice+mausbot": {
- "bytes": 63789,
- "sha256": "e2fcf2493453439bb72ca338d3b1ca878866a06a85ce8bec9e6f24442b5d4358",
+ "bytes": 63823,
+ "sha256": "ba36c4a86a3ea1694a1e861e18c83cfe3a1fef68390258cc633a2158b0b624e9",
"tools": [
"tool_result_read",
"list_shared_computers",
diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.ts
index eb1dc6d6f4..44be21c89e 100644
--- a/server/drivers/agents-catalog.ts
+++ b/server/drivers/agents-catalog.ts
@@ -205,12 +205,12 @@ const TOOL_DEFINITIONS = [
},
{
name: "shared_computer",
- description: "Use a desktop the user explicitly shared. Get computer_id and folder_id from list_shared_computers. File actions stay in chosen folders; paths are relative. read_file returns sha256, needed as expected_sha256 to overwrite or delete_file. edit_file swaps old_text (once) for new_text; append_file adds content. Binary files: base64 encoding. run_command requires a SEPARATE unrestricted terminal grant and stops after timeout_seconds (default 120, at most 240): run longer jobs in the background with output to a file, then read it. computer_tools lists the native computer-control tools; computer_call invokes one with arguments and needs a SEPARATE computer-control grant. To browse there, open pages with launch_app urls (the person's own browser) and use get_window_state, click and type_text: the browser_* tools need a DevTools endpoint most browsers lack. Never substitute the server's filesystem when this desktop is offline. Actions are not retried: inspect an uncertain outcome before retrying.",
+ description: "Use a desktop the user explicitly shared. Get computer_id and folder_id from list_shared_computers. File actions stay in chosen folders; paths are relative. read_file returns sha256, needed as expected_sha256 to overwrite or delete_file. edit_file swaps old_text (once) for new_text; append_file adds content. Binary files: base64 encoding. run_command requires a SEPARATE unrestricted terminal grant and stops after timeout_seconds (default 120, at most 900), returning what it printed so far: run longer jobs in the background with output to a file, then read it. computer_tools lists the native computer-control tools; computer_call invokes one with arguments and needs a SEPARATE computer-control grant. To browse there, open pages with launch_app urls (the person's own browser) and use get_window_state, click and type_text: the browser_* tools need a DevTools endpoint most browsers lack. Never substitute the server's filesystem when this desktop is offline. Actions are not retried: inspect an uncertain outcome before retrying.",
inputSchema: { type: "object", additionalProperties: false, properties: {
computer_id: { type: "string" }, action: { type: "string", enum: ["list_files", "read_file", "write_file", "edit_file", "append_file", "delete_file", "run_command", "computer_tools", "computer_call"] },
folder_id: { type: "string" }, path: { type: "string" }, content: { type: "string" }, encoding: { type: "string", enum: ["utf8", "base64"] }, expected_sha256: { type: "string" },
old_text: { type: "string" }, new_text: { type: "string" },
- command: { type: "string" }, timeout_seconds: { type: "integer", minimum: 1, maximum: 240 }, tool_name: { type: "string" }, arguments: { type: "object", additionalProperties: true },
+ command: { type: "string" }, timeout_seconds: { type: "integer", minimum: 1, maximum: 900 }, tool_name: { type: "string" }, arguments: { type: "object", additionalProperties: true },
}, required: ["computer_id", "action"] },
},
{
diff --git a/server/drivers/agents-client.ts b/server/drivers/agents-client.ts
index b400b5ca1c..beb4fd0682 100644
--- a/server/drivers/agents-client.ts
+++ b/server/drivers/agents-client.ts
@@ -1,29 +1,49 @@
// The agents tools' only way to the harness: loopback /api/internal/* with this turn's capability token;
// the harness authenticates and scopes every call.
+import { request as httpRequest } from "node:http";
+import { request as httpsRequest } from "node:https";
export type Json = Record<string, unknown>;
+export type HarnessRequest = { method?: string; body?: string; headers?: Record<string, string>; signal?: AbortSignal };
+
export interface HarnessClient {
/** The route's JSON body; a refusal throws an Error carrying the route's `error` sentence. */
- api(path: string, init?: RequestInit): Promise<Json>;
+ api(path: string, init?: HarnessRequest): Promise<Json>;
/** Like api, but a refusal comes back as its body. */
- apiResponse(path: string, init?: RequestInit): Promise<{ ok: boolean; status: number; body: Json }>;
+ apiResponse(path: string, init?: HarnessRequest): Promise<{ ok: boolean; status: number; body: Json }>;
+}
+
+/** Node's fetch (undici 7.29 in Electron 43) fails a call after 300 s without response headers, whatever its signal
+ * allows; node:http waits as long as the harness works, such as a lent computer's command of up to 900 s. */
+function send(url: URL, init: HarnessRequest): Promise<{ status: number; text: string }> {
+ return new Promise((resolve, reject) => {
+ const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, { method: init.method ?? "GET", headers: init.headers, signal: init.signal }, (response) => {
+ const chunks: Buffer[] = [];
+ response.on("data", (chunk: Buffer) => chunks.push(chunk));
+ response.on("end", () => resolve({ status: response.statusCode ?? 0, text: Buffer.concat(chunks).toString("utf8") }));
+ response.on("error", reject);
+ });
+ request.on("error", reject);
+ request.end(init.body);
+ });
}
export function createHarnessClient(baseUrl: string, token: string): HarnessClient {
- async function api(path: string, init?: RequestInit): Promise<Json> {
+ async function api(path: string, init?: HarnessRequest): Promise<Json> {
const { ok, status, body } = await apiResponse(path, init);
if (!ok) throw new Error(String(body.error ?? `HTTP ${status}`));
return body;
}
- async function apiResponse(path: string, init?: RequestInit): Promise<{ ok: boolean; status: number; body: Json }> {
- const res = await fetch(baseUrl + path, {
+ async function apiResponse(path: string, init: HarnessRequest = {}): Promise<{ ok: boolean; status: number; body: Json }> {
+ const { status, text } = await send(new URL(baseUrl + path), {
...init,
- headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ...init?.headers },
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ...init.headers },
});
- const body = (await res.json().catch(() => ({}))) as Json;
- return { ok: res.ok, status: res.status, body };
+ let body: Json = {};
+ try { body = JSON.parse(text) as Json; } catch {}
+ return { ok: status >= 200 && status < 300, status, body };
}
return { api, apiResponse };
diff --git a/server/drivers/agents-tool-limit.ts b/server/drivers/agents-tool-limit.ts
new file mode 100644
index 0000000000..1a1b6f3dc1
--- /dev/null
+++ b/server/drivers/agents-tool-limit.ts
@@ -0,0 +1,4 @@
+/** The longest an engine waits on one agents tool call: a lent computer's command of up to 900 seconds, plus the time
+ * its result takes to come back. Codex CLI otherwise ends an MCP tool call after the server's tool_timeout_sec, 60 by
+ * default in its config docs. */
+export const AGENTS_TOOL_TIMEOUT_SECONDS = 960;
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index e1ca51b475..a831a8d7d7 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -1620,6 +1620,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv.join(" ")).toContain("mcp_servers.agents.command");
expect(seen.argv).toContain('mcp_servers.agents.default_tools_approval_mode="approve"');
+ expect(seen.argv).toContain("mcp_servers.agents.tool_timeout_sec=960");
expect(seen.argv.join(" ")).toContain("/tmp/agents-proxy.js");
expect(seen.argv.join(" ")).toContain("OMB_COMMS_TOKEN");
expect(seen.argv.join(" ")).not.toContain("peer-comms-secret");
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index b9a0ef61cd..0f2857a7ec 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -56,7 +56,7 @@ import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-que
import { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";
import { codexReleaseUpdate, codexUpdateCommand } from "./codex-update.ts";
export { codexUpdateCommand };
-import { effectiveApprovalPolicy, effectiveApprovalsReviewer } from "./codex-approval-config.ts";
+import { effectiveApprovalPolicy, effectiveApprovalsReviewer } from "./codex-approval-config.ts"; import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts";
import { canUseMcpServer } from "../../shared/tool-scope.ts";
import { assertToolScopeSupported } from "../../shared/tool-scope-support.ts";
import { appMountFor, gateServer, mcpStdioServer } from "../mcp-gate-config.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";
@@ -717,7 +717,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (turn.integrations?.composioOwn) mountSelected(OWN_APPS_SERVER, `openmausbot_${OWN_APPS_SERVER}`, turn.integrations.composioOwn);
if (turn.integrations?.agents) {
// OpenMausBot's own coordination tools never ask: "auto" quiets only read-only tools.
- mountSelected("agents", "agents", turn.integrations.agents, "approve");
+ mountSelected("agents", "agents", turn.integrations.agents, "approve"); if (selectedMcp.has("agents")) appServerArgs.push("-c", `mcp_servers.agents.tool_timeout_sec=${AGENTS_TOOL_TIMEOUT_SECONDS}`);
}
if (turn.integrations?.localComputer) {
mountSelected("computer", "computer", turn.integrations.localComputer);
diff --git a/server/drivers/pi-mcp-extension.ts b/server/drivers/pi-mcp-extension.ts
index 445589c278..7cc1e54217 100644
--- a/server/drivers/pi-mcp-extension.ts
+++ b/server/drivers/pi-mcp-extension.ts
@@ -8,6 +8,7 @@ import { allowsTool, canUseMcpServer, parseToolScope, type ToolIdentity } from "
import { ASK_USER_TOOL, formatQuestionAnswers, MAX_OPTIONS, MAX_QUESTIONS, parseAskQuestions } from "../../shared/ask-question.ts";
import { CALL_TOOL, directoryCallTarget, isDirectoryTool } from "../mcp-directory.ts";
import { REMOTE_MCP_STARTUP_MS } from "../mcp-http.ts";
+import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts";
interface McpServerDef {
command: string;
@@ -80,7 +81,7 @@ interface PiExtensionApi {
}
const MCP_STARTUP_TIMEOUT_MS = 8_000;
-const MCP_TOOL_TIMEOUT_MS = 10 * 60_000;
+const MCP_TOOL_TIMEOUT_MS = AGENTS_TOOL_TIMEOUT_SECONDS * 1000;
const MCP_MAX_LIST_PAGES = 100;
const MCP_MAX_FRAME_BYTES = 32 * 1024 * 1024;
const TOOL_OUTPUT_MAX_BYTES = 50 * 1024;
diff --git a/server/environment.test.ts b/server/environment.test.ts
index 678e327177..06eeab8fce 100644
--- a/server/environment.test.ts
+++ b/server/environment.test.ts
@@ -129,7 +129,7 @@ describe("environment identity", () => {
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: false }).capabilities)
.not.toHaveProperty("sharedComputers");
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities)
- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, fileEdits: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });
+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true }).capabilities)
.toEqual({ remoteSessions: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: false }).capabilities).not.toHaveProperty("cloudHome");
@@ -138,7 +138,7 @@ describe("environment identity", () => {
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, ownHome: false }).capabilities).not.toHaveProperty("move");
// A lent computer may lend its internet connection only to a Cloud home that lends at all.
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true, sharedComputers: true }).capabilities)
- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, fileEdits: true, deviceLink: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });
+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, deviceLink: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities).not.toHaveProperty("deviceLink");
});
diff --git a/server/environment.ts b/server/environment.ts
index b1b800d258..8ebb1a98f9 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -35,6 +35,8 @@ export interface EnvironmentDescriptor {
computerAsks?: true;
/** A lent computer may say it takes run_command's timeout_seconds; only then does this server send it. */
commandTimeouts?: true;
+ /** A lent computer may say it runs a command for up to 900 seconds; only then does this server ask it for more than 240. */
+ longCommands?: true;
/** A lent computer may say it takes edit_file, append_file and delete_file; only then does this server send them. */
fileEdits?: true;
/** A person's own OMB Cloud home. */
@@ -141,7 +143,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan
remoteSessions: true,
// Never advertise a protocol this server would refuse.
// lendingDetails: a lent computer may say its platform, and this server remembers what was lent to it.
- ...(input.sharedComputers === true ? { sharedComputers: true as const, lendingDetails: true as const, commandTimeouts: true as const, fileEdits: true as const } : {}),
+ ...(input.sharedComputers === true ? { sharedComputers: true as const, lendingDetails: true as const, commandTimeouts: true as const, longCommands: true as const, fileEdits: true as const } : {}),
...(input.sharedComputers === true && input.cloudHome === true ? { deviceLink: true as const } : {}),
...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const, computerAsks: true as const } : {}),
...(input.cloudHome === true ? { cloudHome: true as const, move: 1 as const } : {}),
diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.ts
index a3dd879e72..fc903b9d85 100644
--- a/server/shared-computers.test.ts
+++ b/server/shared-computers.test.ts
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerScopeRefusal } from "./shared-computers.ts";
+import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerOperation, sharedComputerScopeRefusal } from "./shared-computers.ts";
import { hostScreenBusyText, SharedComputerControl } from "./shared-computer-control.ts";
import { TurnResources } from "./turn-resources.ts";
@@ -99,6 +99,27 @@ describe("shared computer authority and lifecycle", () => {
await expect(tools.result).rejects.toThrow(/timed out/);
tools.close();
});
+ it("runs a command up to 900 seconds on a desktop that takes long commands, and refuses past 240 on one that does not", async () => {
+ expect(sharedComputerOperation.safeParse({ computer_id: randomUUID(), action: "run_command", command: "./scan", timeout_seconds: 900 }).success).toBe(true);
+ expect(sharedComputerOperation.safeParse({ computer_id: randomUUID(), action: "run_command", command: "./scan", timeout_seconds: 901 }).success).toBe(false);
+ vi.useFakeTimers();
+ const broker = new SharedComputers(() => true);
+ const computer = { ...registration({ terminal: true }), commandTimeouts: true as const, longCommands: true as const }; broker.register(computer, alice, secret);
+ const result = broker.request({ computer_id: computer.id, action: "run_command", command: "./evals", timeout_seconds: 900 }, alice.person, () => true);
+ result.catch(() => {});
+ const job = await broker.poll(computer.id, alice.session, secret);
+ expect(job!.operation).toMatchObject({ timeout_seconds: 900 });
+ broker.liveJob(computer.id, alice.session, secret, job!.id);
+ await vi.advanceTimersByTimeAsync(899_000);
+ broker.complete(computer.id, alice.session, secret, job!.id, { exitCode: 0 });
+ await expect(result).resolves.toEqual({ exitCode: 0 });
+ broker.close();
+ const older = new SharedComputers(() => true);
+ const capped = { ...registration({ terminal: true }), commandTimeouts: true as const }; older.register(capped, alice, secret);
+ await expect(older.request({ computer_id: capped.id, action: "run_command", command: "./evals", timeout_seconds: 241 }, alice.person, () => true))
+ .rejects.toThrow(/at most 240 seconds/);
+ older.close();
+ });
it("never sends a timeout to a desktop that did not say it takes one, and waits for it as before", async () => {
const broker = new SharedComputers(() => true);
const computer = registration({ terminal: true }); broker.register(computer, alice, secret);
diff --git a/server/shared-computers.ts b/server/shared-computers.ts
index e56a200e53..01ec5d8efc 100644
--- a/server/shared-computers.ts
+++ b/server/shared-computers.ts
@@ -18,6 +18,8 @@ export const sharedComputerRegistration = z.object({
/** It takes and honours run_command's timeout_seconds; sent only to a server that advertises commandTimeouts. Older
* desktops refuse a job with a field they do not know, and stop every command at 30 seconds. */
commandTimeouts: z.literal(true).optional(),
+ /** It runs a command for up to 900 seconds, not 240; sent only to a server that advertises longCommands. */
+ longCommands: z.literal(true).optional(),
/** It takes edit_file, append_file and delete_file; sent only to a server that advertises fileEdits. */
fileEdits: z.literal(true).optional(),
}).strict();
@@ -28,12 +30,13 @@ export const sharedComputerOperation = z.object({
content: z.string().max(350_000).optional(), encoding: z.enum(["utf8", "base64"]).optional(),
old_text: z.string().min(1).max(350_000).optional(), new_text: z.string().max(350_000).optional(),
expected_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
- command: z.string().max(8000).optional(), timeout_seconds: z.number().int().min(1).max(240).optional(), tool_name: z.string().max(100).optional(),
+ command: z.string().max(8000).optional(), timeout_seconds: z.number().int().min(1).max(900).optional(), tool_name: z.string().max(100).optional(),
arguments: z.record(z.string(), z.unknown()).optional(),
}).strict();
type Registration = z.infer<typeof sharedComputerRegistration>;
type Operation = z.infer<typeof sharedComputerOperation>;
const COMMAND_SECONDS = 120;
+const OLD_MAX_COMMAND_SECONDS = 240;
/** A command's deadline is its own limit on the desktop plus time for the result to come back. */
const jobDeadlineMs = (registration: Registration, operation: Operation) =>
operation.action === "run_command" && registration.commandTimeouts ? (operation.timeout_seconds ?? COMMAND_SECONDS) * 1000 + 15_000 : 45_000;
@@ -322,6 +325,9 @@ export class SharedComputers {
const entry = lent()!;
const refusal = sharedComputerScopeRefusal(entry.registration, operation, this.askTool);
if (refusal) throw failure(refusal, 403);
+ if (operation.action === "run_command" && entry.registration.commandTimeouts && !entry.registration.longCommands && (operation.timeout_seconds ?? 0) > OLD_MAX_COMMAND_SECONDS) {
+ throw failure(`${entry.registration.name} runs an older OpenMausBot that stops a command after at most ${OLD_MAX_COMMAND_SECONDS} seconds. Give timeout_seconds of ${OLD_MAX_COMMAND_SECONDS} or less, or run longer jobs in the background with output to a file.`, 400);
+ }
if (entry.jobs.size >= 1) throw failure("This shared computer is busy. Wait for its current action to finish.");
if (!active()) throw failure("The requesting turn ended", 401);
const { timeout_seconds: _timeout, ...withoutTimeout } = operation;