Skip to content

Commit 165e68c

Browse files
committed
feat: add managed sandbox lifecycle
1 parent 79d2e56 commit 165e68c

69 files changed

Lines changed: 7907 additions & 715 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
729181bf726ea51bebfa51c760eff8d5016933c21815e47197b5d05db8d549d5 plugin-sdk-api-baseline.json
2-
d8add92c9c5445e8bdd8a8361cdd5a42e1ab5baa45cd16ea640152d6f577f1bf plugin-sdk-api-baseline.jsonl
1+
58fdfc4b2583ab4ca803e9accf3ceb7eef8c8b9c07da1f3e5bff4cab69a4a03b plugin-sdk-api-baseline.json
2+
43afb74acc4f33953df988f04c4a830e1bdec46b09522bc77395ae105cd94e02 plugin-sdk-api-baseline.jsonl

‎docs/cli/sandbox.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,30 @@ openclaw sandbox recreate --agent family
150150
openclaw sandbox recreate --agent alfred
151151
```
152152

153+
### Managed ephemeral session sandboxes
154+
155+
For long-running task or thread owners, combine session scope with lifecycle cleanup:
156+
157+
```jsonc
158+
{
159+
"agents": {
160+
"defaults": {
161+
"sandbox": {
162+
"mode": "all",
163+
"scope": "session",
164+
"prune": {
165+
"idleHours": 12,
166+
"maxAgeDays": 3,
167+
"onSessionEnd": true,
168+
},
169+
},
170+
},
171+
},
172+
}
173+
```
174+
175+
OpenClaw reuses the same sandbox runtime for the same session/thread key while that owner is active. When the owning session is reset, deleted, or rolled over by idle/daily reset policy, OpenClaw removes the matching runtime, browser runtime, registry entries, and non-shared sandbox workspace. Idle and max-age prune remain the crash-recovery path for owners that never reach a clean lifecycle end, and remove stale session-scope workspaces after the runtime cleanup succeeds.
176+
153177
## Why this is needed
154178

155179
When you update sandbox configuration:
@@ -193,6 +217,7 @@ Sandbox settings live in `~/.openclaw/openclaw.json` under `agents.defaults.sand
193217
"prune": {
194218
"idleHours": 24, // Auto-prune after 24h idle
195219
"maxAgeDays": 7, // Auto-prune after 7 days
220+
"onSessionEnd": false, // Remove session-scoped resources on reset/delete/rollover
196221
},
197222
},
198223
},

‎docs/gateway/config-agents.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,7 @@ Optional sandboxing for the embedded agent. See [Sandboxing](/gateway/sandboxing
861861
prune: {
862862
idleHours: 24,
863863
maxAgeDays: 7,
864+
onSessionEnd: false,
864865
},
865866
},
866867
},
@@ -929,6 +930,12 @@ When `backend: "openshell"` is selected, runtime-specific settings move to
929930
- `ro`: sandbox workspace at `/workspace`, agent workspace mounted read-only at `/agent`
930931
- `rw`: agent workspace mounted read/write at `/workspace`
931932

933+
**Lifecycle cleanup:**
934+
935+
- `prune.idleHours`: remove idle sandbox runtimes after this many hours (`0` disables idle pruning)
936+
- `prune.maxAgeDays`: remove sandbox runtimes older than this many days (`0` disables age pruning)
937+
- `prune.onSessionEnd`: opt-in cleanup for `scope: "session"`; removes matching runtimes, browser runtimes, registry entries, and non-shared sandbox workspaces when the owning session is reset, deleted, or rolled over by idle/daily reset policy
938+
932939
**Scope:**
933940

934941
- `session`: per-session container + workspace

‎docs/gateway/sandboxing.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,37 @@ Use `backend: "ssh"` when you want OpenClaw to sandbox `exec`, file tools, and m
173173
</Accordion>
174174
</AccordionGroup>
175175

