Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): ban sleeping in code mode and point agents at routines (#9322)
Wolf Mermelstein1312c3aca961
diff --git a/crates/code_execution/AGENTS.md b/crates/code_execution/AGENTS.mdindex fbc7475a9b..3f8d83d295 100644--- a/crates/code_execution/AGENTS.md+++ b/crates/code_execution/AGENTS.md@@ -25,6 +25,10 @@ run under a plain user token (public MCP) has. APIs that ask a program toconfirm what a person picks by opening something read it; the calendarmutation routes demand the copy's `inbox` from such requests.+The bootstrap bans timers before importing `main.mjs`, and the import map points+node timer and worker modules at `timers.mjs`. The bundled SDK's only timer is+the SSE reconnect delay, so a reconnecting event stream fails the same way.+The bootstrap replaces a result's `data` larger than `Limits::max_result_bytes`with an outline and preview, keeping `reviews`; the frame limit stays the backstop.diff --git a/crates/code_execution/README.md b/crates/code_execution/README.mdindex a94c614567..12b04740ff 100644--- a/crates/code_execution/README.md+++ b/crates/code_execution/README.md@@ -57,6 +57,9 @@ The supervisor clears inherited environment variables and gives each process aprivate scratch directory. Deno permits reads only there and network connectionsonly to the configured API host/port destinations. Remote and npm imports,writes, environment access, subprocesses, FFI, and system information are denied.+Timers, workers and other sleep primitives throw an error that points programs+at `macro.routines.create` for checking back later; this steers agents and is not+a security boundary.The trusted bootstrap dynamically imports generated `main.mjs` so its modulereads are subject to the scratch read permission. Both static and dynamic importsoutside scratch are covered by real-runtime tests.diff --git a/crates/code_execution/src/outbound/deno.rs b/crates/code_execution/src/outbound/deno.rsindex 377cb427a4..e96c8fd5a6 100644--- a/crates/code_execution/src/outbound/deno.rs+++ b/crates/code_execution/src/outbound/deno.rs@@ -22,6 +22,7 @@ use tokio_util::{const BOOTSTRAP: &str = include_str!("deno/bootstrap.mjs");const SDK: &str = include_str!("deno/sdk.mjs");const HANDLEBARS: &str = include_str!("deno/handlebars.mjs");+const TIMERS: &str = include_str!("deno/timers.mjs");/// Runtime version pinned by the container and checked at startup.pub const DENO_VERSION: &str = "2.9.6";@@ -115,9 +116,12 @@ impl DenoRunner {tokio::fs::write(root.join("handlebars.mjs"), HANDLEBARS).await.map_err(internal)?;+ tokio::fs::write(root.join("timers.mjs"), TIMERS)+ .await+ .map_err(internal)?;tokio::fs::write(root.join("imports.json"),- r#"{"imports":{"@macro-inc/sdk":"./sdk.mjs","handlebars":"./handlebars.mjs"}}"#,+ r#"{"imports":{"@macro-inc/sdk":"./sdk.mjs","handlebars":"./handlebars.mjs","node:timers":"./timers.mjs","node:timers/promises":"./timers.mjs","node:worker_threads":"./timers.mjs","timers":"./timers.mjs","timers/promises":"./timers.mjs","worker_threads":"./timers.mjs"}}"#,).await.map_err(internal)?;diff --git a/crates/code_execution/src/outbound/deno/bootstrap.mjs b/crates/code_execution/src/outbound/deno/bootstrap.mjsindex 1b4f7b69b0..b97a04c397 100644--- a/crates/code_execution/src/outbound/deno/bootstrap.mjs+++ b/crates/code_execution/src/outbound/deno/bootstrap.mjs@@ -62,6 +62,17 @@ globalThis.console = {log: consoleMethod("info"), info: consoleMethod("info"),debug: consoleMethod("debug"), warn: consoleMethod("warn"), error: consoleMethod("error"),};+// Sleeping to wait for something burns the execution deadline and blocks the+// turn. A worker would bring fresh timers; imports of node timer modules are+// remapped to timers.mjs.+// A function, not an arrow, so `new Worker(...)` reaches the throw.+const sleepBanned = (name) => function () {+ throw new Error(`${name} is unavailable in ExecuteCode: do not sleep or poll in a program. Finish this execution, and to check back later create a routine with macro.routines.create.`);+};+for (const name of ["setTimeout", "setInterval", "setImmediate", "Worker"]) globalThis[name] = sleepBanned(name);+AbortSignal.timeout = sleepBanned("AbortSignal.timeout");+Atomics.wait = sleepBanned("Atomics.wait");+Atomics.waitAsync = sleepBanned("Atomics.waitAsync");try {const {maxResultBytes, ...context} = await new Response(Deno.stdin.readable).json();const originalFetch = globalThis.fetch.bind(globalThis);diff --git a/crates/code_execution/src/outbound/deno/test.rs b/crates/code_execution/src/outbound/deno/test.rsindex 234825c627..679562de91 100644--- a/crates/code_execution/src/outbound/deno/test.rs+++ b/crates/code_execution/src/outbound/deno/test.rs@@ -280,6 +280,32 @@ async fn denies_ambient_io_and_external_module_imports() {service.shutdown().await;}+#[tokio::test]+#[ignore = "requires pinned Deno runtime"]+async fn rejects_sleeping_and_points_at_routines() {+ let (_root, service) = setup(Limits::default()).await;+ let sources = [+ "export async function main() { await new Promise(resolve => setTimeout(resolve, 20000)); }",+ "export function main() { setInterval(() => {}, 1000); }",+ "export function main() { setImmediate(() => {}); }",+ "export async function main() { await new Promise(resolve => AbortSignal.timeout(1000).addEventListener('abort', resolve)); }",+ "export function main() { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000); }",+ "export async function main() { await Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000).value; }",+ "export function main() { new Worker('data:text/javascript,setTimeout(() => postMessage(1), 1000)', {type: 'module'}); }",+ "export async function main() { const { setTimeout } = await import('node:timers/promises'); await setTimeout(1000); }",+ "import { setTimeout } from 'node:timers'; export async function main() { await new Promise(resolve => setTimeout(resolve, 1000)); }",+ "import { Worker } from 'worker_threads'; export function main() { return Worker; }",+ ];+ for source in sources {+ let (_, outcome) = run(&service, source, 5000).await;+ assert!(+ matches!(&outcome, Outcome::Failed { error } if error.code == FailureCode::Runtime && error.message.contains("create a routine with macro.routines.create")),+ "{source}: {outcome:?}"+ );+ }+ service.shutdown().await;+}+#[tokio::test]#[ignore = "requires pinned Deno runtime"]async fn denies_unlisted_destinations_including_redirects() {@@ -479,7 +505,7 @@ async fn total_output_budget_applies_across_small_frames() {..Limits::default()}).await;- let (_, outcome) = run(&service, "export async function main() { for(let i = 0; i < 20; i++) { console.log('x'.repeat(500)); await new Promise(resolve => setTimeout(resolve, 1)); } return null; }", 5000).await;+ let (_, outcome) = run(&service, "export async function main() { for(let i = 0; i < 20; i++) { console.log('x'.repeat(500)); } return null; }", 5000).await;assert!(matches!(outcome, Outcome::Failed { error } if error.code == FailureCode::Limit && error.message == "process output limit exceeded"));diff --git a/crates/code_execution/src/outbound/deno/timers.mjs b/crates/code_execution/src/outbound/deno/timers.mjsnew file mode 100644index 0000000000..eb7c483546--- /dev/null+++ b/crates/code_execution/src/outbound/deno/timers.mjs@@ -0,0 +1,5 @@+// The import map points node timer and worker modules here; see bootstrap.mjs.+// The exports let named imports link, so evaluation reaches the throw.+export let setTimeout, setInterval, setImmediate, scheduler, promises, Worker;+export default undefined;+throw new Error("Timer and worker modules are unavailable in ExecuteCode: do not sleep or poll in a program. Finish this execution, and to check back later create a routine with macro.routines.create.");diff --git a/services/agent_harness_service/src/internal_mcp/test/code_mode.rs b/services/agent_harness_service/src/internal_mcp/test/code_mode.rsindex a322850468..f56d21c295 100644--- a/services/agent_harness_service/src/internal_mcp/test/code_mode.rs+++ b/services/agent_harness_service/src/internal_mcp/test/code_mode.rs@@ -295,7 +295,7 @@ async fn authenticated_mcp_runs_javascript_and_persists_source_and_result(pool:let running = tokio::spawn(async move {rpc(app, Some("session-secret"), "tools/call", json!({"name": "ExecuteCode", "arguments": {"acting_as": "owner", "turn_id": "00000000-0000-0000-0000-000000000003", "execution_id": cancelled_id,- "source": "export async function main() { await new Promise(r => setTimeout(r, 10000)); return {data:true,reviews:[]}; }"+ "source": "export function main() { while (true) {} }"}})).await});tokio::time::timeout(std::time::Duration::from_secs(5), async {