Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Refuse a connect_to_room the agent controller did not record (CHOO-3808)
Simon Flackea5dde71c493
diff --git a/console/packages/agent-controller/src/agent-hub.test.ts b/console/packages/agent-controller/src/agent-hub.test.tsindex c06e36946..a8f56f257 100644--- a/console/packages/agent-controller/src/agent-hub.test.ts+++ b/console/packages/agent-controller/src/agent-hub.test.ts@@ -311,6 +311,19 @@ describe('placements', () => {expect(hub.roomFor(AGENT, 'session-1')).toBe('room-a');});+ it('refuses placements from an agent host a newer one replaced, rather than dropping them', async () => {+ hub.streamAttached();+ hub.attach(AGENT, 0, ['room-a']);+ const older = watcher();+ older.stream.start();+ const newer = watcher();+ newer.stream.start();+ await expect(older.stream.replacePlacements({ 'session-1': 'room-a' })).rejects.toThrow(+ /a newer one does/+ );+ expect(hub.roomFor(AGENT, 'session-1')).toBeNull();+ });+it('refuses one room for two sessions', async () => {hub.streamAttached();hub.attach(AGENT, 0, ['room-a']);diff --git a/console/packages/agent-controller/src/agent-hub.ts b/console/packages/agent-controller/src/agent-hub.tsindex 80c050259..ed99d6d40 100644--- a/console/packages/agent-controller/src/agent-hub.ts+++ b/console/packages/agent-controller/src/agent-hub.ts@@ -413,6 +413,8 @@ export class AgentHub {return {// Switch keeps no record of an agent's sessions: the agent host says when it starts one.announcesSessionStarts: true,+ // The relay names each call's room from these placements (`roomFor`).+ placementsNameCallRooms: true,start: () => {if (host.started || host.closed) return;host.started = true;@@ -447,7 +449,10 @@ export class AgentHub {// session of the agent unplaced, and its room tools answered "not// connected" though the session had just connected.replacePlacements: async (placements) => {- if (host.closed || agent.host !== host) return { refusedRooms: [] };+ if (host.closed || agent.host !== host)+ throw new Error(+ `this agent host no longer holds agent ${agentId}'s stream on the agent controller; a newer one does`+ );const refusedRooms = [...new Set(Object.values(placements))].filter((roomId) => agent.rooms !== null && !agent.rooms.has(roomId)).sort();diff --git a/console/packages/agent-controller/src/relay.test.ts b/console/packages/agent-controller/src/relay.test.tsindex 5797bdb81..3dbf65266 100644--- a/console/packages/agent-controller/src/relay.test.ts+++ b/console/packages/agent-controller/src/relay.test.ts@@ -537,6 +537,18 @@ describe('forwarding to Switch', () => {expect(forwarded.body).toEqual({ row: 1 });});+ it('refuses placements while the hub is not connected, rather than reporting them taken', async () => {+ const agentHost = host();+ await connected(agentHost);+ await relay.close();+ await waitFor(() => agentHost.seen.disconnected.length > 0, 'the hub to drop');+ await expect(agentHost.stream.replacePlacements({ 'session-1': 'room-a' })).rejects.toThrow(+ /hub is not connected/+ );+ relay = newRelay();+ await relay.start(null);+ });+it('names the room of a call from its session’s placement on the hub', async () => {// An agent host in the controller's own process states its placements to the hub directly.hub.attach('agent-2', 0, ['room-shared']);diff --git a/console/packages/agent-controller/src/runtime.test.ts b/console/packages/agent-controller/src/runtime.test.tsindex 19c049b83..ebdad9c62 100644--- a/console/packages/agent-controller/src/runtime.test.ts+++ b/console/packages/agent-controller/src/runtime.test.ts@@ -76,6 +76,7 @@ function openStream(agentId: string): OpenAgentStream {opened.push({ agentId, scope: deps.scope, filter: deps.filter, signal: deps.signal });return {announcesSessionStarts: true,+ placementsNameCallRooms: true,start: () => {},setSpawnCapable: () => {},replacePlacements: async () => ({ refusedRooms: [] }),diff --git a/console/packages/agent-providers/src/host/agent-host.test.ts b/console/packages/agent-providers/src/host/agent-host.test.tsindex b4064fd51..e48773666 100644--- a/console/packages/agent-providers/src/host/agent-host.test.ts+++ b/console/packages/agent-providers/src/host/agent-host.test.ts@@ -1268,6 +1268,7 @@ it('tells the room it is starting a session when its stream leaves that to it, bopened.push(deps);return {announcesSessionStarts: true,+ placementsNameCallRooms: true,start: () => {},setSpawnCapable: () => {},replacePlacements: async (placements) => {diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.tsindex a028a8136..4ea779348 100644--- a/console/packages/agent-providers/src/host/agent-host.ts+++ b/console/packages/agent-providers/src/host/agent-host.ts@@ -648,6 +648,15 @@ export class AgentHostAssignments {export type AgentEventStream = {/** The agent host, not Switch, tells a room when it starts a session for it. */readonly announcesSessionStarts: boolean;+ /**+ * The room of a session's tool call is the one this stream was last told+ * the session is placed in, not one Switch recorded when the session called+ * `connect_to_room`. True for an agent controller, whose relay names the+ * room on every call from these placements, so a placement it did not take+ * leaves the session calling from no room. False for the agent's own+ * connection, where Switch places the session itself.+ */+ readonly placementsNameCallRooms: boolean;start(): void;setSpawnCapable(capable: boolean): void;/**@@ -844,7 +853,15 @@ export async function runAgentHost(identity,connectionId,placements,- publish,+ // Nothing is stated before the stream exists, so a move made then+ // has not been taken by anyone: said rather than reported done.+ publish: async () => {+ if (!stream) throw new Error("this agent's stream to Switch is not open yet");+ await publish();+ },+ // Without a stream there is no connection for Switch to have placed+ // the session on either, so the move counts as not taken.+ placementsNameCallRooms: () => stream?.placementsNameCallRooms ?? true,redactions: links.redactions,}))diff --git a/console/packages/agent-providers/src/host/hub-stream.ts b/console/packages/agent-providers/src/host/hub-stream.tsindex b64274888..ebe824f1d 100644--- a/console/packages/agent-providers/src/host/hub-stream.ts+++ b/console/packages/agent-providers/src/host/hub-stream.ts@@ -77,6 +77,8 @@ export function openHubStream(url: string): OpenAgentStream {class HubEventStream implements AgentEventStream {/** The agent host, not Switch, tells a room when it starts a session for it. */readonly announcesSessionStarts = true;+ /** The controller's relay names each call's room from the placements. */+ readonly placementsNameCallRooms = true;private started = false;private socket: WebSocket | null = null;/** The last sequence this side has handled; sent on every hello. */@@ -110,8 +112,12 @@ class HubEventStream implements AgentEventStream {async replacePlacements(placements: Record<string, string>): Promise<{ refusedRooms: string[] }> {this.placements = { ...placements };const socket = this.socket;- // Not connected: the next hello carries them.- if (!socket || socket.readyState !== WebSocket.OPEN) return { refusedRooms: [] };+ // Not connected: the next hello carries them, but until then the relay+ // names no room for the sessions they move.+ if (!socket || socket.readyState !== WebSocket.OPEN)+ throw new Error(+ 'the agent controller hub is not connected; the placements are stated when it reconnects'+ );const id = ++this.nextId;const answer = await new Promise<{ error?: string; refusedRooms?: string[] }>((resolve) => {this.placementCalls.set(id, resolve);@@ -196,7 +202,11 @@ class HubEventStream implements AgentEventStream {this.deps.signal.removeEventListener('abort', abort);if (this.socket === socket) this.socket = null;// The placements a call was sending go again with the next hello.- for (const call of this.placementCalls.values()) call({});+ for (const call of this.placementCalls.values())+ call({+ error:+ 'the agent controller hub closed before it took the placements; they are stated again when it reconnects',+ });this.placementCalls.clear();resolve({ code: event.code, reason: event.reason, helloed });});diff --git a/console/packages/agent-providers/src/host/watcher-tools.test.ts b/console/packages/agent-providers/src/host/watcher-tools.test.tsindex b6ec9f214..61b4cc223 100644--- a/console/packages/agent-providers/src/host/watcher-tools.test.ts+++ b/console/packages/agent-providers/src/host/watcher-tools.test.ts@@ -1,7 +1,7 @@import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { afterEach, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { SessionPlacements } from './placements';import { Redactions } from './redaction';import type { Caller } from './session-channel';@@ -48,6 +48,7 @@ it('moves rooms one at a time, so a refused move puts back only what it replacedconnectionId: 'connection',placements,publish: async () => {},+ placementsNameCallRooms: () => false,redactions: new Redactions(),});let refuseFirst!: () => void;@@ -87,6 +88,7 @@ it('scrubs every service token handed out from what it sends to Switch', async (connectionId: 'connection',placements: await SessionPlacements.open(base, () => []),publish: async () => {},+ placementsNameCallRooms: () => false,redactions,});calls.connect.mockResolvedValue({ content: [{ type: 'text', text: 'posted' }] });@@ -122,6 +124,7 @@ it('answers a service token ask from Switch, as the agent, and scrubs the tokenconnectionId: 'connection',placements: await SessionPlacements.open(base, () => []),publish: async () => {},+ placementsNameCallRooms: () => false,redactions,});const answered = await answer(await caller(base, 'session'), {@@ -193,6 +196,7 @@ it('posts a session’s room reply only into the room it still attends', async (connectionId: 'connection',placements,publish: async () => {},+ placementsNameCallRooms: () => false,redactions: new Redactions(),});calls.connect.mockResolvedValue({ content: [{ type: 'text', text: '{"event_id":"e"}' }] });@@ -229,6 +233,7 @@ it('reads the instructions of the room a session attends, without moving it', asconnectionId: 'connection',placements,publish: async () => {},+ placementsNameCallRooms: () => false,redactions: new Redactions(),});const session = await caller(base, 'session');@@ -268,3 +273,114 @@ it('reads the instructions of the room a session attends, without moving it', asexpect(calls.connect).toHaveBeenCalledTimes(3);expect(placements.roomOf('session')).toBe('elsewhere');});++describe('a move behind an agent controller, whose relay names each call’s room', () => {+ async function setUp(publish: (placements: SessionPlacements) => Promise<void>) {+ const base = await mkdtemp(join(tmpdir(), 'watcher-tools-'));+ roots.push(base);+ const placements = await SessionPlacements.open(base, () => []);+ await placements.place('session', 'room-before');+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const answer = sessionToolAnswerer({+ identity: { agentId: 'agent', endpoint: 'https://switch.test', token: 't' },+ connectionId: 'connection',+ placements,+ publish: () => publish(placements),+ placementsNameCallRooms: () => true,+ redactions: new Redactions(),+ });+ calls.connect.mockResolvedValue({+ content: [{ type: 'text', text: 'connected' }],+ structuredContent: { room_id: 'room-after' },+ });+ const connect = async () =>+ (await answer(await caller(base, 'session'), {+ type: 'tool',+ name: 'connect_to_room',+ arguments: { room_id: 'room-after' },+ })) as {+ isError?: boolean;+ content: { text: string }[];+ structuredContent?: Record<string, unknown>;+ };+ return { placements, connect };+ }++ it('is refused, and put back, when the controller does not take it', async () => {+ const stated: string[] = [];+ let refuse = true;+ const { placements, connect } = await setUp(async (held) => {+ stated.push(held.roomOf('session') ?? 'none');+ if (refuse) {+ refuse = false;+ throw new Error('the agent controller hub is not connected');+ }+ });+ const result = await connect();++ expect(result.isError).toBe(true);+ expect(result.content[0]!.text).toMatch(/did not take effect/);+ expect(result.content[0]!.text).toMatch(/the agent controller hub is not connected/);+ expect(placements.roomOf('session')).toBe('room-before');+ // The move, then the map put back, so the next reconnect states that.+ expect(stated).toEqual(['room-after', 'room-before']);+ });++ it('is refused when the controller leaves the room out and names it back', async () => {+ // The controller places only rooms it counts the agent as in; the publish+ // then takes the session out of the room it named back. Told it had+ // connected, the session would call from no room.+ let leaveOut = true;+ const { placements, connect } = await setUp(async (held) => {+ if (leaveOut) {+ leaveOut = false;+ await held.roomLost('room-after');+ }+ });+ const result = await connect();++ expect(result.isError).toBe(true);+ expect(result.content[0]!.text).toMatch(+ /does not count room room-after among this agent's rooms yet/+ );+ expect(placements.roomOf('session')).toBe('room-before');+ });++ it('is answered as Switch answered it once the controller takes it', async () => {+ const { placements, connect } = await setUp(async () => {});+ const result = await connect();++ expect(result.isError).toBeFalsy();+ expect(result.structuredContent).toEqual({ room_id: 'room-after' });+ expect(placements.roomOf('session')).toBe('room-after');+ });+});++it('keeps a move Switch recorded itself when the stream does not take the placements', async () => {+ // Over the agent's own connection Switch placed the session on connect, so+ // the placements going astray costs nothing a later statement will not fix.+ const base = await mkdtemp(join(tmpdir(), 'watcher-tools-'));+ roots.push(base);+ const placements = await SessionPlacements.open(base, () => []);+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const answer = sessionToolAnswerer({+ identity: { agentId: 'agent', endpoint: 'https://switch.test', token: 't' },+ connectionId: 'connection',+ placements,+ publish: async () => {+ throw new Error('timed out');+ },+ placementsNameCallRooms: () => false,+ redactions: new Redactions(),+ });+ calls.connect.mockResolvedValue({ content: [{ type: 'text', text: 'connected' }] });+ const result = (await answer(await caller(base, 'session'), {+ type: 'tool',+ name: 'connect_to_room',+ arguments: { room_id: 'room' },+ })) as { isError?: boolean };++ expect(result.isError).toBeFalsy();+ expect(placements.roomOf('session')).toBe('room');+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/stated again on the next change/));+});diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.tsindex 70e49f46d..fe3d7f827 100644--- a/console/packages/agent-providers/src/host/watcher-tools.ts+++ b/console/packages/agent-providers/src/host/watcher-tools.ts@@ -26,7 +26,11 @@ import { sharedConfigSchema } from './shared-config';* connection id, and the selector naming the session, its host and its* generation. `connect_to_room` is also a local move: the room is placed with* the calling session before Switch is asked, so the room's next message- * reaches it, and put back as it was if Switch refuses.+ * reaches it, and put back as it was if Switch refuses. Behind an agent+ * controller, whose relay names each call's room from the placements, a move+ * the controller does not take is put back and refused as well: Switch only+ * checked membership, and the session would otherwise be told it connected+ * and then find every call made from no room.** It also answers the sessions' asks for service tokens (`AgentServiceTokens`),* and scrubs every token handed out from the arguments of every call it makes,@@ -38,6 +42,11 @@ export function sessionToolAnswerer(deps: {placements: SessionPlacements;/** States every placement to Switch; raises when Switch does not take them. */publish: () => Promise<void>;+ /**+ * Whether a call's room is named from the stated placements rather than+ * recorded by Switch on `connect_to_room` (`AgentEventStream`).+ */+ placementsNameCallRooms: () => boolean;/** The service tokens handed out in this process, added to as more are. */redactions: Redactions;}): AskHandler {@@ -109,12 +118,44 @@ export function sessionToolAnswerer(deps: {await deps.placements.restore(before);return result;}+ let notTaken: string | null = null;try {await deps.publish();+ // A room the controller left out and named back (it does not count the+ // agent as in it yet) is taken off the session by the publish itself.+ if (deps.placementsNameCallRooms() && deps.placements.roomOf(caller.sessionId) !== roomId)+ notTaken = `the agent controller does not count room ${roomId} among this agent's rooms yet`;} catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ // Over the agent's own connection Switch placed the session on connect,+ // and a later statement puts the copy right.+ if (deps.placementsNameCallRooms()) notTaken = reason;+ else+ console.warn(+ `Switch did not take this agent's session placements after session ${caller.sessionId} connected to room ${roomId}: ${reason}. They are stated again on the next change or reconnect.`+ );+ }+ if (notTaken !== null) {+ await deps.placements.restore(before);+ // So what the stream states on its next change or reconnect is the map+ // put back, not the move it did not take.+ await deps.publish().catch(() => {});console.warn(- `Switch did not take this agent's session placements after session ${caller.sessionId} connected to room ${roomId}: ${error instanceof Error ? error.message : String(error)}. They are stated again on the next change or reconnect.`+ `The agent controller did not take session ${caller.sessionId}'s move to room ${roomId}: ${notTaken}. The move was put back and connect_to_room refused.`);+ return {+ isError: true,+ content: [+ {+ type: 'text',+ text:+ 'connect_to_room did not take effect: Switch accepted it, but the agent controller ' ++ `running this agent did not record the move to room ${roomId} (${notTaken}), so your ` ++ 'calls would not be made from that room. Call connect_to_room again; if it keeps ' ++ "failing, the agent controller's log says why.",+ },+ ],+ };}if (!displaced) return result;const warning =diff --git a/console/packages/switch-agent-runtime/src/event-stream.ts b/console/packages/switch-agent-runtime/src/event-stream.tsindex 792ff953d..f90a33057 100644--- a/console/packages/switch-agent-runtime/src/event-stream.ts+++ b/console/packages/switch-agent-runtime/src/event-stream.ts@@ -474,6 +474,12 @@ export class SwitchEventStream {return this.announces;}+ /**+ * Switch places a session itself when it calls `connect_to_room` over this+ * connection, so a call's room never waits on the placements stated here.+ */+ readonly placementsNameCallRooms = false;+start(): void {void this.streamLoop();void this.beatLoop();diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.pyindex 0f7d472f7..6155b1907 100644--- a/core/switch_core/bridges/agent/api/operations.py+++ b/core/switch_core/bridges/agent/api/operations.py@@ -214,6 +214,7 @@ async def resolve_caller(host_id=host_id or "",epoch=epoch or "",room_id=protocol.connections.session_room(agent_id, session_id),+ placed_by_controller=False,)# Derived, never taken on trust: a connection belonging to another agent,@@ -255,7 +256,9 @@ async def resolve_controller_caller(raise HTTPException(status_code=404, detail=str(exc)) from excexcept PermissionError as exc:raise HTTPException(status_code=403, detail=str(exc)) from exc- return holder, CallerSession(id=holder, host_id="", epoch="", room_id=room_id)+ return holder, CallerSession(+ id=holder, host_id="", epoch="", room_id=room_id, placed_by_controller=True+ )router = APIRouter(prefix="/agents", tags=["operations"])diff --git a/core/switch_core/bridges/agent/operations/callctx.py b/core/switch_core/bridges/agent/operations/callctx.pyindex ef3083021..4e83ffa1f 100644--- a/core/switch_core/bridges/agent/operations/callctx.py+++ b/core/switch_core/bridges/agent/operations/callctx.py@@ -43,12 +43,19 @@ class CallerSession:The fence travels with it so an operation that *changes* the binding writesit back through the same guarded path the door read it through, instead ofa second, weaker way into the session row.++ `placed_by_controller` is set when an agent controller named the room+ (`X-Switch-Room-Id`) rather than Switch recording it. Switch keeps no+ record of such a session, so a call naming no room means the controller+ had none for it, which is a different fault to report than a session that+ never connected."""id: strhost_id: strepoch: strroom_id: str | None+ placed_by_controller: bool@dataclass(frozen=True)diff --git a/core/switch_core/bridges/agent/operations/context.py b/core/switch_core/bridges/agent/operations/context.pyindex a6a50a02a..1d00efe96 100644--- a/core/switch_core/bridges/agent/operations/context.py+++ b/core/switch_core/bridges/agent/operations/context.py@@ -136,6 +136,14 @@ def sole_connected_room(rooms: set[str]) -> str:set as well and must not pay for reading it twice."""if not rooms:+ caller = caller_session()+ if caller is not None and caller.placed_by_controller:+ raise ValueError(+ "Not connected to a room: the agent controller running this agent "+ "named no room for this session, so it has no record of the "+ "session connecting to one. Call connect_to_room again; if this "+ "keeps happening, the agent controller's log says why."+ )raise ValueError("Not connected to a room. Call connect_to_room first.")if len(rooms) > 1:raise ValueError(diff --git a/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py b/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.pyindex 4759e9e5e..3b7659b64 100644--- a/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py+++ b/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py@@ -311,6 +311,7 @@ async def test_a_read_that_lands_after_losing_the_room_clears_nothing(host_id="host-1",epoch="epoch-1",room_id=CONNECTED_ROOM,+ placed_by_controller=False,),))@@ -354,6 +355,7 @@ async def test_a_session_reading_after_a_restart_takes_its_rooms_count(host_id="host-1",epoch="epoch-1",room_id=CONNECTED_ROOM,+ placed_by_controller=False,),))diff --git a/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.py b/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.pyindex 70f78fc8a..774b699a3 100644--- a/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.py+++ b/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.py@@ -86,7 +86,11 @@ async def test_a_session_takes_the_seat_in_its_own_name(holders) -> None:agent_id=AGENT,session_key=CONNECTION,session=CallerSession(- id="session-a", host_id="host-1", epoch="epoch-1", room_id=ROOM+ id="session-a",+ host_id="host-1",+ epoch="epoch-1",+ room_id=ROOM,+ placed_by_controller=False,),)with call_context(context):diff --git a/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.py b/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.pyindex d189db494..7f767fb3c 100644--- a/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.py+++ b/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.py@@ -56,7 +56,11 @@ def _caller(session_id: str, room_id: str | None) -> CallContext:agent_id=AGENT,session_key=CONNECTION,session=CallerSession(- id=session_id, host_id=HOST, epoch=EPOCH, room_id=room_id+ id=session_id,+ host_id=HOST,+ epoch=EPOCH,+ room_id=room_id,+ placed_by_controller=False,),)diff --git a/core/tests/switch_core/management/test_act_as.py b/core/tests/switch_core/management/test_act_as.pyindex b0301f13c..6db094e92 100644--- a/core/tests/switch_core/management/test_act_as.py+++ b/core/tests/switch_core/management/test_act_as.py@@ -485,6 +485,10 @@ class TestOperationsTakeTheRoomFromTheHeader:assert unknown.status_code == 404assert missing.status_code == 400assert "Not connected to a room" in missing.json()["detail"]+ assert (+ "agent controller running this agent named no room"+ in (missing.json()["detail"])+ )async def test_connect_to_room_checks_membership_and_claims_nothing(self, harness: Harness@@ -519,7 +523,13 @@ class TestOperationsTakeTheRoomFromTheHeader:context = CallContext(agent_id=agent_id,session_key=holder,- session=CallerSession(id=holder, host_id="", epoch="", room_id=None),+ session=CallerSession(+ id=holder,+ host_id="",+ epoch="",+ room_id=None,+ placed_by_controller=True,+ ),)previous = op_context._protocolop_context.init_operations_protocol(protocol)