Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Build connector SDK into Modal images before sandbox creation (#1277)

Regan Bellfc055480b06b
diff --git a/docs/modal-image.md b/docs/modal-image.md
new file mode 100644
index 000000000..3c788fc79
--- /dev/null
+++ b/docs/modal-image.md
@@ -0,0 +1,48 @@
+# Prebuilt Modal connector image
+
+Build the sandbox image before deploying core to keep package installation and image
+building out of the first user turn. The image contains the same locked Composio SDK
+bundle that core supplies to sandboxes without a baked image. Connector credentials
+are supplied at runtime; none are used during this build.
+
+From the matching source checkout, install dependencies with `npm ci`, configure Modal
+authentication, then run:
+
+```bash
+MODAL_APP_NAME=qm npm run build:modal-image
+```
+
+The command eagerly builds the image on Modal and prints `MODAL_IMAGE=im-...` only
+after the bundle's checksum and import checks pass. Save that exact image ID in the
+core deployment's `MODAL_IMAGE` setting. Use the same Modal workspace and environment
+for building and running; `MODAL_ENVIRONMENT` selects the SDK environment. The build
+does not change running sandboxes or deploy core.
+
+With no `MODAL_IMAGE` set during the build, the image starts from QM's pinned Node
+base and installs its usual shell, Python, Git, curl, and archive utilities. To extend
+an existing custom image, set `MODAL_IMAGE` to its registry reference (prefer an
+immutable digest) or an existing Modal image ID. Custom bases must already contain
+Node, npm, and QM's baseline utilities; this preserves the existing custom-image
+contract. Building again from the same inputs uses Modal's layer cache.
+
+The connector build uses `deploy/connector-sdk/package-lock.json` and the shared
+bundle builder. The resulting SDK, checksum, and license notices live in
+`/opt/qm/composio`, outside `/root`. Restoring a home snapshot therefore cannot hide
+or replace image-installed dependencies. Core validates the baked artifact against
+its own bundle and exposes the matching copy through the usual home launcher path;
+an older image can use the runtime bundle fallback.
+
+Rebuild the image when updating the SDK lockfile or builder, and retain the previous
+image ID with the previous core release for rollback. Existing running sandboxes
+keep their current image until normal replacement. Do not delete image IDs still
+used by running deployments or retained rollback releases.
+
+For an isolated provider smoke test after the build:
+
+```bash
+MODAL_APP_NAME=qm-image-smoke MODAL_IMAGE=im-... node scripts/modal-live-smoke.mjs
+```
+
+This creates temporary sandboxes and terminates them afterward. It does not switch
+production scopes. Sprites and Modal deployments without a baked image continue to
+use the shared runtime bundle installer.
diff --git a/docs/sandbox-preservation.md b/docs/sandbox-preservation.md
index 903785ea0..f018ad2ab 100644
--- a/docs/sandbox-preservation.md
+++ b/docs/sandbox-preservation.md
@@ -1,5 +1,8 @@
# Sandbox recovery
+See [prebuilt Modal images](modal-image.md) to prepare system dependencies and the
+connector SDK before creating user sandboxes.
+
The agent runs in core. Sandbox home state is working state with a provider-specific recovery window. Publish code to git and deliverables to Files when they must remain durable and accessible independently of compute.
`MODAL_NATIVE_SNAPSHOTS_ENABLED` defaults to false. First deploy this reader-compatible release with native capture disabled; keep portable checkpointing until every active core and the retained rollback release can read native checkpoints. Enable the flag only in a later deployment after that condition holds. Once a scope has a native checkpoint, disabling the flag continues its native capture and recovery; it does not revert that scope to stale portable state. After activation, rolling back to releases without the native reader is unsupported and can lose working state.
diff --git a/package.json b/package.json
index 4dbecdbb3..af3f5e9d3 100644
--- a/package.json
+++ b/package.json
@@ -40,6 +40,7 @@
"smoke:service-cred": "node scripts/service-credential-livetest.ts",
"smoke:aws-sandbox": "node scripts/aws-sandbox-smoke.ts",
"smoke:local-sandbox": "node scripts/local-sandbox-smoke.ts",
+ "build:modal-image": "node scripts/modal-build-image.ts",
"build:aws-image": "node scripts/aws-build-sandbox-image.ts",
"sandbox:local:build": "bash scripts/local-sandbox-build.sh",
"sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"",
diff --git a/scripts/modal-build-image.ts b/scripts/modal-build-image.ts
new file mode 100644
index 000000000..cf0deaf35
--- /dev/null
+++ b/scripts/modal-build-image.ts
@@ -0,0 +1,24 @@
+import { readFile } from "node:fs/promises";
+import { ModalClient } from "modal";
+import { resolveModalImage } from "../src/sandbox/modal-image.ts";
+
+const client = new ModalClient();
+try {
+ const app = await client.apps.fromName(process.env.MODAL_APP_NAME ?? "qm", { createIfMissing: true });
+ const files = await Promise.all(
+ ["package.json", "package-lock.json", "build.mjs"].map(async (name) => {
+ const data = await readFile(new URL(`../deploy/connector-sdk/${name}`, import.meta.url));
+ return `printf '%s' '${data.toString("base64")}' | base64 -d > /tmp/qm-connector-build/${name}`;
+ }),
+ );
+ const base = await resolveModalImage(client, process.env.MODAL_IMAGE);
+ const image = await base
+ .dockerfileCommands([
+ `RUN mkdir -p /tmp/qm-connector-build && ${files.join(" && ")} && cd /tmp/qm-connector-build && npm ci --ignore-scripts --no-audit --no-fund && node build.mjs /opt/qm/composio && rm -rf /tmp/qm-connector-build /root/.npm`,
+ `RUN cd /opt/qm/composio && node -e 'if (typeof require("./sdk.cjs").Composio !== "function") process.exit(1)' && sha256sum sdk.cjs | cut -d ' ' -f1 | cmp - sha256`,
+ ])
+ .build(app);
+ console.log(`MODAL_IMAGE=${image.imageId}`);
+} finally {
+ client.close();
+}
diff --git a/scripts/modal-live-smoke.mjs b/scripts/modal-live-smoke.mjs
index 536001bd8..8f936a155 100644
--- a/scripts/modal-live-smoke.mjs
+++ b/scripts/modal-live-smoke.mjs
@@ -1,4 +1,5 @@
import { ModalClient, AlreadyExistsError } from "modal";
+import { resolveModalImage } from "../src/sandbox/modal-image.ts";
const log = (step, ok, detail = "") => console.log(`${ok ? "PASS" : "FAIL"} ${step}${detail ? " — " + detail : ""}`);
const info = (step, detail) => console.log(`INFO ${step} — ${detail}`);
@@ -9,9 +10,6 @@ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
const APP = process.env.MODAL_APP_NAME ?? "qm-smoke";
const IMAGE = process.env.MODAL_IMAGE;
-const DEFAULT_IMAGE = "node:24-slim@sha256:6f7b03f7c2c8e2e784dcf9295400527b9b1270fd37b7e9a7285cf83b6951452d";
-const DEFAULT_IMAGE_SETUP =
- "RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git jq tar xz-utils unzip python3 python3-venv openssh-client && rm -rf /var/lib/apt/lists/*";
const NAME = `qm-smoke-${Date.now().toString(36)}`;
info(
@@ -26,9 +24,7 @@ let idler;
try {
const app = await modal.apps.fromName(APP, { createIfMissing: true });
log("auth + app lookup (through any configured proxy)", true, `app=${APP} (${el()})`);
- const image = IMAGE
- ? modal.images.fromRegistry(IMAGE)
- : modal.images.fromRegistry(DEFAULT_IMAGE).dockerfileCommands([DEFAULT_IMAGE_SETUP]);
+ const image = await resolveModalImage(modal, IMAGE);
const ct = Date.now();
sb = await modal.sandboxes.create(app, image, { name: NAME, timeoutMs: 30 * 60_000 });
diff --git a/src/sandbox/modal-client.ts b/src/sandbox/modal-client.ts
index 0f5ea4a00..a617257b4 100644
--- a/src/sandbox/modal-client.ts
+++ b/src/sandbox/modal-client.ts
@@ -1,3 +1,5 @@
+import { resolveModalImage } from "./modal-image.ts";
+
export interface ModalCommandResult {
stdout: string;
stderr: string;
@@ -43,10 +45,6 @@ export interface ModalClient {
terminate(sandboxId: string): Promise<void>;
}
-const MODAL_DEFAULT_IMAGE = "node:24-slim@sha256:6f7b03f7c2c8e2e784dcf9295400527b9b1270fd37b7e9a7285cf83b6951452d";
-const MODAL_DEFAULT_IMAGE_SETUP =
- "RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git jq tar xz-utils unzip python3 python3-venv openssh-client && rm -rf /var/lib/apt/lists/*";
-
export interface SdkModalClientOptions {
tokenId: string;
tokenSecret: string;
@@ -128,9 +126,7 @@ export function createSdkModalClient(opts: SdkModalClientOptions): ModalClient {
...(opts.environment ? { environment: opts.environment } : {}),
});
const app = await client.apps.fromName(opts.appName, { createIfMissing: true });
- const image = opts.image
- ? client.images.fromRegistry(opts.image)
- : client.images.fromRegistry(MODAL_DEFAULT_IMAGE).dockerfileCommands([MODAL_DEFAULT_IMAGE_SETUP]);
+ const image = await resolveModalImage(client, opts.image);
return { client, app, image };
};
const loadCtx = (): Promise<{ client: SdkClient; app: SdkApp; image: SdkImage }> =>
diff --git a/src/sandbox/modal-image.ts b/src/sandbox/modal-image.ts
new file mode 100644
index 000000000..401ff1130
--- /dev/null
+++ b/src/sandbox/modal-image.ts
@@ -0,0 +1,12 @@
+import type { ModalClient } from "modal";
+
+export const MODAL_DEFAULT_IMAGE =
+ "node:24-slim@sha256:6f7b03f7c2c8e2e784dcf9295400527b9b1270fd37b7e9a7285cf83b6951452d";
+export const MODAL_DEFAULT_IMAGE_SETUP =
+ "RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git jq tar xz-utils unzip python3 python3-venv openssh-client && rm -rf /var/lib/apt/lists/*";
+
+export async function resolveModalImage(client: ModalClient, reference?: string) {
+ if (reference?.startsWith("im-")) return client.images.fromId(reference);
+ if (reference) return client.images.fromRegistry(reference);
+ return client.images.fromRegistry(MODAL_DEFAULT_IMAGE).dockerfileCommands([MODAL_DEFAULT_IMAGE_SETUP]);
+}
diff --git a/test/modal-image.test.ts b/test/modal-image.test.ts
new file mode 100644
index 000000000..6330ed5ac
--- /dev/null
+++ b/test/modal-image.test.ts
@@ -0,0 +1,45 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { ModalClient } from "modal";
+import { MODAL_DEFAULT_IMAGE, MODAL_DEFAULT_IMAGE_SETUP, resolveModalImage } from "../src/sandbox/modal-image.ts";
+
+function client() {
+ const calls: unknown[][] = [];
+ const image = {
+ dockerfileCommands(commands: string[]) {
+ calls.push(["commands", commands]);
+ return image;
+ },
+ };
+ const sdk = {
+ images: {
+ fromRegistry(reference: string) {
+ calls.push(["registry", reference]);
+ return image;
+ },
+ async fromId(reference: string) {
+ calls.push(["id", reference]);
+ return image;
+ },
+ },
+ } as unknown as ModalClient;
+ return { calls, image, sdk };
+}
+
+test("Modal resolves a prebuilt image ID without creating registry layers", async () => {
+ const { calls, image, sdk } = client();
+ assert.equal(await resolveModalImage(sdk, "im-connector"), image);
+ assert.deepEqual(calls, [["id", "im-connector"]]);
+});
+
+test("Modal preserves custom registry images and the default baseline", async () => {
+ const { calls, sdk } = client();
+ await resolveModalImage(sdk, "registry.example/sandbox@sha256:abc");
+ assert.deepEqual(calls, [["registry", "registry.example/sandbox@sha256:abc"]]);
+ calls.length = 0;
+ await resolveModalImage(sdk);
+ assert.deepEqual(calls, [
+ ["registry", MODAL_DEFAULT_IMAGE],
+ ["commands", [MODAL_DEFAULT_IMAGE_SETUP]],
+ ]);
+});