Skip to content

Commit 153cc87

Browse files
committed
fix: bind session creation to admitted Gateway
1 parent a87fb08 commit 153cc87

2 files changed

Lines changed: 175 additions & 10 deletions

File tree

‎src/agents/tools/in-process-gateway.test.ts‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { createDeferred } from "../../../test/helpers/promise.js";
23
import { readInProcessAgentRuntimeIdentity } from "../../gateway/in-process-agent-runtime-identity.js";
34
import type { GatewayRequestContext } from "../../gateway/server-methods/types.js";
45

@@ -27,6 +28,7 @@ import { withGatewayToolCallerIdentity } from "./gateway-caller-context.js";
2728
import { getGatewaySessionSpawnContext } from "./gateway-session-spawn-context.js";
2829
import {
2930
callAgentToolGatewayRequest,
31+
callInProcessGatewayTool,
3032
callInProcessGatewayToolWithCreation,
3133
withAgentToolGatewayRuntimeIdentity,
3234
} from "./in-process-gateway.js";
@@ -108,6 +110,157 @@ describe("trusted in-process Gateway session creation", () => {
108110
);
109111
expect(getGatewaySessionSpawnContext()).toBeUndefined();
110112
});
113+
114+
it("keeps session creation on the admitted Gateway through async settlement", async () => {
115+
const admitted = { gateway: "admitted" } as unknown as GatewayRequestContext;
116+
const replacement = { gateway: "replacement" } as unknown as GatewayRequestContext;
117+
const params = { agentId: "main", label: "worker" };
118+
const creation = {
119+
via: "spawn" as const,
120+
actor: { type: "agent" as const, id: "main" },
121+
requesterSessionKey: "agent:main:main",
122+
};
123+
const controller = new AbortController();
124+
let current = admitted;
125+
let admittedDispatches = 0;
126+
let replacementDispatches = 0;
127+
const dispatchThroughSelectedGateway = (
128+
options:
129+
| {
130+
resolveGatewayContext?: () => GatewayRequestContext | undefined;
131+
sessionCreation?: unknown;
132+
signal?: AbortSignal;
133+
syntheticScopes?: string[];
134+
timeoutMs?: number;
135+
}
136+
| undefined,
137+
) => {
138+
const selected = options?.resolveGatewayContext?.() ?? replacement;
139+
if (selected === admitted) {
140+
admittedDispatches += 1;
141+
} else if (selected === replacement) {
142+
replacementDispatches += 1;
143+
}
144+
return selected;
145+
};
146+
const runAsAdmittedCaller = async <T>(run: () => Promise<T>) =>
147+
await withGatewayToolCallerIdentity(
148+
{
149+
agentId: "main",
150+
sessionKey: "agent:main:main",
151+
gatewayContextResolver: () => current,
152+
},
153+
run,
154+
);
155+
156+
mocks.dispatch.mockImplementationOnce(async (_method, _params, options) => {
157+
expect(dispatchThroughSelectedGateway(options)).toBe(admitted);
158+
expect(options).toEqual({
159+
forceSyntheticClient: true,
160+
resolveGatewayContext: expect.any(Function),
161+
sessionCreation: creation,
162+
signal: controller.signal,
163+
syntheticScopes: ["operator.write"],
164+
timeoutMs: 2_000,
165+
});
166+
return { key: "agent:main:worker" };
167+
});
168+
169+
await expect(
170+
runAsAdmittedCaller(() =>
171+
callInProcessGatewayToolWithCreation("sessions.create", params, creation, {
172+
signal: controller.signal,
173+
timeoutMs: 2_000,
174+
}),
175+
),
176+
).resolves.toEqual({ key: "agent:main:worker" });
177+
expect(mocks.dispatch).toHaveBeenLastCalledWith("sessions.create", params, expect.any(Object));
178+
expect({ admittedDispatches, replacementDispatches }).toEqual({
179+
admittedDispatches: 1,
180+
replacementDispatches: 0,
181+
});
182+
183+
current = admitted;
184+
const dispatchesBeforeReplacement = mocks.dispatch.mock.calls.length;
185+
await expect(
186+
runAsAdmittedCaller(async () => {
187+
current = replacement;
188+
return await callInProcessGatewayToolWithCreation("sessions.create", params, creation);
189+
}),
190+
).rejects.toThrow("Gateway instance unavailable for sessions.create");
191+
expect(mocks.dispatch).toHaveBeenCalledTimes(dispatchesBeforeReplacement);
192+
expect(mocks.callGatewayTool).not.toHaveBeenCalled();
193+
expect(replacementDispatches).toBe(0);
194+
195+
for (const settlement of ["resolve", "reject"] as const) {
196+
current = admitted;
197+
const pendingDispatch = createDeferred<{ key: string }>();
198+
mocks.dispatch.mockImplementationOnce(async (_method, _params, options) => {
199+
expect(dispatchThroughSelectedGateway(options)).toBe(admitted);
200+
return await pendingDispatch.promise;
201+
});
202+
203+
const expectedDispatchCount = mocks.dispatch.mock.calls.length + 1;
204+
const creationCall = runAsAdmittedCaller(() =>
205+
callInProcessGatewayToolWithCreation("sessions.create", params, creation),
206+
);
207+
await vi.waitFor(() => expect(mocks.dispatch).toHaveBeenCalledTimes(expectedDispatchCount));
208+
current = replacement;
209+
if (settlement === "resolve") {
210+
pendingDispatch.resolve({ key: "agent:main:worker" });
211+
} else {
212+
pendingDispatch.reject(new Error("inner dispatch failed"));
213+
}
214+
await expect(creationCall).rejects.toThrow(
215+
"Gateway instance unavailable for sessions.create",
216+
);
217+
expect(replacementDispatches).toBe(0);
218+
}
219+
});
220+
221+
it("retains the generic helper's admitted binding and transport fallback", async () => {
222+
const admitted = { gateway: "admitted" } as unknown as GatewayRequestContext;
223+
const replacement = { gateway: "replacement" } as unknown as GatewayRequestContext;
224+
let current = admitted;
225+
mocks.dispatch.mockImplementationOnce(async (_method, _params, options) => ({
226+
selected: options?.resolveGatewayContext?.() ?? replacement,
227+
}));
228+
229+
await expect(
230+
withGatewayToolCallerIdentity(
231+
{
232+
agentId: "main",
233+
sessionKey: "agent:main:main",
234+
gatewayContextResolver: () => current,
235+
},
236+
() => callInProcessGatewayTool("sessions.list", {}),
237+
),
238+
).resolves.toEqual({ selected: admitted });
239+
240+
current = admitted;
241+
await expect(
242+
withGatewayToolCallerIdentity(
243+
{
244+
agentId: "main",
245+
sessionKey: "agent:main:main",
246+
gatewayContextResolver: () => current,
247+
},
248+
async () => {
249+
current = replacement;
250+
return await callInProcessGatewayTool("sessions.list", {});
251+
},
252+
),
253+
).rejects.toThrow("Gateway instance unavailable for sessions.list");
254+
255+
mocks.hasContext = false;
256+
await callInProcessGatewayTool("sessions.list", { limit: 5 });
257+
expect(mocks.callGatewayTool).toHaveBeenCalledWith(
258+
"sessions.list",
259+
{},
260+
{ limit: 5 },
261+
{ scopes: ["operator.write"] },
262+
);
263+
});
111264
});
112265

