Skip to content

Commit 56f7b2e

Browse files
committed
fix(sessions): harden lifecycle, ownership, and subagent spawning
1 parent db97a74 commit 56f7b2e

22 files changed

Lines changed: 1122 additions & 87 deletions

‎docs/concepts/session-tool.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ OpenClaw gives agents tools to work across sessions, inspect status, and orchest
1313

1414
| Tool | What it does |
1515
| -------------------- | --------------------------------------------------------------------------- |
16-
| `sessions` | Patch visible session settings and manage the global session-group catalog |
16+
| `sessions` | Patch, reset, or delete visible sessions and manage session groups |
1717
| `sessions_list` | List sessions with optional filters (kind, label, agent, archive, preview) |
1818
| `sessions_search` | Search visible session transcripts and return matching excerpts |
1919
| `sessions_history` | Read the transcript of a specific session |
@@ -58,11 +58,15 @@ Use [`sessions_search`](/concepts/session-search) for exact full-text recall acr
5858

5959
## Managing session settings and groups
6060

61-
The owner-gated `sessions` tool exposes two bounded self-service surfaces:
61+
The owner-gated `sessions` tool exposes bounded self-service surfaces:
6262

63-
- `action: "patch"` changes the current session by default, or another visible session selected by `sessionKey`. It can set the label, sidebar icon, pin/archive state, model, and thinking level. It does not expose reset, delete, or compact actions.
63+
- `action: "patch"` changes the current session by default, or another visible session selected by `sessionKey`. It can set the label, sidebar icon, pin/archive state, model, and thinking level.
64+
- `action: "reset"` resets another visible session selected by `sessionKey`.
65+
- `action: "delete"` first archives and then deletes the exact same generation of another visible session selected by `sessionKey`. By default its transcript is retained as a deleted archive; pass `deleteTranscript: false` to leave the transcript state untouched. Resetting or deleting the session currently running the tool is rejected.
6466
- `group_list`, `group_set`, `group_rename`, and `group_delete` manage the global ordered session-group catalog. `group_set` replaces the ordered name list rather than patching one entry.
6567

68+
Use `sessions_spawn` with `visible: true` to create a persistent dashboard session. This keeps session creation on the controlled spawn path, which enforces the parent's tool policy, sandbox, concurrency limits, and run timeout.
69+
6670
An agent-selected model patch stays reversible until that selection completes a successful run. If the selected model is definitively unusable because of authentication, billing, or model-not-found failure, OpenClaw restores the previous model and writes a visible system note. Transient rate-limit, overload, timeout, network, and server failures do not undo the selection.
6771

6872
## Sessions versus conversations
@@ -120,6 +124,7 @@ Key options:
120124

121125
- `runtime: "subagent"` (default) or `"acp"` for external harness agents.
122126
- `model` and `thinking` overrides for the child session.
127+
- `runTimeoutSeconds` to override the configured child-run timeout; `0` disables it.
123128
- `thread: true` to bind the spawn to a chat thread (Discord, Slack, etc.).
124129
- `sandbox: "require"` to enforce sandboxing on the child.
125130
- `context: "fork"` for native sub-agents when the child needs the current requester transcript; omit it or use `context: "isolated"` for a clean child. `context: "fork"` is only valid with `runtime: "subagent"`. Thread-bound native sub-agents default to `context: "fork"` unless `threadBindings.defaultSpawnContext` says otherwise.

‎docs/tools/subagents.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ session to confirm the effective tool list.
147147

