:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(agent-platform): unwrap cjs default export in sandbox dispatcher (#69201)
Aidan Zarski7fd6d346305d
diff --git a/products/agent_platform/services/agent-sandbox-host/README.md b/products/agent_platform/services/agent-sandbox-host/README.mdindex ba79e911d75b..9ec6b3bf0d99 100644--- a/products/agent_platform/services/agent-sandbox-host/README.md+++ b/products/agent_platform/services/agent-sandbox-host/README.md@@ -93,7 +93,9 @@ or{ "ok": false, "error": { "code": "tool_not_found", "message": "..." } }```-Tool contract (`/workdir/tools/<id>/compiled.js`):+Tool contract (`/workdir/tools/<id>/compiled.js`) — two accepted shapes:++1. Plain CJS:```jsmodule.exports = {@@ -108,6 +110,12 @@ module.exports = {}```+2. A `default` property on `module.exports` (esbuild's `__toCommonJS` CJS+ interop for the typed pipeline's mandated `export default {}` source).+ The dispatcher applies the same unwrap rule as the in-process pool+ (`agent-shared/src/sandbox/sandbox-inprocess.ts`): `module.exports.default`+ when present, else `module.exports` itself.+`ctx.secrets.ref(name)` returns the nonce the runner-side `SecretBroker`minted for this session. The sandbox never sees raw secret values; therunner substitutes nonces with real values at egress.diff --git a/products/agent_platform/services/agent-sandbox-host/scripts/smoke-test-image.sh b/products/agent_platform/services/agent-sandbox-host/scripts/smoke-test-image.shindex 7ea896516f0f..b3250f66edfd 100755--- a/products/agent_platform/services/agent-sandbox-host/scripts/smoke-test-image.sh+++ b/products/agent_platform/services/agent-sandbox-host/scripts/smoke-test-image.sh@@ -34,6 +34,34 @@ ECHO_TOOL='module.exports = {},}'+# This fixture IS the repo's esbuild output for the typed pipeline's mandated+# `export default {}` source shape (format:"cjs", loader:"ts", target:"node20")+# — the compiled.js production tools ship. It exposes the tool object as+# `.default` via a __toCommonJS getter on module.exports.+ECHO_DEFAULT_TOOL='var __defProp = Object.defineProperty;+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;+var __getOwnPropNames = Object.getOwnPropertyNames;+var __hasOwnProp = Object.prototype.hasOwnProperty;+var __export = (target, all) => {+ for (var name in all)+ __defProp(target, name, { get: all[name], enumerable: true });+};+var __copyProps = (to, from, except, desc) => {+ if (from && typeof from === "object" || typeof from === "function") {+ for (let key of __getOwnPropNames(from))+ if (!__hasOwnProp.call(to, key) && key !== except)+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });+ }+ return to;+};+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);+var stdin_exports = {};+__export(stdin_exports, {+ default: () => stdin_default+});+module.exports = __toCommonJS(stdin_exports);+var stdin_default = { id: "echo-default", actions: { default: (args, ctx) => ({ doubled: args.n * 2 }) } };'+# Run a single dispatch scenario:# $1 — request JSON# $2 — node assertion script (reads response.json from $1 argument)@@ -48,6 +76,9 @@ run_scenario() {mkdir -p "$workdir/tools/echo"printf '%s' "$ECHO_TOOL" > "$workdir/tools/echo/compiled.js"echo '{ "type": "object" }' > "$workdir/tools/echo/schema.json"+ mkdir -p "$workdir/tools/echo-default"+ printf '%s' "$ECHO_DEFAULT_TOOL" > "$workdir/tools/echo-default/compiled.js"+ echo '{ "type": "object" }' > "$workdir/tools/echo-default/schema.json"echo '{ "TEST_SECRET": "nonce_smoke_abc" }' > "$workdir/nonces.json"printf '%s' "$request_json" > "$workdir/request.json"# Bind-mounted dirs keep the host's UID/GID; the in-container `sandbox`@@ -107,4 +138,12 @@ const res = JSON.parse(require("node:fs").readFileSync(process.argv[2], "utf-8")assert.equal(res.ok, false, `expected ok=false, got ${JSON.stringify(res)}`)assert.equal(res.error.code, "tool_not_found", `wrong code: ${JSON.stringify(res)}`)'+echo "smoke: scenario 4 — esbuild-CJS default-export tool (typed pipeline shape)" >&2+run_scenario \+ '{"toolId":"echo-default","action":"default","args":{"n":21},"timeoutMs":10000}' \+ 'const assert = require("node:assert/strict")+const res = JSON.parse(require("node:fs").readFileSync(process.argv[2], "utf-8"))+assert.equal(res.ok, true, `expected ok=true, got ${JSON.stringify(res)}`)+assert.deepEqual(res.result, { doubled: 42 })'+echo "smoke: PASS — image $IMAGE works end-to-end" >&2diff --git a/products/agent_platform/services/agent-sandbox-host/src/dispatch.js b/products/agent_platform/services/agent-sandbox-host/src/dispatch.jsindex 716bc25a848d..6049e340d729 100644--- a/products/agent_platform/services/agent-sandbox-host/src/dispatch.js+++ b/products/agent_platform/services/agent-sandbox-host/src/dispatch.js@@ -12,13 +12,12 @@* { "ok": true, "result": unknown }* | { "ok": false, "error": { "code": string, "message": string } }*- * Compiled-tool contract:- * module.exports = {- * id: "<tool-id>",- * actions: {- * <name>: (args, ctx) => any | Promise<any>- * }- * }+ * Compiled-tool contract — two accepted shapes:+ * 1. Plain CJS:+ * module.exports = { id: "<tool-id>", actions: { <name>: (args, ctx) => any | Promise<any> } }+ * 2. A `default` property on `module.exports` (esbuild's `__toCommonJS` CJS+ * interop for the typed pipeline's mandated `export default {}` source).+ * Sibling loader applying the same unwrap rule: agent-shared/src/sandbox/sandbox-inprocess.ts.** `ctx` exposes:* - secrets.ref(name) → opaque per-session nonce string. The raw secret@@ -67,7 +66,9 @@ function loadTool(toolId) {// Clear require cache so a re-published bundle is picked up — sandboxes// are per-session so cache reuse is fine within one session.delete require.cache[require.resolve(compiledPath)]- return require(compiledPath)+ const mod = require(compiledPath)+ // Same rule as the in-process pool (agent-shared/src/sandbox/sandbox-inprocess.ts).+ return mod.default ?? mod}function buildContext(nonces) {diff --git a/products/agent_platform/services/agent-sandbox-host/src/dispatch.test.js b/products/agent_platform/services/agent-sandbox-host/src/dispatch.test.jsindex f3373b764a95..e2a21350bd2b 100644--- a/products/agent_platform/services/agent-sandbox-host/src/dispatch.test.js+++ b/products/agent_platform/services/agent-sandbox-host/src/dispatch.test.js@@ -46,6 +46,45 @@ test('dispatch returns the action result for a known tool + action', async () =>assert.deepEqual(out.result, { got: { hi: 'world' } })})+test('dispatch unwraps an esbuild-CJS default export (typed-pipeline compiled.js)', async () => {+ setupToolsDir()+ // This fixture IS the repo's esbuild output: the janitor's typed pipeline+ // mandates `export default {...}` source and compiles with esbuild+ // format:"cjs" (loader:"ts", target:"node20"), which exposes the tool+ // object as `.default` via a __toCommonJS getter on module.exports — not+ // a bare `module.exports = {...}` like the fixtures above.+ writeTool(+ 'typed-echo',+ `var __defProp = Object.defineProperty;+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;+var __getOwnPropNames = Object.getOwnPropertyNames;+var __hasOwnProp = Object.prototype.hasOwnProperty;+var __export = (target, all) => {+ for (var name in all)+ __defProp(target, name, { get: all[name], enumerable: true });+};+var __copyProps = (to, from, except, desc) => {+ if (from && typeof from === "object" || typeof from === "function") {+ for (let key of __getOwnPropNames(from))+ if (!__hasOwnProp.call(to, key) && key !== except)+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });+ }+ return to;+};+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);+var stdin_exports = {};+__export(stdin_exports, {+ default: () => stdin_default+});+module.exports = __toCommonJS(stdin_exports);+var stdin_default = { id: "typed-echo", actions: { default: async (args) => ({ ok: true, echo: args.x }) } };+`+ )+ const { dispatch } = freshRequire()+ const out = await dispatch({ toolId: 'typed-echo', action: 'default', args: { x: 42 } })+ assert.deepEqual(out.result, { ok: true, echo: 42 })+})+test('dispatch surfaces a tool-not-found error code', async () => {setupToolsDir()const { dispatch } = freshRequire()