113266
describe("request-shaped in-process Gateway dispatch", () => {

‎src/agents/tools/in-process-gateway.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -232,16 +232,28 @@ export async function callInProcessGatewayToolWithCreation<T = Record<string, un
232232
options: { signal?: AbortSignal; timeoutMs?: number | null } = {},
233233
): Promise<T> {
234234
const scopes = resolveLeastPrivilegeOperatorScopesForMethod(method, params);
235-
if (hasInProcessGatewayContext()) {
236-
return await dispatchGatewayMethodInProcess<T>(method, params, {
237-
forceSyntheticClient: true,
238-
sessionCreation: creation,
239-
syntheticScopes: scopes,
240-
...(options.signal ? { signal: options.signal } : {}),
241-
...(options.timeoutMs !== undefined && options.timeoutMs !== null
242-
? { timeoutMs: options.timeoutMs }
243-
: {}),
244-
});
235+
const resolveGatewayContext = callerGatewayContextResolver();
236+
const boundGateway = resolveGatewayContext
237+
? bindInProcessGatewayContext(method, resolveGatewayContext)
238+
: undefined;
239+
if (hasInProcessGatewayContext(boundGateway?.resolve)) {
240+
return await runBoundInProcessGatewayCall(
241+
boundGateway,
242+
async (boundResolver) =>
243+
await dispatchGatewayMethodInProcess<T>(method, params, {
244+
forceSyntheticClient: true,
245+
sessionCreation: creation,
246+
syntheticScopes: scopes,
247+
...(options.signal ? { signal: options.signal } : {}),
248+
...(options.timeoutMs !== undefined && options.timeoutMs !== null
249+
? { timeoutMs: options.timeoutMs }
250+
: {}),
251+
...(boundResolver ? { resolveGatewayContext: boundResolver } : {}),
252+
}),
253+
);
254+
}
255+
if (boundGateway) {
256+
throw new Error(`Gateway instance unavailable for ${method}`);
245257
}
246258
// The fallback is a real local Gateway request. Carry spawn policy only in
247259
// the signed agent-runtime identity token, never in model-authored params.

0 commit comments

Comments
 (0)