148148
- **Model:** native sub-agents inherit the caller unless you set `agents.defaults.subagents.model` (or per-agent `agents.entries.*.subagents.model`). ACP runtime spawns use the same configured subagent model when present; otherwise the ACP harness keeps its own default. An explicit `sessions_spawn.model` still wins.
149149
- **Thinking:** native sub-agents inherit the caller unless you set `agents.defaults.subagents.thinking` (or per-agent `agents.entries.*.subagents.thinking`). ACP runtime spawns also apply `agents.defaults.models["provider/model"].params.thinking` for the selected model. An explicit `sessions_spawn.thinking` still wins.
150-
- **Run timeout:** OpenClaw uses `agents.defaults.subagents.runTimeoutSeconds` when set; otherwise it falls back to `0` (no timeout). `sessions_spawn` does not accept per-call timeout overrides.
150+
- **Run timeout:** pass `runTimeoutSeconds` to set a timeout for a specific native, ACP, or visible sub-agent run. When omitted, OpenClaw uses `agents.defaults.subagents.runTimeoutSeconds` if configured; otherwise it falls back to `0` (no timeout). An explicit `0` disables the timeout for that run.
151151
- **Process lifetime:** a detached OpenClaw sub-agent has its own run lifecycle. A background task created inside an external CLI backend is different: it shares the parent CLI subprocess and stops if that parent reaches `agents.defaults.timeoutSeconds`.
152152
- **Task delivery:** native sub-agents receive the delegated task in their first visible `[Subagent Task]` message. The sub-agent system prompt carries runtime rules and routing context, not a hidden duplicate of the task.
153153

@@ -212,6 +212,9 @@ Per-agent override: `agents.entries.*.subagents.delegationMode`.
212212
<ParamField path="model" type="string">
213213
Override the sub-agent model. Invalid values are skipped and the sub-agent runs on the default model with a warning in the tool result.
214214
</ParamField>
215+
<ParamField path="runTimeoutSeconds" type="integer">
216+
Override the configured run timeout for this child. Must be a non-negative integer; `0` disables the timeout. Applies to native, ACP, and visible sessions.
217+
</ParamField>
215218
<ParamField path="thinking" type="string">
216219
Override thinking level for the sub-agent run. Not available with `visible: true`.
217220
</ParamField>

‎src/agents/agent-tools.create-openclaw-coding-tools.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,23 @@ describe("createOpenClawCodingTools", () => {
535535
expect(inheritedAllow?.includes("exec")).toBe(false);
536536
});
537537