176+
### Managed ephemeral session lifecycle
177+
178+
Use `scope: "session"` when a task, thread, or spawned child session needs deterministic sandbox reuse while it is active. Add `prune.onSessionEnd: true` when that owner should be ephemeral:
179+
180+
```json5
181+
{
182+
agents: {
183+
defaults: {
184+
sandbox: {
185+
mode: "all",
186+
scope: "session",
187+
prune: {
188+
idleHours: 12,
189+
maxAgeDays: 3,
190+
onSessionEnd: true,
191+
},
192+
},
193+
},
194+
},
195+
}
196+
```
197+
198+
With this opt-in lifecycle, OpenClaw:
199+
200+
- creates and reuses one sandbox per session/thread key
201+
- removes the matching runtime, browser runtime, registry entries, and non-shared sandbox workspace when the owning session is reset, deleted, or rolled over by idle/daily reset policy
202+
- uses idle/max-age prune as crash recovery for owners that stop without a clean lifecycle end; after a stale session-scope runtime is removed, prune also removes that scope's sandbox workspace
203+
- still lets operators force a rebuild with `openclaw sandbox recreate --session <key>`
204+
205+
This does not enable sandboxing globally, does not affect `scope: "agent"` or `scope: "shared"`, and does not tear down a still-active owner after every turn.
206+
176207
### OpenShell backend
177208

178209
Use `backend: "openshell"` when you want OpenClaw to sandbox tools in an OpenShell-managed remote environment. For the full setup guide, configuration reference, and workspace mode comparison, see the dedicated [OpenShell page](/gateway/openshell).

