Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix: a chat deleted under an agent's session no longer silences the agent everywhere

raullopez-sandbox7b7655125c55
diff --git a/console/packages/agent-controller/src/agent-hub.test.ts b/console/packages/agent-controller/src/agent-hub.test.ts
index c34dec8a8..c06e36946 100644
--- a/console/packages/agent-controller/src/agent-hub.test.ts
+++ b/console/packages/agent-controller/src/agent-hub.test.ts
@@ -5,7 +5,8 @@ import type {
SessionCommand,
SwitchEventStreamDeps,
} from '@sandboxaq/switch-agent-runtime';
-import { beforeEach, describe, expect, it } from 'vitest';
+import type { AgentStreamDeps } from '@switch-console/agent-providers';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentHub } from './agent-hub';
import { silentLogger } from './log';
import type { AgentEventFrame } from './schemas';
@@ -48,7 +49,7 @@ beforeEach(() => {
});
/** A watcher as `runAgentHost` opens its stream, recording what it hears. */
-function watcher(overrides: Partial<SwitchEventStreamDeps> = {}) {
+function watcher(overrides: Partial<AgentStreamDeps> = {}) {
const seen = {
events: [] as AgentBridgeEvent[],
gaps: [] as Parameters<SwitchEventStreamDeps['onGap']>[0][],
@@ -274,14 +275,47 @@ describe('placements', () => {
expect(hub.roomFor(AGENT, 'session-1')).toBeNull();
});
- it('refuses a room the agent is not in, and one room for two sessions', async () => {
+ it('places the sessions in rooms the agent is in, leaving out and naming one that is gone, every time', async () => {
+ const warn = vi.spyOn(silentLogger, 'warn');
hub.streamAttached();
hub.attach(AGENT, 0, ['room-a']);
const { stream } = watcher();
stream.start();
- await expect(stream.replacePlacements({ 'session-1': 'room-z' })).rejects.toThrow(
- /not a member of room room-z/
+ for (let i = 0; i < 3; i++) {
+ // A session left placed in a room since deleted, beside one in a live room.
+ await expect(
+ stream.replacePlacements({ 'session-old': 'room-deleted', 'session-1': 'room-a' })
+ ).resolves.toEqual({ refusedRooms: ['room-deleted'] });
+ // The live session's room tools carry its room.
+ expect(hub.roomFor(AGENT, 'session-1')).toBe('room-a');
+ expect(hub.roomFor(AGENT, 'session-old')).toBeNull();
+ }
+ // Said once for the room, not on every statement.
+ expect(warn.mock.calls.filter(([message]) => String(message).includes('not in'))).toHaveLength(
+ 1
);
+ warn.mockRestore();
+ });
+
+ it('tells the agent host when a room a session is placed in stops being the agent’s', async () => {
+ hub.streamAttached();
+ hub.attach(AGENT, 0, ['room-a', 'room-b']);
+ const gone: { roomId: string; sessionId: string }[] = [];
+ const { stream } = watcher({ onRoomGone: (info) => void gone.push(info) });
+ stream.start();
+ await stream.replacePlacements({ 'session-1': 'room-a', 'session-2': 'room-b' });
+ // The chat in room-b was deleted: Switch's rooms for the agent no longer have it.
+ hub.setRooms(AGENT, ['room-a']);
+ expect(gone).toEqual([{ roomId: 'room-b', sessionId: 'session-2' }]);
+ expect(hub.roomFor(AGENT, 'session-2')).toBeNull();
+ expect(hub.roomFor(AGENT, 'session-1')).toBe('room-a');
+ });
+
+ it('refuses one room for two sessions', async () => {
+ hub.streamAttached();
+ hub.attach(AGENT, 0, ['room-a']);
+ const { stream } = watcher();
+ stream.start();
await expect(
stream.replacePlacements({ 'session-1': 'room-a', 'session-2': 'room-a' })
).rejects.toThrow(/more than one session/);
diff --git a/console/packages/agent-controller/src/agent-hub.ts b/console/packages/agent-controller/src/agent-hub.ts
index 6270813c6..0a00c6846 100644
--- a/console/packages/agent-controller/src/agent-hub.ts
+++ b/console/packages/agent-controller/src/agent-hub.ts
@@ -4,7 +4,7 @@ import type {
SessionCommand,
SwitchEventStreamDeps,
} from '@sandboxaq/switch-agent-runtime';
-import type { AgentEventStream } from '@switch-console/agent-providers';
+import type { AgentEventStream, AgentStreamDeps } from '@switch-console/agent-providers';
import { errorMessage, type Logger } from './log';
import type {
AgentApprovalOutcomeFrame,
@@ -50,7 +50,7 @@ type GapData = {
/** The agent host, as the stream it opened. */
type AgentHostLink = {
- deps: SwitchEventStreamDeps;
+ deps: AgentStreamDeps;
started: boolean;
/** The last sequence handed to the agent host (or skipped); null until the agent's head is known. */
cursor: number | null;
@@ -85,6 +85,8 @@ type AgentState = {
reset: { reason: string; rooms: string[] } | null;
/** Each of its sessions' room, as its agent host last stated. */
placements: Map<string, string>;
+ /** Rooms its agent host placed a session in that it is not in, each said once. */
+ refusedRooms: Set<string>;
host: AgentHostLink | null;
overflowing: boolean;
};
@@ -230,7 +232,25 @@ export class AgentHub {
}
setRooms(agentId: string, rooms: string[]): void {
- this.agent(agentId).rooms = new Set(rooms);
+ const agent = this.agent(agentId);
+ agent.rooms = new Set(rooms);
+ // A room the agent is out of (deleted, or the agent taken out), as Switch
+ // says: a session placed there no longer attends it, and its agent host
+ // forgets the placement rather than state it again and again.
+ for (const [sessionId, roomId] of [...agent.placements]) {
+ if (agent.rooms.has(roomId)) continue;
+ agent.placements.delete(sessionId);
+ this.deps.onChange();
+ const host = agent.host;
+ if (!host || host.closed) continue;
+ void Promise.resolve(host.deps.onRoomGone?.({ roomId, sessionId })).catch((error: unknown) =>
+ this.deps.log.warn('The agent host could not drop a session placement in a room it left', {
+ agentId,
+ roomId,
+ error: errorMessage(error),
+ })
+ );
+ }
}
/**
@@ -366,7 +386,7 @@ export class AgentHub {
* The stream the agent's host hears its events on. One agent host per agent:
* a newer one replaces an older still open, which hears nothing more.
*/
- open(agentId: string, deps: SwitchEventStreamDeps): AgentEventStream {
+ open(agentId: string, deps: AgentStreamDeps): AgentEventStream {
const agent = this.agent(agentId);
if (agent.host) agent.host.closed = true;
const host: AgentHostLink = {
@@ -422,19 +442,36 @@ export class AgentHub {
// Switch decides who may start a session from the agent's binding, not
// from what an agent host on this machine declares.
setSpawnCapable: () => {},
+ // A session placed in a room the agent is not in (any more: the room was
+ // deleted, or the agent taken out) is left out and named back; the rest
+ // are placed. Refusing the whole set for one gone room left every other
+ // 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;
- const rooms = Object.values(placements);
- for (const roomId of new Set(rooms))
- if (agent.rooms && !agent.rooms.has(roomId))
- throw new Error(`agent ${agentId} is not a member of room ${roomId}`);
+ if (host.closed || agent.host !== host) return { refusedRooms: [] };
+ const refusedRooms = [...new Set(Object.values(placements))]
+ .filter((roomId) => agent.rooms !== null && !agent.rooms.has(roomId))
+ .sort();
+ const kept = Object.entries(placements).filter(
+ ([, roomId]) => !refusedRooms.includes(roomId)
+ );
+ const rooms = kept.map(([, roomId]) => roomId);
const twice = [...new Set(rooms.filter((room, index) => rooms.indexOf(room) !== index))];
if (twice.length)
throw new Error(
`placements name room(s) ${twice.sort().join(', ')} for more than one session; one session of an agent acts in a room`
);
- agent.placements = new Map(Object.entries(placements));
+ for (const roomId of refusedRooms) {
+ if (agent.refusedRooms.has(roomId)) continue;
+ agent.refusedRooms.add(roomId);
+ this.deps.log.warn('Left out a session placement in a room the agent is not in', {
+ agentId,
+ roomId,
+ });
+ }
+ agent.placements = new Map(kept);
this.deps.onChange();
+ return { refusedRooms };
},
};
}
@@ -456,6 +493,7 @@ export class AgentHub {
buffer: [],
reset: null,
placements: new Map(),
+ refusedRooms: new Set(),
host: null,
overflowing: false,
};
diff --git a/console/packages/agent-controller/src/hub-socket.ts b/console/packages/agent-controller/src/hub-socket.ts
index e3ec228ad..764af2296 100644
--- a/console/packages/agent-controller/src/hub-socket.ts
+++ b/console/packages/agent-controller/src/hub-socket.ts
@@ -1,9 +1,9 @@
import { randomUUID } from 'node:crypto';
import type { IncomingMessage } from 'node:http';
import type { Duplex } from 'node:stream';
-import type { SwitchEventStreamDeps } from '@sandboxaq/switch-agent-runtime';
import {
type AgentEventStream,
+ type AgentStreamDeps,
HUB_CLOSE,
HUB_PROTOCOL,
type HubClientMessage,
@@ -109,7 +109,7 @@ export class HubSocket {
'another agent host for this agent connected to the hub'
);
this.served.set(agentId, entry);
- const streamDeps: SwitchEventStreamDeps = {
+ const streamDeps: AgentStreamDeps = {
creds: { agentId, apiEndpoint: '', token: '' },
connectionId: randomUUID(),
scope: 'all',
@@ -123,6 +123,8 @@ export class HubSocket {
onSessionCommand: (command) => request((id) => ({ type: 'session_command', id, command })),
onApprovalOutcome: (outcome) =>
request((id) => ({ type: 'approval_outcome', id, outcome })),
+ onRoomGone: ({ roomId, sessionId }) =>
+ request((id) => ({ type: 'room_gone', id, roomId, sessionId })),
onConnected: () => send({ type: 'connected' }),
onDisconnected: ({ error }) => send({ type: 'disconnected', error }),
onEvicted: () => {},
@@ -172,7 +174,7 @@ export class HubSocket {
return;
}
entry.stream.replacePlacements(message.placements).then(
- () => send({ type: 'result', id: message.id }),
+ ({ refusedRooms }) => send({ type: 'result', id: message.id, refusedRooms }),
(error: unknown) => send({ type: 'result', id: message.id, error: errorMessage(error) })
);
};
diff --git a/console/packages/agent-controller/src/relay.test.ts b/console/packages/agent-controller/src/relay.test.ts
index e41b48a4a..5797bdb81 100644
--- a/console/packages/agent-controller/src/relay.test.ts
+++ b/console/packages/agent-controller/src/relay.test.ts
@@ -16,7 +16,11 @@ import {
fetchMediaToFile,
SESSION_SELECTOR_HEADERS,
} from '@sandboxaq/switch-agent-runtime/hosted';
-import { type AgentEventStream, openHubStream } from '@switch-console/agent-providers';
+import {
+ type AgentEventStream,
+ type AgentStreamDeps,
+ openHubStream,
+} from '@switch-console/agent-providers';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import WebSocket from 'ws';
import { AgentHub } from './agent-hub';
@@ -144,7 +148,7 @@ afterEach(async () => {
type Host = ReturnType<typeof host>;
/** An agent host in a process of its own, as the shared daemon opens its stream: on the hub. */
-function host(overrides: Partial<SwitchEventStreamDeps> = {}, as = token) {
+function host(overrides: Partial<AgentStreamDeps> = {}, as = token) {
const seen = {
events: [] as AgentBridgeEvent[],
gaps: [] as Parameters<SwitchEventStreamDeps['onGap']>[0][],
@@ -314,9 +318,33 @@ describe('the hub, over the relay’s WebSocket, read by openHubStream', () => {
body: { type: 'session.reset' },
});
+ // Across the hub's socket, a room the agent is not in is named back, not refused whole.
await expect(
- agentHost.stream.replacePlacements({ 'session-1': 'room-elsewhere' })
- ).rejects.toThrow(/not a member of room room-elsewhere/);
+ agentHost.stream.replacePlacements({ 'session-1': 'room-elsewhere', 'session-2': 'room-a' })
+ ).resolves.toEqual({ refusedRooms: ['room-elsewhere'] });
+ expect(hub.roomFor(AGENT, 'session-2')).toBe('room-a');
+ });
+
+ it('lets a session post after its agent left a chat another session was placed in, repeatedly', async () => {
+ const gone: { roomId: string; sessionId: string }[] = [];
+ const agentHost = host({ onRoomGone: (info) => void gone.push(info) });
+ await connected(agentHost);
+ // The agent's earlier chat, room-b, is deleted while a session is still placed there.
+ hub.setRooms(AGENT, ['room-a']);
+ for (let i = 0; i < 2; i++) {
+ await expect(
+ agentHost.stream.replacePlacements({ 'session-old': 'room-b', 'session-1': 'room-a' })
+ ).resolves.toEqual({ refusedRooms: ['room-b'] });
+ const posted = await callOperation(caller(), 'post_message', { body: 'QA-DIRECT-OK' });
+ expect(posted.isError).toBeFalsy();
+ expect(posted.structuredContent).toMatchObject({ room_id: 'room-a' });
+ }
+
+ // A room the agent leaves while a session is placed in it is said to that agent host.
+ await agentHost.stream.replacePlacements({ 'session-1': 'room-a' });
+ hub.setRooms(AGENT, []);
+ await waitFor(() => gone.length === 1, 'the room gone');
+ expect(gone).toEqual([{ roomId: 'room-a', sessionId: 'session-1' }]);
});
it('passes approval outcomes to the agent host', async () => {
diff --git a/console/packages/agent-controller/src/runtime.test.ts b/console/packages/agent-controller/src/runtime.test.ts
index cd0133a3f..19c049b83 100644
--- a/console/packages/agent-controller/src/runtime.test.ts
+++ b/console/packages/agent-controller/src/runtime.test.ts
@@ -78,7 +78,7 @@ function openStream(agentId: string): OpenAgentStream {
announcesSessionStarts: true,
start: () => {},
setSpawnCapable: () => {},
- replacePlacements: async () => {},
+ 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.ts
index 1238d005d..b4064fd51 100644
--- a/console/packages/agent-providers/src/host/agent-host.test.ts
+++ b/console/packages/agent-providers/src/host/agent-host.test.ts
@@ -18,6 +18,7 @@ import {
supersededSessions,
withDefinitionOf,
} from './agent-host';
+import type { AgentStreamDeps } from './agent-host';
import type { Handoff } from './handoff';
import { ensureSharedProcess, type Supervision } from './launch';
import { type SessionRequest, SessionLinks } from './session-channel';
@@ -44,11 +45,14 @@ vi.mock('./session-services', async (importOriginal) => ({
GRANTS_CHECK_MS: 20,
currentServicesShape: async () => grantsNow.shape,
}));
-const streams = vi.hoisted(() => [] as SwitchEventStreamDeps[]);
+const streams = vi.hoisted(() => [] as AgentStreamDeps[]);
const declarations = vi.hoisted(() => [] as boolean[]);
/** Every placements map the watcher stated to Switch, in order. */
const published = vi.hoisted(() => [] as Record<string, string>[]);
-const placementsRefusal = vi.hoisted(() => ({ error: null as Error | null }));
+const placementsRefusal = vi.hoisted(() => ({
+ error: null as Error | null,
+ refusedRooms: [] as string[],
+}));
vi.mock('@sandboxaq/switch-agent-runtime', async (importOriginal) => {
const original = await importOriginal<typeof runtime>();
return {
@@ -62,9 +66,12 @@ vi.mock('@sandboxaq/switch-agent-runtime', async (importOriginal) => {
setSpawnCapable(capable: boolean): void {
declarations.push(capable);
}
- async replacePlacements(placements: Record<string, string>): Promise<void> {
+ async replacePlacements(
+ placements: Record<string, string>
+ ): Promise<{ refusedRooms: string[] }> {
published.push(structuredClone(placements));
if (placementsRefusal.error) throw placementsRefusal.error;
+ return { refusedRooms: placementsRefusal.refusedRooms };
}
},
};
@@ -76,6 +83,7 @@ afterEach(async () => {
declarations.length = 0;
published.length = 0;
placementsRefusal.error = null;
+ placementsRefusal.refusedRooms = [];
vi.useRealTimers();
vi.unstubAllGlobals();
supervisors.clear();
@@ -1262,7 +1270,10 @@ it('tells the room it is starting a session when its stream leaves that to it, b
announcesSessionStarts: true,
start: () => {},
setSpawnCapable: () => {},
- replacePlacements: async (placements) => void published.push(structuredClone(placements)),
+ replacePlacements: async (placements) => {
+ published.push(structuredClone(placements));
+ return { refusedRooms: [] };
+ },
};
};
@@ -2132,6 +2143,121 @@ it('starts the host of a session a failure took down, to hand it a retry', async
}
});
+it('stops stating a session placed in a room Switch says the agent is not in, and keeps the rest', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-gone-room-'));
+ roots.push(root);
+ paths.root = root;
+ const config = await spawning(root);
+ const stale = await existing(root, config);
+ const live = await existing(root, config);
+ await writeFile(
+ join(root, 'placements.json'),
+ JSON.stringify({ placements: { [stale.sessionId]: 'room-deleted', [live.sessionId]: 'room' } })
+ );
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ placementsRefusal.refusedRooms = ['room-deleted'];
+ const abort = new AbortController();
+ const run = runAgentHost(
+ root,
+ config,
+ abort.signal,
+ sessionHosts().supervision,
+ new WatcherControl(),
+ openSwitchStream
+ );
+ try {
+ await eventually(() => streams.length === 1);
+ streams[0]!.onConnected!();
+ await eventually(() => published.length >= 1);
+ placementsRefusal.refusedRooms = [];
+ await eventually(
+ async () =>
+ JSON.parse(await readFile(join(root, 'placements.json'), 'utf8')).placements[
+ stale.sessionId
+ ] === undefined
+ );
+ const before = published.length;
+ streams[0]!.onConnected!();
+ await eventually(() => published.length === before + 1);
+ expect(published.at(-1)).toEqual({ [live.sessionId]: 'room' });
+ } finally {
+ abort.abort();
+ await run;
+ }
+});
+
+it('drops a session’s placement once its room is deleted, and the live session keeps its room', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-room-deleted-'));
+ roots.push(root);
+ paths.root = root;
+ const config = await spawning(root);
+ const deleted = await existing(root, config);
+ const live = await existing(root, config);
+ await writeFile(
+ join(root, 'placements.json'),
+ JSON.stringify({
+ placements: { [deleted.sessionId]: 'room-deleted', [live.sessionId]: 'room' },
+ })
+ );
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const abort = new AbortController();
+ const run = runAgentHost(
+ root,
+ config,
+ abort.signal,
+ sessionHosts().supervision,
+ new WatcherControl(),
+ openSwitchStream
+ );
+ try {
+ await eventually(() => streams.length === 1);
+ // The controller's hub says the chat is gone, as Switch told it.
+ await streams[0]!.onRoomGone!({ roomId: 'room-deleted', sessionId: deleted.sessionId });
+ expect(JSON.parse(await readFile(join(root, 'placements.json'), 'utf8')).placements).toEqual({
+ [live.sessionId]: 'room',
+ });
+ await eventually(() => published.length >= 1);
+ expect(published.at(-1)).toEqual({ [live.sessionId]: 'room' });
+ } finally {
+ abort.abort();
+ await run;
+ }
+});
+
+it('keeps a placement when Switch could not be asked, rather than taking it for gone', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-unanswered-'));
+ roots.push(root);
+ paths.root = root;
+ const config = await spawning(root);
+ const placed = await existing(root, config);
+ await writeFile(
+ join(root, 'placements.json'),
+ JSON.stringify({ placements: { [placed.sessionId]: 'room' } })
+ );
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ placementsRefusal.error = new Error('HTTP 503');
+ const abort = new AbortController();
+ const run = runAgentHost(
+ root,
+ config,
+ abort.signal,
+ sessionHosts().supervision,
+ new WatcherControl(),
+ openSwitchStream
+ );
+ try {
+ await eventually(() => streams.length === 1);
+ streams[0]!.onConnected!();
+ await eventually(() => published.length >= 1);
+ expect(
+ JSON.parse(await readFile(join(root, 'placements.json'), 'utf8')).placements[placed.sessionId]
+ ).toBe('room');
+ } finally {
+ abort.abort();
+ await run;
+ }
+});
+
it('hands a room control to the session working in its room, when Switch names only the room', async () => {
const root = await mkdtemp(join(tmpdir(), 'shared-watch-room-control-'));
roots.push(root);
diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.ts
index 1afe2862a..a028a8136 100644
--- a/console/packages/agent-providers/src/host/agent-host.ts
+++ b/console/packages/agent-providers/src/host/agent-host.ts
@@ -650,10 +650,25 @@ export type AgentEventStream = {
readonly announcesSessionStarts: boolean;
start(): void;
setSpawnCapable(capable: boolean): void;
- replacePlacements(placements: Record<string, string>): Promise<void>;
+ /**
+ * State every session's room. The rooms named back in `refusedRooms` are
+ * ones the agent is not in (deleted, or the agent taken out): their sessions
+ * were left out, and the rest placed.
+ */
+ replacePlacements(placements: Record<string, string>): Promise<{ refusedRooms: string[] }>;
+};
+
+/**
+ * What the agent host is told on its stream. Beside the runtime's own, an
+ * agent controller's hub says when a room a session is placed in is no longer
+ * the agent's (deleted, or the agent taken out): Switch said so, so the
+ * placement goes.
+ */
+export type AgentStreamDeps = SwitchEventStreamDeps & {
+ onRoomGone?: (info: { roomId: string; sessionId: string }) => Promise<void> | void;
};
-export type OpenAgentStream = (deps: SwitchEventStreamDeps) => AgentEventStream;
+export type OpenAgentStream = (deps: AgentStreamDeps) => AgentEventStream;
/** The watcher's own connection to Switch, with the agent's credentials. */
export const openSwitchStream: OpenAgentStream = (deps) => new SwitchEventStream(deps);
@@ -780,7 +795,17 @@ export async function runAgentHost(
*/
const publish = (): Promise<void> => {
const run = async () => {
- await stream?.replacePlacements(placements.snapshot());
+ const answer = await stream?.replacePlacements(placements.snapshot());
+ // Switch or the controller said the agent is not in the room (it is gone,
+ // or the agent was taken out): a refusal naming the room, never a failure
+ // to answer. The session no longer attends it, so it is not stated again.
+ for (const roomId of answer?.refusedRooms ?? []) {
+ const lost = await placements.roomLost(roomId);
+ if (lost)
+ console.warn(
+ `Session ${lost} was placed in room ${roomId}, which this agent is no longer in; it no longer attends it.`
+ );
+ }
};
publishing = publishing.then(run, run);
return publishing;
@@ -1262,6 +1287,20 @@ export async function runAgentHost(
throw error;
});
},
+ onRoomGone: async ({ roomId, sessionId }) => {
+ pending = pending.then(async () => {
+ if (placements.roomOf(sessionId) !== roomId) return;
+ await placements.roomLost(roomId);
+ console.warn(
+ `Room ${roomId} is no longer this agent's (deleted, or the agent taken out); session ${sessionId} no longer attends it.`
+ );
+ publishQuietly();
+ });
+ return pending.catch((error: Error) => {
+ fail(error);
+ throw error;
+ });
+ },
onApprovalOutcome: async (outcome) => {
await askSession(outcome.session_id, { type: 'approvals' }, 'an approval answer', 0);
},
diff --git a/console/packages/agent-providers/src/host/hub-stream.ts b/console/packages/agent-providers/src/host/hub-stream.ts
index 9b6a1e437..b64274888 100644
--- a/console/packages/agent-providers/src/host/hub-stream.ts
+++ b/console/packages/agent-providers/src/host/hub-stream.ts
@@ -6,7 +6,7 @@ import {
type SwitchEventStreamDeps,
} from '@sandboxaq/switch-agent-runtime';
import { z } from 'zod';
-import type { AgentEventStream, OpenAgentStream } from './agent-host';
+import type { AgentEventStream, AgentStreamDeps, OpenAgentStream } from './agent-host';
/**
* The agent controller's hub, over a WebSocket on the controller's loopback
@@ -56,7 +56,8 @@ export type HubServerMessage =
| { type: 'gap'; id: number; gap: HubGap }
| { type: 'session_command'; id: number; command: SessionCommand }
| { type: 'approval_outcome'; id: number; outcome: ApprovalOutcome }
- | { type: 'result'; id: number; error?: string };
+ | { type: 'room_gone'; id: number; roomId: string; sessionId: string }
+ | { type: 'result'; id: number; error?: string; refusedRooms?: string[] };
/** Node's WebSocket, which, unlike a browser's, takes request headers. */
type HeaderedWebSocket = new (url: string, init: { headers: Record<string, string> }) => WebSocket;
@@ -82,14 +83,17 @@ class HubEventStream implements AgentEventStream {
private cursor: number | null;
private placements: Record<string, string> = {};
private nextId = 0;
- private readonly calls = new Map<number, (error: string | undefined) => void>();
+ private readonly placementCalls = new Map<
+ number,
+ (answer: { error?: string; refusedRooms?: string[] }) => void
+ >();
/** Requests are handled one at a time, in the order they came. */
private handling: Promise<void> = Promise.resolve();
private standingDown = false;
constructor(
private readonly url: string,
- private readonly deps: SwitchEventStreamDeps
+ private readonly deps: AgentStreamDeps
) {
this.cursor = deps.startCursor ?? null;
}
@@ -103,17 +107,18 @@ class HubEventStream implements AgentEventStream {
// Switch decides who may start a session from the agent's binding.
setSpawnCapable(): void {}
- async replacePlacements(placements: Record<string, string>): Promise<void> {
+ 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;
+ if (!socket || socket.readyState !== WebSocket.OPEN) return { refusedRooms: [] };
const id = ++this.nextId;
- const error = await new Promise<string | undefined>((resolve) => {
- this.calls.set(id, resolve);
+ const answer = await new Promise<{ error?: string; refusedRooms?: string[] }>((resolve) => {
+ this.placementCalls.set(id, resolve);
socket.send(JSON.stringify({ type: 'placements', id, placements }));
});
- if (error !== undefined) throw new Error(error);
+ if (answer.error !== undefined) throw new Error(answer.error);
+ return { refusedRooms: answer.refusedRooms ?? [] };
}
private async run(): Promise<void> {
@@ -180,9 +185,9 @@ class HubEventStream implements AgentEventStream {
return;
}
if (parsed.type === 'result') {
- const call = this.calls.get(parsed.id);
- this.calls.delete(parsed.id);
- call?.(parsed.error);
+ const call = this.placementCalls.get(parsed.id);
+ this.placementCalls.delete(parsed.id);
+ call?.({ error: parsed.error, refusedRooms: parsed.refusedRooms });
return;
}
this.handling = this.handling.then(() => this.handle(socket, parsed));
@@ -191,8 +196,8 @@ 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.calls.values()) call(undefined);
- this.calls.clear();
+ for (const call of this.placementCalls.values()) call({});
+ this.placementCalls.clear();
resolve({ code: event.code, reason: event.reason, helloed });
});
// A failed handshake also closes; the close says what happened.
@@ -223,6 +228,9 @@ class HubEventStream implements AgentEventStream {
case 'approval_outcome':
await deps.onApprovalOutcome?.(message.outcome);
break;
+ case 'room_gone':
+ await deps.onRoomGone?.({ roomId: message.roomId, sessionId: message.sessionId });
+ break;
}
} catch (failure) {
error = failure instanceof Error ? failure.message : String(failure);
diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.ts
index b0d93cd52..8b3cc1aca 100644
--- a/console/packages/agent-providers/src/index.ts
+++ b/console/packages/agent-providers/src/index.ts
@@ -87,6 +87,7 @@ export {
export { hostStartSources, type HostStartSource } from './host/session-start';
export {
type AgentEventStream,
+ type AgentStreamDeps,
type OpenAgentStream,
openSwitchStream,
runAgentHost,
diff --git a/console/packages/switch-agent-runtime/src/event-stream.test.ts b/console/packages/switch-agent-runtime/src/event-stream.test.ts
index a3ecf1aca..fac1e1877 100644
--- a/console/packages/switch-agent-runtime/src/event-stream.test.ts
+++ b/console/packages/switch-agent-runtime/src/event-stream.test.ts
@@ -1337,6 +1337,28 @@ describe('placements', () => {
}
});
+ it('names back the rooms Switch left out of the placements, and none from a server that does not say', async () => {
+ serve((socket) => {
+ socket.open();
+ socket.announce(4);
+ });
+ let body =
+ '{"ok":true,"refused":[{"session_id":"old","room_id":"room-deleted","reason":"gone"}]}';
+ const fetchMock = vi.fn(async (url: string) =>
+ url.includes('connection/placements') ? answer(200, body) : answer()
+ );
+ const { stream, abort } = makeStream({ rooms: [], scope: 'all' }, fetchMock);
+ try {
+ await expect(stream.replacePlacements({ old: 'room-deleted', s: 'room' })).resolves.toEqual({
+ refusedRooms: ['room-deleted'],
+ });
+ body = '{"ok":true}';
+ await expect(stream.replacePlacements({ s: 'room' })).resolves.toEqual({ refusedRooms: [] });
+ } finally {
+ abort.abort();
+ }
+ });
+
it('does not give its connection up to itself over a request answered across its own reopen', async () => {
// Seen on a real host: placements stated under incarnation 4, the stream
// reopened (to 5) before the answer came, and the answer, "taken over:
diff --git a/console/packages/switch-agent-runtime/src/event-stream.ts b/console/packages/switch-agent-runtime/src/event-stream.ts
index 3d4053dd6..792ff953d 100644
--- a/console/packages/switch-agent-runtime/src/event-stream.ts
+++ b/console/packages/switch-agent-runtime/src/event-stream.ts
@@ -719,7 +719,7 @@ export class SwitchEventStream {
* up to `PLACEMENTS_WAIT_MS` for the stream to be attached, then refuses.
* Raises on any answer but success; a takeover also stands the stream down.
*/
- async replacePlacements(placements: Record<string, string>): Promise<void> {
+ async replacePlacements(placements: Record<string, string>): Promise<{ refusedRooms: string[] }> {
if (!(await this.attached()))
throw new Error('the connection to Switch is not open, so it cannot take placements');
const generation = this.generation;
@@ -728,7 +728,9 @@ export class SwitchEventStream {
placements,
generation,
});
- if (resp.ok) return;
+ // Switch leaves out a session in a room the agent is no longer in, and
+ // names it; one from before that answers no `refused` at all.
+ if (resp.ok) return { refusedRooms: refusedRoomsOf(await resp.text()) };
const body = await resp.text();
if (
resp.status === 409 &&
@@ -1488,3 +1490,19 @@ export class SwitchEventStream {
}
}
}
+
+/** The rooms a placements answer says the agent is not in. */
+function refusedRoomsOf(body: string): string[] {
+ try {
+ const parsed = JSON.parse(body) as { refused?: { room_id?: unknown }[] };
+ return [
+ ...new Set(
+ (parsed.refused ?? [])
+ .map((each) => each.room_id)
+ .filter((room): room is string => typeof room === 'string')
+ ),
+ ];
+ } catch {
+ return [];
+ }
+}