Skip to content

Commit b99b1d3

Browse files
committed
fix(sessions): inherit trusted parent repositories for worktree spawns
Preserve explicit source selection and cross-agent defaults. Revalidate the exact parent session and managed worktree at creation commit boundaries, including deferred worktree intent. Align visible-spawn schema guidance and documentation with accepted inert defaults. Fixes #132398.
1 parent 837d3c9 commit b99b1d3

6 files changed

Lines changed: 301 additions & 30 deletions

File tree

‎docs/tools/subagents.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ In `prefer` mode, hidden sub-agents are for internal legwork that the user does
215215
Spawn under another configured agent id when allowed by `subagents.allowAgents`.
216216
</ParamField>
217217
<ParamField path="cwd" type="string">
218-
Optional task working directory for the child run. Native sub-agents still load bootstrap files from the target agent workspace; `cwd` only changes where runtime tools and CLI harnesses do the delegated work. For visible sessions, paths outside configured agent workspaces require `operator.admin`; omit `cwd` to use the target agent workspace.
218+
Optional task working directory for the child run. Native sub-agents still load bootstrap files from the target agent workspace; `cwd` only changes where runtime tools and CLI harnesses do the delegated work. For visible sessions, paths outside configured agent workspaces require `operator.admin`. With `worktree: true`, omitting `cwd` inherits the same-agent parent's managed repository when available; otherwise the target agent workspace is used.
219219
</ParamField>
220220
<ParamField path="runtime" type='"subagent" | "acp"' default="subagent">
221221
`acp` is only for external ACP harnesses (`claude`, `droid`, `gemini`, `opencode`, or explicitly requested Codex ACP/acpx) and for `agents.entries.*` entries whose `runtime.type` is `acp`.
@@ -241,7 +241,7 @@ In `prefer` mode, hidden sub-agents are for internal legwork that the user does
241241
<ParamField path="mode" type='"run" | "session"' default="run">
242242
If `thread: true` and `mode` is omitted, default becomes `session`. `mode: "session"` requires `thread: true`.
243243
If thread binding is unavailable for the requester channel, use `mode: "run"` instead.
244-
With `visible: true`, omit `mode`; visible sessions are persistent and do not support `mode: "run"`.
244+
With `visible: true`, omit `mode` or use the default `"run"`; the visible session remains persistent. `mode: "session"` is unavailable on this path.
245245
</ParamField>
246246
<ParamField path="cleanup" type='"delete" | "keep"' default="keep">
247247
`"delete"` archives the session immediately after announce (still keeps the transcript via rename).
@@ -275,7 +275,7 @@ their latest assistant turn back to the requester; external delivery stays with
275275
the parent/requester agent.
276276
</Warning>
277277

