Skip to content

Commit 8d7b492

Browse files
committed
refactor(sandbox): canonicalize backend ownership
1 parent adc6084 commit 8d7b492

5 files changed

Lines changed: 73 additions & 69 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -965,7 +965,7 @@ extensions/openrouter/stream.ts 8
965965
extensions/openrouter/usage.ts 2
966966
extensions/openrouter/video-generation-provider.ts 1
967967
extensions/openrouter/video-model-catalog.ts 1
968-
extensions/openshell/src/backend.ts 3
968+
extensions/openshell/src/backend.ts 2
969969
extensions/openshell/src/config.ts 1
970970
extensions/openshell/src/fs-bridge.ts 2
971971
extensions/parallel/src/parallel-free-web-search-provider.runtime.ts 1

‎extensions/codex/src/app-server/sandbox-exec-server/processes.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
*/
55
import { embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
66
import { coerceErrorMessage } from "openclaw/plugin-sdk/error-runtime";
7-
import { sanitizeEnvVars } from "openclaw/plugin-sdk/sandbox";
7+
import { buildRemoteCommand, sanitizeEnvVars } from "openclaw/plugin-sdk/sandbox";
88
import type { WebSocket } from "ws";
99
import type { JsonObject, JsonValue } from "../protocol.js";
1010
import { requireObject, requireString, requireStringArray } from "./json-rpc.js";
@@ -98,7 +98,7 @@ async function runProcess(
9898
throwIfProcessStartCancelled(managed);
9999
const remoteExec = prepareSandboxChildExec(backend, params.env);
100100
const execSpec = await backend.buildExecSpec({
101-
command: shellCommandFromArgv(params.argv),
101+
command: buildRemoteCommand(params.argv),
102102
workdir: params.cwd,
103103
env: remoteExec.env,
104104
// This bridge currently owns only pipe-backed child processes. Asking the
@@ -338,14 +338,6 @@ function hasChunksAtOrAfter(managed: ManagedProcess, afterSeq: number): boolean
338338
return managed.chunks.some((chunk) => chunk.seq > afterSeq);
339339
}
340340

341-
function shellCommandFromArgv(argv: string[]): string {
342-
return argv.map(shellEscape).join(" ");
343-
}
344-
345-
function shellEscape(value: string): string {
346-
return `'${value.replaceAll("'", `'"'"'`)}'`;
347-
}
348-
349341
function requireProcess(processes: Map<string, ManagedProcess>, processId: string): ManagedProcess {
350342
const managed = processes.get(processId);
351343
if (!managed) {

‎extensions/openshell/src/backend.ts‎

Lines changed: 11 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -276,60 +276,12 @@ async function createOpenShellSandboxBackend(params: {
276276
remoteWorkspaceDir: params.pluginConfig.remoteWorkspaceDir,
277277
remoteAgentWorkspaceDir: params.pluginConfig.remoteAgentWorkspaceDir,
278278
});
279-
280-
return {
281-
id: "openshell",
282-
runtimeId: sandboxName,
283-
runtimeLabel: sandboxName,
284-
workdir: params.pluginConfig.remoteWorkspaceDir,
285-
env: params.createParams.cfg.docker.env,
286-
mode: params.pluginConfig.mode,
287-
configLabel: params.pluginConfig.from,
288-
configLabelKind: "Source",
289-
workdirValidation: "backend",
290-
validateWorkdir: async (workdir) => await impl.validateWorkdir(workdir),
291-
discardPreparedWorkdir: (workdir) => impl.discardPreparedWorkdir(workdir),
292-
workdirRoots: [
293-
params.pluginConfig.remoteWorkspaceDir,
294-
params.pluginConfig.remoteAgentWorkspaceDir,
295-
],
296-
buildExecSpec: async ({ command, workdir, env, usePty }) => {
297-
const pending = await impl.prepareExec({ command, workdir, env, usePty });
298-
return {
299-
argv: pending.argv,
300-
env: buildOpenShellSshExecEnv(),
301-
stdinMode: "pipe-open",
302-
finalizeToken: pending.token,
303-
};
304-
},
305-
finalizeExec: async ({ token }) => {
306-
await impl.finalizeExec(token as PendingExec | undefined);
307-
},
308-
runShellCommand: async (command) => await impl.runRemoteShellScript(command),
309-
createFsBridge: ({ sandbox }) =>
310-
params.pluginConfig.mode === "remote"
311-
? createRemoteShellSandboxFsBridge({
312-
sandbox,
313-
runtime: impl.asHandle(),
314-
})
315-
: createOpenShellFsBridge({
316-
sandbox,
317-
backend: impl.asHandle(),
318-
}),
319-
remoteWorkspaceDir: params.pluginConfig.remoteWorkspaceDir,
320-
remoteAgentWorkspaceDir: params.pluginConfig.remoteAgentWorkspaceDir,
321-
runRemoteShellScript: async (command) => await impl.runRemoteShellScript(command),
322-
mkdirpRemotePath: async (remotePath, signal) => await impl.mkdirpRemotePath(remotePath, signal),
323-
removeRemotePath: async (remotePath, removeParams) =>
324-
await impl.removeRemotePath(remotePath, removeParams),
325-
renameRemotePath: async (fromRemotePath, toRemotePath, signal) =>
326-
await impl.renameRemotePath(fromRemotePath, toRemotePath, signal),
327-
syncLocalPathToRemote: async (localPath, remotePath) =>
328-
await impl.syncLocalPathToRemote(localPath, remotePath),
329-
};
279+
return impl.asHandle();
330280
}
331281

332282
class OpenShellSandboxBackendImpl {
283+
// Filesystem bridges must retain the same lifecycle owner returned by the factory.
284+
private handle: OpenShellSandboxBackend | null = null;
333285
private ensurePromise: Promise<void> | null = null;
334286
private preparedRemoteWorkspaceForNextExec: {
335287
workdir: string;
@@ -348,7 +300,10 @@ class OpenShellSandboxBackendImpl {
348300
) {}
349301

350302
asHandle(): OpenShellSandboxBackend {
351-
return {
303+
if (this.handle) {
304+
return this.handle;
305+
}
306+
const handle: OpenShellSandboxBackend = {
352307
id: "openshell",
353308
runtimeId: this.params.execContext.sandboxName,
354309
runtimeLabel: this.params.execContext.sandboxName,
@@ -380,11 +335,11 @@ class OpenShellSandboxBackendImpl {
380335
this.params.execContext.config.mode === "remote"
381336
? createRemoteShellSandboxFsBridge({
382337
sandbox,
383-
runtime: this.asHandle(),
338+
runtime: handle,
384339
})
385340
: createOpenShellFsBridge({
386341
sandbox,
387-
backend: this.asHandle(),
342+
backend: handle,
388343
}),
389344
runRemoteShellScript: async (command) => await this.runRemoteShellScript(command),
390345
mkdirpRemotePath: async (remotePath, signal) =>
@@ -396,6 +351,8 @@ class OpenShellSandboxBackendImpl {
396351
syncLocalPathToRemote: async (localPath, remotePath) =>
397352
await this.syncLocalPathToRemote(localPath, remotePath),
398353
};
354+
this.handle = handle;
355+
return handle;
399356
}
400357

401358
async prepareExec(params: {

‎extensions/openshell/src/cli.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import type { ResolvedOpenShellPluginConfig } from "./config.js";
99

1010
export {
11+
buildRemoteCommand,
1112
buildRemoteWorkdirValidationCommand,
1213
buildValidatedExecRemoteCommand,
1314
} from "openclaw/plugin-sdk/sandbox";
@@ -32,10 +33,6 @@ function buildOpenShellBaseArgv(config: ResolvedOpenShellPluginConfig): string[]
3233
return argv;
3334
}
3435

35-
export function buildRemoteCommand(argv: string[]): string {
36-
return argv.map((entry) => shellEscape(entry)).join(" ");
37-
}
38-
3936
function applyGatewayEndpointToSshConfig(params: {
4037
configText: string;
4138
gatewayEndpoint?: string;

‎extensions/openshell/src/openshell-core.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,64 @@ describe("openshell fs bridges", () => {
869869
afterAll(uninstallOpenShellBackendMocks);
870870
beforeEach(resetOpenShellBackendMocks);
871871

872+
it.each(["remote", "mirror"] as const)(
873+
"keeps the factory backend as the canonical owner of the %s filesystem bridge",
874+
async (mode) => {
875+
await using workspace = await createOpenShellTestWorkspace("fs-owner");
876+
const workspaceDir = workspace.dir;
877+
sandboxMocks.remoteRoot = workspaceDir;
878+
sandboxMocks.remoteAgentRoot = workspaceDir;
879+
cliMocks.runOpenShellCli.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
880+
const factory = createOpenShellSandboxBackendFactory({
881+
pluginConfig: resolveOpenShellPluginConfig({ command: "openshell", mode }),
882+
});
883+
const backend = (await factory({
884+
sessionKey: "agent:main:turn",
885+
scopeKey: "agent:main",
886+
workspaceDir,
887+
agentWorkspaceDir: workspaceDir,
888+
cfg: createOpenShellBackendSandboxConfig(),
889+
})) as OpenShellSandboxBackend;
890+
const sandbox = createSandboxTestContext({
891+
overrides: {
892+
backendId: "openshell",
893+
workspaceDir,
894+
agentWorkspaceDir: workspaceDir,
895+
containerWorkdir: "/sandbox",
896+
},
897+
});
898+
const bridge = backend.createFsBridge?.({ sandbox });
899+
if (!bridge) {
900+
throw new Error("Expected an OpenShell filesystem bridge");
901+
}
902+
expect(bridge.resolvePath({ filePath: "owner.txt" })).toEqual({
903+
...(mode === "mirror" ? { hostPath: path.join(workspaceDir, "owner.txt") } : {}),
904+
relativePath: "owner.txt",
905+
containerPath: "/sandbox/owner.txt",
906+
});
907+
908+
if (mode === "remote") {
909+
const runRemoteShellScript = vi.spyOn(backend, "runRemoteShellScript").mockResolvedValue({
910+
stdout: Buffer.from("0\n"),
911+
stderr: Buffer.alloc(0),
912+
code: 0,
913+
});
914+
await expect(bridge.stat({ filePath: "owner.txt" })).resolves.toBeNull();
915+
expect(runRemoteShellScript).toHaveBeenCalledOnce();
916+
return;
917+
}
918+
919+
const syncLocalPathToRemote = vi
920+
.spyOn(backend, "syncLocalPathToRemote")
921+
.mockResolvedValue(undefined);
922+
await bridge.writeFile({ filePath: "owner.txt", data: "owner" });
923+
expect(syncLocalPathToRemote).toHaveBeenCalledWith(
924+
path.join(workspaceDir, "owner.txt"),
925+
"/sandbox/owner.txt",
926+
);
927+
},
928+
);
929+
872930
it.runIf(process.platform !== "win32")(
873931
"rejects remote-only symlink parents in pinned mirror mutations",
874932
async () => {

0 commit comments

Comments
 (0)