‎extensions/codex/src/app-server/run-attempt.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,7 @@ export async function runCodexAppServerAttempt(
484484
const sandbox = await resolveSandboxContext({
485485
config: params.config,
486486
sessionKey: sandboxSessionKey,
487+
lifecycleOwnerSessionId: params.sessionId,
487488
workspaceDir: resolvedWorkspace,
488489
});
489490
preDynamicStartupStages.mark("sandbox");

‎extensions/codex/src/app-server/side-question.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,7 @@ async function createCodexSideToolBridge(input: {
678678
const sandbox = await resolveSandboxContext({
679679
config: input.params.cfg,
680680
sessionKey: sandboxSessionKey,
681+
lifecycleOwnerSessionId: input.params.sessionId,
681682
workspaceDir: input.cwd,
682683
});
683684
const allTools = createOpenClawCodingTools({

‎extensions/codex/src/conversation-binding.test.ts‎

Lines changed: 75 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,56 @@ describe("codex conversation binding", () => {
240240
);
241241
});
242242

243+
it("passes the current session owner when resolving bind thread sandbox policy", async () => {
244+
codexRequirementsTomlMock.mockReturnValue(
245+
[
246+
'allowed_sandbox_modes = ["read-only", "workspace-write"]',
247+
'allowed_approval_policies = ["never", "on-request"]',
248+
'allowed_approvals_reviewers = ["user"]',
249+
].join("\n"),
250+
);
251+
resolveSandboxContextMock.mockResolvedValue({ enabled: true });
252+
const sessionFile = path.join(tempDir, "session.jsonl");
253+
const storePath = path.join(tempDir, "sessions.json");
254+
const sessionKey = "agent:main:session-1";
255+
const config = {
256+
session: { store: storePath },
257+
tools: {
258+
exec: {
259+
security: "full",
260+
ask: "on-miss",
261+
},
262+
},
263+
};
264+
await upsertSessionEntry({
265+
storePath,
266+
sessionKey,
267+
entry: {
268+
sessionId: "owner-session-1",
269+
updatedAt: Date.now(),
270+
},
271+
});
272+
273+
await expect(
274+
startCodexConversationThread({
275+
config: config as never,
276+
sessionFile,
277+
workspaceDir: tempDir,
278+
sessionKey,
279+
}),
280+
).rejects.toThrow(
281+
"OpenClaw native Codex conversation binding cannot route interactive approvals yet",
282+
);
283+
284+
expect(resolveSandboxContextMock).toHaveBeenCalledWith({
285+
config,
286+
sessionKey,
287+
workspaceDir: tempDir,
288+
lifecycleOwnerSessionId: "owner-session-1",
289+
});
290+
expect(sharedClientMocks.getSharedCodexAppServerClient).not.toHaveBeenCalled();
291+
});
292+
243293
it("selects Codex network-proxy permissions through app-server bind thread config", async () => {
244294
const sessionFile = path.join(tempDir, "session.jsonl");
245295
const requests: Array<{ method: string; params: Record<string, unknown> }> = [];
@@ -1556,6 +1606,25 @@ describe("codex conversation binding", () => {
15561606
);
15571607
resolveSandboxContextMock.mockResolvedValue({ enabled: true });
15581608
const sessionFile = path.join(tempDir, "session.jsonl");
1609+
const storePath = path.join(tempDir, "sessions.json");
1610+
const sessionKey = "agent:main:session-1";
1611+
const config = {
1612+
session: { store: storePath },
1613+
tools: {
1614+
exec: {
1615+
security: "full",
1616+
ask: "on-miss",
1617+
},
1618+
},
1619+
};
1620+
await upsertSessionEntry({
1621+
storePath,
1622+
sessionKey,
1623+
entry: {
1624+
sessionId: "owner-session-1",
1625+
updatedAt: Date.now(),
1626+
},
1627+
});
15591628
await fs.writeFile(
15601629
`${sessionFile}.codex-app-server.json`,
15611630
JSON.stringify({
@@ -1603,11 +1672,11 @@ describe("codex conversation binding", () => {
16031672
channel: "telegram",
16041673
isGroup: false,
16051674
commandAuthorized: true,
1606-
sessionKey: "agent:main:session-1",
1675+
sessionKey,
16071676
},
16081677
{
16091678
channelId: "telegram",
1610-
sessionKey: "agent:main:session-1",
1679+
sessionKey,
16111680
pluginBinding: {
16121681
bindingId: "binding-1",
16131682
pluginId: "codex",
@@ -1626,14 +1695,7 @@ describe("codex conversation binding", () => {
16261695
},
16271696
{
16281697
timeoutMs: 50,
1629-
config: {
1630-
tools: {
1631-
exec: {
1632-
security: "full",
1633-
ask: "on-miss",
1634-
},
1635-
},
1636-
} as never,
1698+
config: config as never,
16371699
},
16381700
);
16391701

@@ -1645,16 +1707,10 @@ describe("codex conversation binding", () => {
16451707
"legacy full exec security with ask requires Codex app-server danger-full-access",
16461708
);
16471709
expect(resolveSandboxContextMock).toHaveBeenCalledWith({
1648-
config: {
1649-
tools: {
1650-
exec: {
1651-
security: "full",
1652-
ask: "on-miss",
1653-
},
1654-
},
1655-
},
1656-
sessionKey: "agent:main:session-1",
1710+
config,
1711+
sessionKey,
16571712
workspaceDir: tempDir,
1713+
lifecycleOwnerSessionId: "owner-session-1",
16581714
});
16591715
expect(turnStartParams).toEqual([]);
16601716
});

‎extensions/codex/src/conversation-binding.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,18 @@ async function resolveConversationAppServerRuntime(params: {
141141
agentId: params.agentId,
142142
sessionKey: params.sessionKey,
143143
});
144+
const lifecycleOwnerSessionId = readSessionLifecycleOwnerSessionId({
145+
config: params.config,
146+
sessionKey: params.sessionKey,
147+
agentId: params.agentId,
148+
});
144149
const sandboxForPolicy =
145150
execPolicy.touched && execPolicy.security === "full" && execPolicy.ask !== "off"
146151
? await resolveSandboxContext({
147152
config: params.config,
148153
sessionKey: params.sessionKey,
149154
workspaceDir: params.workspaceDir,
155+
lifecycleOwnerSessionId,
150156
})
151157
: undefined;
152158
const runtime = resolveCodexAppServerRuntimeOptions({
@@ -895,6 +901,29 @@ function readSessionExecOverrides(params: {
895901
};
896902
}
897903

904+
function readSessionLifecycleOwnerSessionId(params: {
905+
config?: CodexConversationConfig;
906+
agentId?: string;
907+
sessionKey?: string;
908+
}): string | undefined {
909+
const sessionKey = params.sessionKey?.trim();
910+
if (!params.config || !sessionKey) {
911+
return undefined;
912+
}
913+
const agentId = parseAgentIdFromSessionKey(sessionKey) ?? params.agentId;
914+
try {
915+
const storePath = resolveStorePath(params.config.session?.store, { agentId });
916+
const sessionId = getSessionEntry({
917+
storePath,
918+
sessionKey,
919+
readConsistency: "latest",
920+
})?.sessionId?.trim();
921+
return sessionId || undefined;
922+
} catch {
923+
return undefined;
924+
}
925+
}
926+
898927
function canReadSessionExecOverrides(params: {
899928
config: ResolvedCodexConversationConfig;
900929
agentId?: string;

0 commit comments

Comments
 (0)