278-
With `visible: true`, `category`, `model`, `cwd`, and a same-agent `context: "fork"` are supported. Use this durable mode for coding, multi-step work, or results the user may revisit, steer, or keep; it appears in the sidebar when the web UI is available and still works without it. Pass `category` to place the new session in that sidebar group atomically; omitted or blank values leave it ungrouped. A sandboxed target restricts `cwd` to that agent's workspace. Non-admin callers may use `cwd` only inside a configured agent workspace. Omit `cwd` to use the target agent workspace; for another repository, ask the operator to start the session from a registered project. Do not replace a rejected persistent spawn with the synchronous `openclaw agent` CLI, whose command deadline defaults to 600 seconds. Thread binding, `mode`, thinking overrides, `lightContext`, `attachments`, and `attachAs` are unavailable on this path because visible sessions are persistent dashboard sessions created through `sessions.create`. The new dashboard child inherits the requester's effective tool-policy ceiling before its first turn. Session listing and addressing obey `tools.sessions.visibility`; the default `tree` scope covers the current session and its own spawn subtree, while the main session can reach every same-agent session unless `self` or the sandbox spawned-only clamp applies. See [Session tools](/concepts/session-tool#visibility) and [Managed worktrees](/concepts/managed-worktrees).
278+
With `visible: true`, `category`, `model`, `cwd`, and a same-agent `context: "fork"` are supported. Use this durable mode for coding, multi-step work, or results the user may revisit, steer, or keep; it appears in the sidebar when the web UI is available and still works without it. Pass `category` to place the new session in that sidebar group atomically; omitted or blank values leave it ungrouped. A sandboxed target restricts `cwd` to that agent's workspace. Non-admin callers may use `cwd` only inside a configured agent workspace. With `worktree: true`, omitting `cwd` inherits the same-agent parent's live managed repository and creates a separate worktree. Other spawns use the target agent workspace; for another repository, ask the operator to start the session from a registered project. Do not replace a rejected persistent spawn with the synchronous `openclaw agent` CLI, whose command deadline defaults to 600 seconds. Thread binding, `mode: "session"`, thinking overrides, `lightContext`, and attachment staging are unavailable on this path because visible sessions are persistent dashboard sessions created through `sessions.create`. The default `mode: "run"`, empty `attachments`, and an empty `attachAs.mountPath` are accepted without changing that behavior. The new dashboard child inherits the requester's effective tool-policy ceiling before its first turn. Session listing and addressing obey `tools.sessions.visibility`; the default `tree` scope covers the current session and its own spawn subtree, while the main session can reach every same-agent session unless `self` or the sandbox spawned-only clamp applies. See [Session tools](/concepts/session-tool#visibility) and [Managed worktrees](/concepts/managed-worktrees).
279279

280280
If a call fails with `Parameters require visible=true`, omit the named category or worktree options to keep the hidden or ACP runtime. To create a visible session instead, use `visible: true` with `runtime: "subagent"` and omit `mode`, `thread`, `thinking`, `lightContext`, `attachments`, `attachAs`, swarm options, and the ACP-only `streamTo` and `resumeSessionId`. Worktree names and base refs also require `worktree: true`. Adding `visible: true` alone does not make an ACP call compatible.
281281

‎src/agents/tools/sessions-spawn-tool.test.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ describe("sessions_spawn tool", () => {
518518
};
519519

520520
expect(schema.properties?.visible?.description).toBe(
521-
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only; omit mode/thread/thinking/lightContext/attachments/attachAs.",
521+
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only. Default run mode and empty attachment fields are accepted; no thread/thinking/lightContext or attachment staging.",
522522
);
523523
expect(schema.properties?.cwd?.description).toContain(
524524
"outside configured agent workspaces require operator.admin",
@@ -531,10 +531,12 @@ describe("sessions_spawn tool", () => {
531531
expect(tool.description).toContain("`Owner: <label>` on the second line");
532532
expect(tool.description).toContain("`tools.sessions.visibility`");
533533
expect(schema.properties?.runtime?.description).toContain("visible=true");
534-
expect(schema.properties?.mode?.description).toContain("Omit with visible=true");
534+
expect(schema.properties?.mode?.description).toContain('accept omitted/default "run"');
535535
expect(schema.properties?.lightContext?.description).toContain("unavailable with visible=true");
536-
expect(schema.properties?.attachments?.description).toContain("unavailable with visible=true");
537-
expect(schema.properties?.attachAs?.description).toContain("unavailable with visible=true");
536+
expect(schema.properties?.attachments?.description).toContain("accepts only an empty array");
537+
expect(schema.properties?.attachAs?.description).toContain(
538+
"only an omitted or blank mountPath",
539+
);
538540
expect(schema.properties?.category?.description).toContain("leave it ungrouped");
539541
expect(schema.properties?.mode?.enum).toEqual(["run"]);
540542
expect(schema.properties?.mode?.anyOf).toBeUndefined();

‎src/agents/tools/sessions-spawn-tool.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ function createSessionsSpawnToolSchema(params: {
190190
cwd: Type.Optional(
191191
Type.String({
192192
description:
193-
"Working directory for the child. With visible=true, paths outside configured agent workspaces require operator.admin; omit to use the target agent workspace.",
193+
"Child working directory. Visible paths outside configured agent workspaces require operator.admin. Omitted with worktree=true: inherit the same-agent parent managed repository; otherwise use the target agent workspace.",
194194
}),
195195
),
196196
...(params.threadAvailable
@@ -205,8 +205,8 @@ function createSessionsSpawnToolSchema(params: {
205205
: {}),
206206
mode: optionalStringEnum(spawnModes, {
207207
description: params.threadAvailable
208-
? '"run" one-shot; "session" persistent/thread-bound. Omit with visible=true.'
209-
: '"run" one-shot. Omit with visible=true; visible sessions are persistent.',
208+
? '"run" one-shot; "session" persistent/thread-bound. Visible sessions accept only omitted/default "run" and remain persistent.'
209+
: '"run" one-shot. Visible sessions accept omitted/default "run" and remain persistent.',
210210
}),
211211
cleanup: optionalStringEnum(["delete", "keep"] as const, {
212212
description: "Hidden session cleanup; visible=true always keeps the session.",
@@ -253,7 +253,10 @@ function createSessionsSpawnToolSchema(params: {
253253
encoding: Type.Optional(optionalStringEnum(["utf8", "base64"] as const)),
254254
mimeType: Type.Optional(Type.String()),
255255
}),
256-
{ maxItems: 50, description: "Inline snapshots; unavailable with visible=true." },
256+
{
257+
maxItems: 50,
258+
description: "Inline snapshots; visible=true accepts only an empty array.",
259+
},
257260
),
258261
),
259262
attachAs: Type.Optional(
@@ -263,7 +266,10 @@ function createSessionsSpawnToolSchema(params: {
263266
// Kept as a hint; implementation materializes into the child workspace.
264267
mountPath: Type.Optional(Type.String()),
265268
},
266-
{ description: "Attachment mount hint; unavailable with visible=true." },
269+
{
270+
description:
271+
"Attachment mount hint; visible=true accepts only an omitted or blank mountPath.",
272+
},
267273
),
268274
),
269275
...(params.acpAvailable

‎src/agents/tools/sessions-spawn-visible.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
23
import { Type } from "typebox";
34
import { readMissingScopeErrorDetails } from "../../../packages/gateway-protocol/src/gateway-error-details.js";
@@ -41,7 +42,7 @@ export const VISIBLE_SESSIONS_SPAWN_SCHEMA = {
4142
visible: Type.Optional(
4243
Type.Boolean({
4344
description:
44-
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only; omit mode/thread/thinking/lightContext/attachments/attachAs.",
45+
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only. Default run mode and empty attachment fields are accepted; no thread/thinking/lightContext or attachment staging.",
4546
}),
4647
),
4748
category: Type.Optional(
@@ -167,8 +168,8 @@ export async function maybeSpawnVisibleSession(params: {
167168
],
168169
[
169170
"attachAs",
170-
params.raw.attachAs && typeof params.raw.attachAs === "object"
171-
? readToolStringParam(params.raw.attachAs as Record<string, unknown>, "mountPath")
171+
isRecord(params.raw.attachAs)
172+
? readToolStringParam(params.raw.attachAs, "mountPath")
172173
: params.raw.attachAs,
173174
"attachment staging is not wired to the sessions.create path",
174175
],

‎src/gateway/server-methods/sessions-create.ts‎

Lines changed: 69 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "../../../packages/gateway-protocol/src/index.js";
1212
import { resolveAgentWorkspaceDir } from "../../agents/agent-scope.js";
1313
import { insideGitCheckout } from "../../agents/worktrees/git.js";
14+
import { managedWorktrees } from "../../agents/worktrees/service.js";
1415
import { resolveAgentMainSessionKey } from "../../config/sessions/main-session.js";
1516
import { sessionEntryForkedFromParent } from "../../config/sessions/session-entry-lineage.js";
1617
import type { InternalSessionEntry } from "../../config/sessions/types.js";
@@ -61,6 +62,44 @@ import type { GatewayRequestHandlers } from "./types.js";
6162
import { assertValidParams } from "./validation.js";
6263
import { resolveWorkspacePathContainment } from "./workspace-path-containment.js";
6364

65+
function resolveSpawnParentWorktreeSource(
66+
parentSessionKey: string,
67+
agentId: string,
68+
assertCallerCurrent: (() => void) | undefined,
69+
) {
70+
const parent = loadGatewaySessionEntryReadOnly(parentSessionKey, { agentId });
71+
if (!parent.entry?.worktree) {
72+
return undefined;
73+
}
74+
const worktree = managedWorktrees.findLiveByOwner("session", parent.canonicalKey);
75+
if (
76+
!worktree ||
77+
worktree.id !== parent.entry.worktree.id ||
78+
parent.entry.archivedAt !== undefined
79+
) {
80+
throw new Error("Spawn parent managed worktree changed; retry from its current session");
81+
}
82+
const parentSessionId = parent.entry.sessionId;
83+
// A copied parent key cannot lend a repository after its exact session or
84+
// registered worktree changes, including during awaited preparation.
85+
const assertCurrent = () => {
86+
assertCallerCurrent?.();
87+
const current = loadGatewaySessionEntryReadOnly(parent.canonicalKey, { agentId });
88+
const currentWorktree = managedWorktrees.findLiveByOwner("session", parent.canonicalKey);
89+
if (
90+
current.entry?.sessionId !== parentSessionId ||
91+
current.entry.archivedAt !== undefined ||
92+
current.entry.worktree?.id !== worktree.id ||
93+
currentWorktree?.id !== worktree.id ||
94+
currentWorktree.repoRoot !== worktree.repoRoot ||
95+
currentWorktree.path !== worktree.path
96+
) {
97+
throw new Error("Spawn parent managed worktree changed; retry from its current session");
98+
}
99+
};
100+
return { workspace: worktree.repoRoot, assertCurrent };
101+
}
102+
64103
export const sessionCreateHandlers: GatewayRequestHandlers = {
65104
"sessions.create": async ({
66105
req,
@@ -77,10 +116,23 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
77116
}
78117
const p = params;
79118
const parentSessionKey = normalizeOptionalString(p.parentSessionKey);
119+
const sessionCreation = resolveOperatorSessionCreation(client, { allowTrustedHint: true });
120+
const spawnRequesterSessionKey =
121+
sessionCreation.via === "spawn"
122+
? normalizeOptionalString(sessionCreation.requesterSessionKey)
123+
: undefined;
124+
if (sessionCreation.inheritedToolPolicy && parentSessionKey !== spawnRequesterSessionKey) {
125+
respond(
126+
false,
127+
undefined,
128+
errorShape(ErrorCodes.INVALID_REQUEST, "spawn parent must match the trusted agent caller"),
129+
);
130+
return;
131+
}
80132
const requestedModel = normalizeOptionalString(p.model);
81133
const cfg = context.getRuntimeConfig();
82134
const authority = createAgentRuntimeAuthorityGuard(client, context, respond);
83-
const commitGuard =
135+
let commitGuard =
84136
authority.commitGuard || sessionMutationCommitGuard || sessionMutationAuthorization
85137
? () => {
86138
sessionMutationCommitGuard?.();
@@ -351,8 +403,23 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
351403
const target = resolveGatewaySessionStoreTarget({ cfg, key: targetKey, agentId });
352404
sessionKey = preservesUnspecifiedKey ? undefined : targetKey;
353405
sessionAgentId = target.agentId;
406+
const inheritParentWorktree =
407+
!projectRoot &&
408+
!requestedCwd &&
409+
!requestedProjectGitUrl &&
410+
spawnRequesterSessionKey &&
411+
spawnRequesterSessionKey === parentSessionKey &&
412+
sessionCreation.actor?.type === "agent" &&
413+
normalizeAgentId(sessionCreation.actor.id) === target.agentId;
414+
const inheritedSource = inheritParentWorktree
415+
? resolveSpawnParentWorktreeSource(spawnRequesterSessionKey, target.agentId, commitGuard)
416+
: undefined;
417+
commitGuard = inheritedSource?.assertCurrent ?? commitGuard;
354418
const workspace =
355-
projectRoot ?? requestedCwd ?? resolveAgentWorkspaceDir(cfg, target.agentId);
419+
projectRoot ??
420+
requestedCwd ??
421+
inheritedSource?.workspace ??
422+
resolveAgentWorkspaceDir(cfg, target.agentId);
356423
// Subdirectory workspaces are valid: the worktree service resolves the repo root
357424
// via git discovery, so the preflight must accept ancestor .git entries too.
358425
if (!requestedProjectGitUrl && !insideGitCheckout(workspace)) {
@@ -404,19 +471,6 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
404471
let runError: unknown;
405472
let runMeta: Record<string, unknown> | undefined;
406473
let messageSeq: number | undefined;
407-
const sessionCreation = resolveOperatorSessionCreation(client, { allowTrustedHint: true });
408-
const spawnRequesterSessionKey =
409-
sessionCreation.via === "spawn"
410-
? normalizeOptionalString(sessionCreation.requesterSessionKey)
411-
: undefined;
412-
if (sessionCreation.inheritedToolPolicy && parentSessionKey !== spawnRequesterSessionKey) {
413-
respond(
414-
false,
415-
undefined,
416-
errorShape(ErrorCodes.INVALID_REQUEST, "spawn parent must match the trusted agent caller"),
417-
);
418-
return;
419-
}
420474
const allowExistingModelSelection = authorizeOperatorScopesForRequiredScope(
421475
ADMIN_SCOPE,
422476
clientScopes,

0 commit comments

Comments
 (0)