538+
it("keeps restricted spawn inheritance in the caller-owned runtime snapshot", () => {
539+
const createOpenClawToolsMock = vi.mocked(createOpenClawTools);
540+
createOpenClawToolsMock.mockClear();
541+
const inheritedToolAllowlistRef: string[] = [];
542+
543+
createOpenClawCodingTools({
544+
config: { tools: { allow: ["read", "sessions_spawn"] } },
545+
inheritedToolAllowlistRef,
546+
});
547+
548+
expect(latestCreateOpenClawToolsOptions().inheritedToolAllowlist).toBe(
549+
inheritedToolAllowlistRef,
550+
);
551+
expectListIncludes(inheritedToolAllowlistRef, ["read", "sessions_spawn"]);
552+
expect(inheritedToolAllowlistRef).not.toContain("exec");
553+
});
554+
538555
it("preserves runtime-allowed message through restrictive profiles", () => {
539556
const tools = createOpenClawCodingTools({
540557
config: { tools: { profile: "minimal" } },

‎src/agents/agent-tools.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,8 @@ type OpenClawCodingToolsOptions = {
404404
runtimeToolAllowlist?: string[];
405405
/** True when runtimeToolAllowlist is real parent authority that child sessions inherit. */
406406
inheritRuntimeToolAllowlist?: boolean;
407+
/** Mutable spawn capability snapshot refreshed after late-bound runtime tools are authorized. */
408+
inheritedToolAllowlistRef?: string[];
407409
/** Mutable cron creator cap ref for callers that append final runtime tools later. */
408410
cronCreatorToolAllowlistRef?: CronCreatorToolAllowlistEntry[];
409411
/** If true, the model has native vision capability */
@@ -805,7 +807,7 @@ function createOpenClawCodingToolsInternal(options?: OpenClawCodingToolsOptions)
805807
const inheritedToolDenylist = [...pluginToolDenylist];
806808
// Passed by reference to sessions_spawn and populated after the final policy
807809
// pass so child sessions inherit the actual parent tool surface.
808-
const inheritedToolAllowlist: string[] = [];
810+
const inheritedToolAllowlist = options?.inheritedToolAllowlistRef ?? [];
809811
const toolPolicyInheritanceSources = capabilityProfile.policy.inheritancePolicies;
810812
const shouldInheritEffectiveToolAllowlist =
811813
toolPolicyInheritanceSources.some(hasRestrictiveAllowPolicy);

‎src/agents/embedded-agent-runner/run/attempt-bundle-tools.test.ts‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,15 @@ vi.mock("../../agent-bundle-mcp-tools.js", () => ({
1717
}));
1818

1919
vi.mock("../../runtime-plan/tools.js", () => ({
20-
normalizeAgentRuntimeTools: vi.fn(() => []),
20+
normalizeAgentRuntimeTools: vi.fn(({ tools }: { tools: unknown[] }) => tools),
21+
}));
22+
23+
vi.mock("../../local-model-lean.js", () => ({
24+
filterLocalModelLeanTools: vi.fn(({ tools }: { tools: unknown[] }) => tools),
25+
}));
26+
27+
vi.mock("../../tool-schema-projection.js", () => ({
28+
filterRuntimeCompatibleTools: vi.fn((tools: unknown[]) => ({ tools, diagnostics: [] })),
2129
}));
2230

2331
vi.mock("../effective-tool-policy.js", () => ({
@@ -35,6 +43,74 @@ import { prepareEmbeddedAttemptBundleTools } from "./attempt-bundle-tools.js";
3543
describe("prepareEmbeddedAttemptBundleTools", () => {
3644
beforeEach(() => {
3745
vi.clearAllMocks();
46+
mocks.createBundleLspToolRuntime.mockReset().mockResolvedValue(undefined);
47+
mocks.getOrCreateSessionMcpRuntime.mockReset().mockResolvedValue(undefined);
48+
mocks.materializeBundleMcpToolsForRun.mockReset().mockResolvedValue(undefined);
49+
mocks.applyFinalEffectiveToolPolicy
50+
.mockReset()
51+
.mockImplementation(({ bundledTools }: { bundledTools: unknown[] }) => bundledTools);
52+
});
53+
54+
function createInput(inheritedToolAllowlist: string[], toolsRaw: unknown[]) {
55+
return {
56+
agentDir: "/tmp/agent",
57+
attempt: {
58+
config: {},
59+
model: {},
60+
modelId: "model",
61+
provider: "provider",
62+
runId: "run",
63+
runtimePlan: {},
64+
sessionId: "session",
65+
},
66+
effectiveWorkspace: "/tmp/workspace",
67+
getCurrentAttemptPluginMetadataSnapshot: () => undefined,
68+
getProviderRuntimeHandle: () => undefined,
69+
isRawModelRun: false,
70+
preparedToolBase: {
71+
cronCreatorToolAllowlist: [],
72+
effectiveToolsAllow: undefined,
73+
inheritedToolAllowlist,
74+
localModelLeanPreserveToolNames: [],
75+
runtimeCapabilityProfile: undefined,
76+
toolsEnabled: true,
77+
toolsRaw,
78+
},
79+
sessionAgentId: "main",
80+
} as unknown as Parameters<typeof prepareEmbeddedAttemptBundleTools>[0];
81+
}
82+
83+
it("refreshes spawned-child inheritance after authorized MCP tools materialize", async () => {
84+
const inheritedToolAllowlist = ["sessions_spawn"];
85+
mocks.getOrCreateSessionMcpRuntime.mockResolvedValue({});
86+
mocks.materializeBundleMcpToolsForRun.mockResolvedValue({
87+
tools: [{ name: "server__read" }],
88+
});
89+
90+
await prepareEmbeddedAttemptBundleTools(
91+
createInput(inheritedToolAllowlist, [{ name: "sessions_spawn" }]),
92+
);
93+
94+
expect(inheritedToolAllowlist).toEqual(["sessions_spawn", "server__read"]);
95+
});
96+
97+
it("never adds policy-denied bundled tools to spawned-child inheritance", async () => {
98+
const inheritedToolAllowlist = ["sessions_spawn"];
99+
mocks.getOrCreateSessionMcpRuntime.mockResolvedValue({});
100+
mocks.materializeBundleMcpToolsForRun.mockResolvedValue({
101+
tools: [{ name: "server__read" }, { name: "server__delete" }],
102+
});
103+
mocks.applyFinalEffectiveToolPolicy.mockImplementation(
104+
({ bundledTools }: { bundledTools: Array<{ name: string }> }) =>
105+
bundledTools.filter((tool) => tool.name !== "server__delete"),
106+
);
107+
108+
await prepareEmbeddedAttemptBundleTools(
109+
createInput(inheritedToolAllowlist, [{ name: "sessions_spawn" }]),
110+
);
111+
112+
expect(inheritedToolAllowlist).toEqual(["sessions_spawn", "server__read"]);
113+
expect(inheritedToolAllowlist).not.toContain("server__delete");
38114
});
39115

40116
it("disposes prepared bundle runtimes when later policy setup fails", async () => {

‎src/agents/embedded-agent-runner/run/attempt-bundle-tools.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
} from "../../agent-bundle-mcp-tools.js";
77
import { filterLocalModelLeanTools } from "../../local-model-lean.js";
88
import { normalizeAgentRuntimeTools } from "../../runtime-plan/tools.js";
9+
import { replaceWithEffectiveToolAllowlist } from "../../tool-policy.js";
910
import { filterRuntimeCompatibleTools } from "../../tool-schema-projection.js";
1011
import { logRuntimeToolSchemaQuarantine } from "../../tool-schema-quarantine.js";
1112
import { replaceWithEffectiveCronCreatorToolAllowlist } from "../../tools/cron-tool.js";
@@ -36,6 +37,7 @@ export async function prepareEmbeddedAttemptBundleTools(params: {
3637
const {
3738
cronCreatorToolAllowlist,
3839
effectiveToolsAllow,
40+
inheritedToolAllowlist,
3941
localModelLeanPreserveToolNames,
4042
runtimeCapabilityProfile,
4143
toolsEnabled,
@@ -199,6 +201,12 @@ export async function prepareEmbeddedAttemptBundleTools(params: {
199201
);
200202
}
201203
const schemaProjection = filterRuntimeCompatibleTools(projectedTools);
204+
if (inheritedToolAllowlist?.length) {
205+
// Spawn tools close over this ref before MCP/LSP materialize. Refresh it
206+
// only after final policy and schema projection so children inherit the
207+
// parent's complete authorized surface, never denied bundled tools.
208+
replaceWithEffectiveToolAllowlist(inheritedToolAllowlist, schemaProjection.tools);
209+
}
202210
logRuntimeToolSchemaQuarantine({
203211
diagnostics: schemaProjection.diagnostics,
204212
tools: projectedTools,

‎src/agents/embedded-agent-runner/run/attempt-tool-base-prepare.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ export function prepareEmbeddedAttemptToolBase(params: {
118118
: undefined;
119119
const toolSearchTargetTranscriptProjections: ToolSearchTargetTranscriptProjection[] = [];
120120
const cronCreatorToolAllowlist: CronCreatorToolAllowlistEntry[] = [];
121+
const inheritedToolAllowlist: string[] = [];
121122
const spawnWorkspaceDir =
122123
params.effectiveCwd !== params.effectiveWorkspace
123124
? params.resolvedWorkspace
@@ -303,6 +304,7 @@ export function prepareEmbeddedAttemptToolBase(params: {
303304
enableHeartbeatTool: attempt.enableHeartbeatTool,
304305
forceHeartbeatTool: attempt.forceHeartbeatTool,
305306
runtimeToolAllowlist: effectiveToolsAllow,
307+
inheritedToolAllowlistRef: inheritedToolAllowlist,
306308
cronCreatorToolAllowlistRef: cronCreatorToolAllowlist,
307309
authProfileStore: attempt.authProfileStore,
308310
recordToolPrepStage: params.markCoreToolStage,
@@ -335,6 +337,7 @@ export function prepareEmbeddedAttemptToolBase(params: {
335337
computerContextEpoch,
336338
cronCreatorToolAllowlist,
337339
effectiveToolsAllow,
340+
inheritedToolAllowlist,
338341
localModelLeanEnabled,
339342
localModelLeanPreserveToolNames,
340343
replaySafetyOptions,

‎src/agents/tool-policy.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export function hasRestrictiveAllowPolicy(policy?: { allow?: string[] }): boolea
7171
/** Replaces an allowlist with the normalized names of an effective tool array. */
7272
export function replaceWithEffectiveToolAllowlist(
7373
target: string[],
74-
tools: Array<{ name: string }>,
74+
tools: ReadonlyArray<{ name: string }>,
7575
): void {
7676
target.length = 0;
7777
const seen = new Set<string>();

0 commit comments

Comments
 (0)