Skip to content

Commit 16c87e6

Browse files
authored
fix(agents): retain caller scope for nested session tools (#126221)
Use the durable run-session identity for nested session lookups on multi-agent hosts while retaining existing visibility and agent-to-agent authorization. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 6775075 commit 16c87e6

2 files changed

Lines changed: 169 additions & 2 deletions

File tree

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// Verifies that nested session tools keep execution identity without narrowing discovery policy.
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { setEmbeddedMode } from "../infra/embedded-mode.js";
4+
import { createOpenClawTools } from "./openclaw-tools.js";
5+
6+
type GatewayRequest = { method: string; params?: Record<string, unknown> };
7+
type OpenClawToolsOptions = NonNullable<Parameters<typeof createOpenClawTools>[0]>;
8+
9+
const embeddedGatewayCalls = vi.hoisted(() => vi.fn());
10+
const embeddedGatewayResponseMock = vi.hoisted(() => vi.fn());
11+
const createEmbeddedCallGatewayMock = vi.hoisted(() =>
12+
vi.fn(() => async (request: GatewayRequest) => {
13+
embeddedGatewayCalls(request);
14+
const response = embeddedGatewayResponseMock(request);
15+
if (response !== undefined) {
16+
return response;
17+
}
18+
if (request.method === "sessions.list") {
19+
return { sessions: [], hasMore: false };
20+
}
21+
if (request.method === "sessions.search") {
22+
return { results: [], indexing: false, truncated: false };
23+
}
24+
if (request.method === "chat.history") {
25+
return { messages: [] };
26+
}
27+
return { ok: false };
28+
}),
29+
);
30+
31+
vi.mock("./tools/embedded-gateway-stub.js", () => ({
32+
createEmbeddedCallGateway: createEmbeddedCallGatewayMock,
33+
}));
34+
35+
vi.mock("./openclaw-plugin-tools.js", () => ({
36+
resolveOpenClawPluginToolsForOptions: () => [],
37+
}));
38+
39+
function createTools(
40+
config: OpenClawToolsOptions["config"],
41+
options: { sandboxed?: boolean } = {},
42+
) {
43+
return createOpenClawTools({
44+
agentSessionKey: "global",
45+
runSessionKey: "agent:research:main",
46+
sandboxed: options.sandboxed,
47+
config,
48+
disablePluginTools: true,
49+
wrapBeforeToolCallHook: false,
50+
});
51+
}
52+
53+
function requireTool(tools: ReturnType<typeof createOpenClawTools>, name: string) {
54+
const tool = tools.find((candidate) => candidate.name === name);
55+
if (!tool) {
56+
throw new Error(`Expected tool ${name} to be registered`);
57+
}
58+
return tool;
59+
}
60+
61+
afterEach(() => {
62+
setEmbeddedMode(false);
63+
embeddedGatewayCalls.mockClear();
64+
embeddedGatewayResponseMock.mockReset();
65+
createEmbeddedCallGatewayMock.mockClear();
66+
});
67+
68+
describe("openclaw session lookup context", () => {
69+
it("binds nested session lookups to the durable caller", async () => {
70+
const runSessionKey = "agent:research:main";
71+
setEmbeddedMode(true);
72+
const tools = createTools(
73+
{ agents: { list: [{ id: "main", default: true }, { id: "research" }] } },
74+
{ sandboxed: true },
75+
);
76+
77+
await requireTool(tools, "sessions_list").execute("list", {});
78+
await requireTool(tools, "sessions_search").execute("search", { query: "needle" });
79+
await requireTool(tools, "sessions_history").execute("history", { sessionKey: "current" });
80+
81+
expect(createEmbeddedCallGatewayMock).toHaveBeenCalledWith();
82+
expect(embeddedGatewayCalls).toHaveBeenCalledWith(
83+
expect.objectContaining({
84+
method: "sessions.list",
85+
params: expect.objectContaining({ spawnedBy: runSessionKey }),
86+
}),
87+
);
88+
expect(embeddedGatewayCalls).toHaveBeenCalledWith(
89+
expect.objectContaining({
90+
method: "sessions.search",
91+
params: expect.objectContaining({ sessionKeys: [runSessionKey] }),
92+
}),
93+
);
94+
expect(embeddedGatewayCalls).toHaveBeenCalledWith(
95+
expect.objectContaining({
96+
method: "chat.history",
97+
params: expect.objectContaining({ sessionKey: runSessionKey }),
98+
}),
99+
);
100+
});
101+
102+
it("preserves implicit all-agent discovery for authorized callers", async () => {
103+
embeddedGatewayResponseMock.mockImplementation((request: GatewayRequest) => {
104+
if (request.method === "sessions.list") {
105+
return {
106+
sessions: [
107+
{ key: "agent:main:main", agentId: "main", kind: "main" },
108+
{ key: "agent:research:main", agentId: "research", kind: "main" },
109+
],
110+
hasMore: false,
111+
};
112+
}
113+
if (request.method === "sessions.search") {
114+
const agentId = request.params?.agentId;
115+
const sessionKeys = request.params?.sessionKeys;
116+
const sessionKey = Array.isArray(sessionKeys) ? sessionKeys[0] : undefined;
117+
return typeof agentId === "string" && typeof sessionKey === "string"
118+
? {
119+
results: [
120+
{
121+
sessionKey,
122+
timestamp: 1,
123+
role: "user",
124+
snippet: `${agentId} hit`,
125+
score: 1,
126+
},
127+
],
128+
indexing: false,
129+
truncated: false,
130+
}
131+
: { results: [] };
132+
}
133+
return undefined;
134+
});
135+
setEmbeddedMode(true);
136+
const tools = createTools({
137+
agents: { list: [{ id: "main", default: true }, { id: "research" }] },
138+
tools: {
139+
sessions: { visibility: "all" },
140+
agentToAgent: { enabled: true, allow: ["*"] },
141+
},
142+
});
143+
144+
const listed = await requireTool(tools, "sessions_list").execute("list", {});
145+
const searched = await requireTool(tools, "sessions_search").execute("search", {
146+
query: "hit",
147+
});
148+
149+
expect((listed.details as { sessions: Array<{ agentId: string }> }).sessions).toEqual(
150+
expect.arrayContaining([
151+
expect.objectContaining({ agentId: "main" }),
152+
expect.objectContaining({ agentId: "research" }),
153+
]),
154+
);
155+
expect((searched.details as { results: Array<{ snippet: string }> }).results).toEqual(
156+
expect.arrayContaining([
157+
expect.objectContaining({ snippet: "main hit" }),
158+
expect.objectContaining({ snippet: "research hit" }),
159+
]),
160+
);
161+
const discoveryRequests = embeddedGatewayCalls.mock.calls
162+
.map(([request]) => request as GatewayRequest)
163+
.filter((request) => request.method === "sessions.list");
164+
expect(discoveryRequests).not.toHaveLength(0);
165+
expect(discoveryRequests.some((request) => request.params?.agentId === undefined)).toBe(true);
166+
});
167+
});

‎src/agents/openclaw-tools.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ export function createOpenClawTools(
235235
runtimeSourceConfig: runtimeSnapshot?.sourceConfig,
236236
});
237237
const { sessionAgentId } = resolveSessionAgentIds({
238-
sessionKey: options?.agentSessionKey,
238+
sessionKey: options?.runSessionKey ?? options?.agentSessionKey,
239239
config: resolvedConfig,
240240
agentId: options?.requesterAgentIdOverride,
241241
});
@@ -443,7 +443,7 @@ export function createOpenClawTools(
443443
denylist: explicitFactoryDenylist,
444444
});
445445
const sessionLookupToolOptions = {
446-
agentSessionKey: options?.agentSessionKey,
446+
agentSessionKey: options?.runSessionKey ?? options?.agentSessionKey,
447447
sandboxed: options?.sandboxed,
448448
config: resolvedConfig,
449449
callGateway: embedded ? createEmbeddedCallGateway() : callAgentToolGatewayRequest,

0 commit comments

Comments
 (0)