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
A room turn that ends without the agent posting is answered by the host (#759)
Louis Amaudruz53b2b6114ff5
diff --git a/console/docs/sdk-sessions.md b/console/docs/sdk-sessions.mdindex da65797de..5c56dd808 100644--- a/console/docs/sdk-sessions.md+++ b/console/docs/sdk-sessions.md@@ -238,6 +238,18 @@ retain durable delivery identities. Room attachments are copied from authenticatserver media into session-owned storage; missing media is reported alongside themessage instead of silently dropping the text.+A turn a room message started that ends without the agent posting to a room — a+provider quota or sign-in error, or a model that answered in plain text — is+answered by the host itself, as the agent, in the message's thread: the agent's+last words (up to 4,000 characters), or that it finished without replying and why+the turn failed. A post is a successful call to one of the Switch tools that+write into a room (`ROOM_POSTING_TOOLS` in `shared-host.ts`), seen as it passes+through the session's own MCP server, so it is recognised the same way for every+provider. The decision is recorded in the session's `inbox.jsonl` before the post,+so a turn is answered at most once, across restarts too. A turn the host stops+itself (a stop, parking, a reset) is not answered, and a post that fails is logged+and noted in the transcript without affecting the session.+Attachment hashes are stored at upload and checked during download and staging.Deleting the SDK session also removes its attachment blobs. Older uploads withouta stored digest receive transport checks but have no original-upload integrity proof.diff --git a/console/packages/agent-providers/src/host/session-channel.ts b/console/packages/agent-providers/src/host/session-channel.tsindex 262e0cdf1..cbb483ffa 100644--- a/console/packages/agent-providers/src/host/session-channel.ts+++ b/console/packages/agent-providers/src/host/session-channel.ts@@ -32,7 +32,8 @@ export const HOST_HUNG_UP_MS = 15000;* requests (`ready`). The other way round, the host says which session it is* (`identity`, again whenever its generation moves) and asks its parent* (`ask`) for what only the holder of the agent's connection can do: list the- * Switch tools and run one. The parent answers (`answer`).+ * Switch tools, run one, and post a turn's reply the agent left unposted. The+ * parent answers (`answer`).*/export const sessionRequestSchema = z.discriminatedUnion('type', [@@ -70,6 +71,17 @@ export const hostAskSchema = z.discriminatedUnion('type', [name: z.string().min(1),arguments: z.record(z.string(), z.unknown()),}),+ /**+ * The host's own post, as the agent, to the room a turn was started from:+ * the turn ended without the agent posting there. Refused unless the session+ * still attends `roomId`.+ */+ z.object({+ type: z.literal('room-reply'),+ roomId: z.string().min(1),+ threadId: z.string().min(1).nullable(),+ body: z.string().min(1),+ }),]);export type HostAsk = z.infer<typeof hostAskSchema>;@@ -577,6 +589,11 @@ export type ParentChannel = {identify: (identity: HostIdentity) => void;/** Ask the parent, rejecting if it does not answer or goes away. */ask: (ask: HostAsk) => Promise<unknown>;+ /**+ * Hear each Switch tool call the parent answered, with its result, before+ * the caller does. Returns the unsubscribe.+ */+ onToolAnswered: (listener: (name: string, result: unknown) => void) => () => void;/** Say whether the session is busy, and why; `barrier` answers a `busyBarrier`. */busy: (state: BusyState, barrier: number | null) => void;/** Answer each `busyBarrier` with this, once it resolves. */@@ -604,6 +621,7 @@ export function connectParent(port: ParentPort): ParentChannel {let barrier: (() => Promise<BusyState>) | null = null;let serving = true;let nextAsk = 0;+ const toolListeners = new Set<(name: string, result: unknown) => void>();const asks = new Map<number,{@@ -683,10 +701,25 @@ export function connectParent(port: ParentPort): ParentChannel {asks.delete(id);reject(new Error('The parent process did not answer in time.'));}, ASK_TIMEOUT_MS);- asks.set(id, { resolve, reject, timer });+ const answered = (value: unknown) => {+ if (ask.type === 'tool')+ for (const listener of toolListeners) {+ try {+ listener(ask.name, value);+ } catch (error) {+ console.error(`A tool-call listener failed: ${String(error)}`);+ }+ }+ resolve(value);+ };+ asks.set(id, { resolve: answered, reject, timer });send({ kind: 'ask', id, ask });});},+ onToolAnswered: (listener) => {+ toolListeners.add(listener);+ return () => toolListeners.delete(listener);+ },close: () => {serving = false;},diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.tsindex 5f1aab5b1..5e9505736 100644--- a/console/packages/agent-providers/src/host/session-host.test.ts+++ b/console/packages/agent-providers/src/host/session-host.test.ts@@ -1,12 +1,12 @@import { randomUUID } from 'node:crypto';-import { appendFile, mkdtemp, rm } from 'node:fs/promises';+import { appendFile, mkdtemp, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import type { Command, Session } from '@switch-console/shared/session-v1';+import type { Command, Session, Snapshot } from '@switch-console/shared/session-v1';import { afterEach, expect, it, vi } from 'vitest';import { ProviderConversationUnavailableError, type ProviderAdapter } from '../adapter';import type { ProviderRuntimeEvent } from '../events';-import { HostedSession } from './session-host';+import { HostedSession, lastAssistantText, type RoomReply, unpostedReply } from './session-host';const roots: string[] = [];const hosts: HostedSession[] = [];@@ -1210,3 +1210,223 @@ it('starts a conversation on recovery when the first start never opened one', as);await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));});++function roomMessage(commandId: string, threadId: string | null): Command {+ return {+ ...message(commandId),+ origin: {+ actorId: '@person:test',+ surface: 'switch-web',+ roomId: 'room',+ threadId,+ messageId: `message-${commandId}`,+ },+ };+}++/** A host that can post to its rooms, through `reply`. */+async function startReplying(+ reply: (reply: RoomReply) => Promise<void>,+ root?: string+): Promise<Awaited<ReturnType<typeof start>>> {+ const dir = root ?? (await mkdtemp(join(tmpdir(), 'sdk-host-test-')));+ if (!root) roots.push(dir);+ const fixture = setup('cursor');+ const host = await HostedSession.start(+ dir,+ { ...fixture.config, replyToRoom: reply },+ fixture.adapter+ );+ hosts.push(host);+ await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));+ return { ...fixture, root: dir, host };+}++function said(+ emit: (event: Record<string, unknown>) => void,+ turnId: string,+ id: string,+ text: string+) {+ emit({+ type: 'item.completed',+ turnId,+ item: { id, type: 'assistant_message', status: 'completed', title: '', text },+ });+}++async function roomReplyRecords(root: string): Promise<unknown[]> {+ return (await readFile(join(root, 'inbox.jsonl'), 'utf8'))+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line))+ .filter((record) => record.type === 'room-reply');+}++it('posts the last words of a room turn that ended without posting, once, in its thread', async () => {+ const reply = vi.fn(async (_reply: RoomReply) => {});+ const { host, emit, root, adapter } = await startReplying(reply);+ await host.command(roomMessage('turn', 'thread'));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());+ said(emit, 'turn', 'first', 'Let me look.');+ said(emit, 'turn', 'last', ' Upgrade your plan to continue ');+ emit({ type: 'turn.completed', turnId: 'turn', outcome: 'completed', usage: [] });+ await vi.waitFor(() =>+ expect(host.snapshot().notices.map((notice) => notice.code)).toContain('ROOM_REPLY_POSTED')+ );+ expect(reply).toHaveBeenCalledExactlyOnceWith({+ roomId: 'room',+ threadId: 'thread',+ body: 'I finished without posting a reply. My last words were:\n\nUpgrade your plan to continue',+ });+ expect(await roomReplyRecords(root)).toEqual([{ type: 'room-reply', commandId: 'turn' }]);++ await host.shutdown();+ const again = vi.fn(async (_reply: RoomReply) => {});+ const recovered = await startReplying(again, root);+ await recovered.host.barrier();+ expect(again).not.toHaveBeenCalled();+ expect(await roomReplyRecords(root)).toHaveLength(1);+});++it('leaves a room turn alone when the agent posted to the room during it', async () => {+ const reply = vi.fn(async (_reply: RoomReply) => {});+ const { host, emit, adapter } = await startReplying(reply);+ await host.command(roomMessage('posted', null));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());+ host.agentPostedToRoom();+ said(emit, 'posted', 'done', 'Posted the answer.');+ emit({ type: 'turn.completed', turnId: 'posted', outcome: 'completed', usage: [] });+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));+ // A post counts for the turn it was made in, not the next one.+ await host.command(roomMessage('silent', null));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));+ emit({ type: 'turn.completed', turnId: 'silent', outcome: 'completed', usage: [] });+ await vi.waitFor(() => expect(reply).toHaveBeenCalledOnce());+ expect(reply).toHaveBeenCalledWith({+ roomId: 'room',+ threadId: null,+ body: 'I finished without replying.',+ });+});++it('tells the room a failed turn with nothing to show failed, and why', async () => {+ const reply = vi.fn(async (_reply: RoomReply) => {});+ const { host, emit, adapter } = await startReplying(reply);+ await host.command(roomMessage('failed', 'thread'));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());+ emit({+ type: 'turn.completed',+ turnId: 'failed',+ outcome: 'error',+ message: 'Not signed in.',+ usage: [],+ });+ await vi.waitFor(() => expect(reply).toHaveBeenCalledOnce());+ expect(reply).toHaveBeenCalledWith({+ roomId: 'room',+ threadId: 'thread',+ body: 'I finished without replying. The turn failed: Not signed in.',+ });+});++it('tells the room a turn that never reached the provider failed', async () => {+ const reply = vi.fn(async (_reply: RoomReply) => {});+ const { host, adapter } = await startReplying(reply);+ vi.mocked(adapter.sendTurn).mockRejectedValueOnce(new Error('quota exhausted'));+ await host.command(roomMessage('unsent', null));+ await vi.waitFor(() => expect(reply).toHaveBeenCalledOnce());+ expect(reply.mock.calls[0]![0].body).toBe(+ 'I finished without replying. The turn failed: Error: quota exhausted'+ );+});++it('posts nothing for a turn no room message started', async () => {+ const reply = vi.fn(async (_reply: RoomReply) => {});+ const { host, emit, adapter } = await startReplying(reply);+ await host.command(message('console'));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());+ said(emit, 'console', 'answer', 'Here you go.');+ emit({ type: 'turn.completed', turnId: 'console', outcome: 'completed', usage: [] });+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));+ await host.barrier();+ expect(reply).not.toHaveBeenCalled();+});++it('posts nothing for a room turn the host stopped', async () => {+ const reply = vi.fn(async (_reply: RoomReply) => {});+ const { host, emit, adapter } = await startReplying(reply);+ await host.command(roomMessage('cut', null));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());+ vi.mocked(adapter.stopSession).mockImplementationOnce(async () => {+ emit({ type: 'turn.completed', turnId: 'cut', outcome: 'interrupted', usage: [] });+ emit({ type: 'session.exited', reason: 'Stopped' });+ });+ await host.command({ ...message('stop'), body: { type: 'session.stop' } });+ await vi.waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));+ expect(reply).not.toHaveBeenCalled();+});++it('keeps the session working when the room reply cannot be posted', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const reply = vi.fn(async (_reply: RoomReply) => {+ throw new Error('Switch refused post_message');+ });+ const { host, emit, adapter } = await startReplying(reply);+ await host.command(roomMessage('first', null));+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());+ emit({ type: 'turn.completed', turnId: 'first', outcome: 'completed', usage: [] });+ await vi.waitFor(() =>+ expect(host.snapshot().notices.map((notice) => notice.code)).toContain('ROOM_REPLY_FAILED')+ );+ expect(+ warn.mock.calls.some(([line]) => String(line).includes('Switch refused post_message'))+ ).toBe(true);+ expect((await host.command(message('second'))).status).toBe('applied');+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));+ expect(host.snapshot().session.status).toBe('ready');+ warn.mockRestore();+});++it('reads the last thing the agent said in a turn, whole', () => {+ const item = (itemId: string, turnId: string, text: string, kind = 'assistant-message') => ({+ itemId,+ turnId,+ revision: 1,+ kind,+ status: 'completed',+ title: '',+ text,+ attachments: [],+ origin: null,+ });+ const snapshot = {+ items: [+ item('a', 'turn', 'First.'),+ item('b', 'turn', 'Long '),+ item('tool', 'turn', '', 'tool-activity'),+ item('b:part:1', 'turn', 'answer'),+ item('c', 'turn', ' '),+ item('d', 'other', 'Another turn.'),+ ],+ } as unknown as Snapshot;+ expect(lastAssistantText(snapshot, 'turn')).toBe('Long answer');+ expect(lastAssistantText(snapshot, 'missing')).toBe('');+});++it('caps what a room reply quotes and adds the failure the text does not already say', () => {+ const long = unpostedReply('x'.repeat(5000), 'completed', null);+ expect(long.endsWith('x…')).toBe(true);+ expect(long.length).toBe(+ 'I finished without posting a reply. My last words were:\n\n'.length + 4000+ );+ expect(+ unpostedReply('Upgrade your plan to continue', 'error', 'Upgrade your plan to continue')+ ).toBe(+ 'I finished without posting a reply. My last words were:\n\nUpgrade your plan to continue'+ );+ expect(unpostedReply('Halfway there', 'interrupted', 'Stopped by a person')).toBe(+ 'I finished without posting a reply. My last words were:\n\nHalfway there\n\n(The turn was interrupted: Stopped by a person)'+ );+ expect(unpostedReply('', 'error', null)).toBe('I finished without replying. The turn failed.');+});diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex 15c358ae3..346752121 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -21,7 +21,7 @@ import type {import { z } from 'zod';import { ProviderConversationUnavailableError } from '../adapter';import type { ProviderAdapter, ProviderSessionStartInput, TurnAttachment } from '../adapter';-import type { TokenUsage, UserInputAnswers } from '../events';+import type { TokenUsage, TurnOutcome, UserInputAnswers } from '../events';import type { ProviderRuntimeEvent } from '../events';import { ChatProjector } from '../session-v1/chat-projector';import { ATTACHMENT_MIME_TYPES } from './attachments';@@ -52,6 +52,8 @@ export const hostInboxRecordSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('reset-started') }),z.object({ type: z.literal('reset-completed') }),z.object({ type: z.literal('model'), id: z.string(), options: z.record(z.string(), z.string()) }),+ /** The host posts this turn's reply to its room itself: decided once, before posting. */+ z.object({ type: z.literal('room-reply'), commandId: z.string() }),]);type RecordEntry = z.infer<typeof hostInboxRecordSchema>;export type HostSessionStart = {@@ -62,7 +64,14 @@ export type HostSessionStart = {epochAuthority?: 'server';resetEpoch?: () => Promise<string>;stageAttachments?: (attachments: Attachment[]) => Promise<TurnAttachment[]>;+ /**+ * Posts to a room as the agent, raising when the post did not land. Absent+ * where the host has no way to reach the agent's rooms.+ */+ replyToRoom?: (reply: RoomReply) => Promise<void>;};+/** What the host posts for a turn a room message started that ended without the agent posting. */+export type RoomReply = { roomId: string; threadId: string | null; body: string };type PendingQuestion = { request: Request; options: Map<string, string> };/*** What Switch recorded for a request: for an approval, `answer` is the chosen@@ -85,6 +94,8 @@ export class HostedSession {private readonly commands = new Map<string, Command>();private readonly dispatched = new Set<string>();private readonly finished = new Set<string>();+ private readonly roomReplies = new Set<string>();+ private readonly postedTurns = new Set<string>();private readonly usage = new Map<string, TokenUsage[]>();private readonly resumeOperations = new Set<string>();private readonly queue: Command[] = [];@@ -158,6 +169,7 @@ export class HostedSession {}if (record.type === 'reset-completed') this.resetPending = false;if (record.type === 'model') config.input.model = { id: record.id, options: record.options };+ if (record.type === 'room-reply') this.roomReplies.add(record.commandId);}this.projector = new ChatProjector(config.session);this.unsubscribe = adapter.subscribe((event) => {@@ -489,6 +501,14 @@ export class HostedSession {return this.usage.get(turnId) ?? [];}+ /**+ * The agent posted to a room, through one of the Switch tools: the running+ * turn has answered, so the host has nothing to post for it.+ */+ agentPostedToRoom(): void {+ if (this.activeTurn) this.postedTurns.add(this.activeTurn);+ }+/** Where the command that started `turnId` came from, if a command started it. */originOf(turnId: string): Origin | null {return this.commands.get(turnId)?.origin ?? null;@@ -944,11 +964,65 @@ export class HostedSession {code: 'TURN_FAILED',message: String(error),});+ await this.replyIfUnposted(command.commandId, 'error', String(error));this.activeTurn = null;void this.runNext().catch((error: unknown) => this.fail(error));}}+ /**+ * Answers the room itself when a turn a room message started ended without+ * the agent posting anywhere — a provider that ended on a quota or sign-in+ * error, or a model that replied in plain text — since the room would+ * otherwise hear nothing at all. A turn the host cut short on purpose+ * (stopping, parking, a reset) is left alone.+ *+ * Decided once per turn and recorded before the post, so a restart never+ * posts it twice. The post runs beside the session; one that fails is+ * logged and noted in the transcript, and nothing else.+ */+ private async replyIfUnposted(+ turnId: string,+ outcome: TurnOutcome,+ detail: string | null+ ): Promise<void> {+ const posted = this.postedTurns.delete(turnId);+ const reply = this.config.replyToRoom;+ if (!reply || posted || this.shuttingDown || this.stopped || this.resetting) return;+ if (this.roomReplies.has(turnId)) return;+ const origin = this.commands.get(turnId)?.origin;+ if (!origin?.roomId || !origin.messageId) return;+ const roomId = origin.roomId;+ const body = unpostedReply(lastAssistantText(this.replica.snapshot(), turnId), outcome, detail);+ await this.inbox.append({ type: 'room-reply', commandId: turnId });+ this.roomReplies.add(turnId);+ void reply({ roomId, threadId: origin.threadId, body })+ .then(+ () =>+ this.publish({+ type: 'notice',+ level: 'info',+ code: 'ROOM_REPLY_POSTED',+ message: `The turn ended without the agent posting to room ${roomId}, so the host posted there for it.`,+ }),+ async (error: unknown) => {+ const reason = error instanceof Error ? error.message : String(error);+ console.warn(+ `Could not tell room ${roomId} that turn ${turnId} ended without a reply: ${reason}`+ );+ await this.publish({+ type: 'notice',+ level: 'warning',+ code: 'ROOM_REPLY_FAILED',+ message: `The turn ended without the agent posting to room ${roomId}, and the host could not post there for it: ${reason}`,+ });+ }+ )+ .catch((error: unknown) =>+ console.warn(`Could not record the room reply for turn ${turnId}: ${String(error)}`)+ );+ }+private async providerEvent(event: ProviderRuntimeEvent): Promise<void> {// A reset stops the old conversation on the way to a fresh one. That stop// is not the session's: shown, it reads as the session ending.@@ -1062,6 +1136,7 @@ export class HostedSession {}await this.publishAll(this.projector.ingest(event, Date.now()));if (event.type === 'turn.completed') {+ await this.replyIfUnposted(event.turnId, event.outcome, event.message ?? null);this.activeTurn = null;void this.runNext().catch((error: unknown) => this.fail(error));}@@ -1179,6 +1254,53 @@ export class HostedSession {}}+/** How much of the agent's last words a room reply carries. */+const ROOM_REPLY_LIMIT = 4000;++/** The text of the last thing the agent said in `turnId`, trimmed; empty when it said nothing. */+export function lastAssistantText(snapshot: Snapshot, turnId: string): string {+ // A long message is published in parts, `<itemId>:part:<n>` after the first.+ const messages = new Map<string, string[]>();+ for (const item of snapshot.items) {+ if (item.turnId !== turnId || item.kind !== 'assistant-message') continue;+ const part = /^(.*):part:(\d+)$/.exec(item.itemId);+ const id = part ? part[1]! : item.itemId;+ const parts = messages.get(id) ?? [];+ parts[part ? Number(part[2]) : 0] = item.text;+ messages.set(id, parts);+ }+ for (const parts of [...messages.values()].reverse()) {+ const text = parts.join('').trim();+ if (text) return text;+ }+ return '';+}++/** What the host posts for a turn that ended without the agent posting. */+export function unpostedReply(text: string, outcome: TurnOutcome, detail: string | null): string {+ const reason = detail?.trim() ? `: ${cap(detail.trim(), 1000)}` : '.';+ const failure =+ outcome === 'error'+ ? `The turn failed${reason}`+ : outcome === 'interrupted'+ ? `The turn was interrupted${reason}`+ : null;+ if (!text)+ return failure ? `I finished without replying. ${failure}` : 'I finished without replying.';+ const said = `I finished without posting a reply. My last words were:\n\n${cap(text, ROOM_REPLY_LIMIT)}`;+ return failure && !(detail && text.includes(detail.trim())) ? `${said}\n\n(${failure})` : said;+}++function cap(text: string, limit: number): string {+ const characters = Array.from(text);+ return characters.length <= limit+ ? text+ : `${characters+ .slice(0, limit - 1)+ .join('')+ .trimEnd()}…`;+}+type QuestionsContent = Extract<Request['content'], { kind: 'questions' }>;/** Throws INVALID_ANSWER unless `answers` answers every question once, with what it offers. */diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex 1743329a0..cdc92e9ea 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -12,7 +12,7 @@ import {} from '../adapter';import type { ProviderRuntimeEvent } from '../events';import { stubSwitchFetch } from '../testing/agent-sessions-server';-import { connectParent } from './session-channel';+import { connectParent, type ParentChannel } from './session-channel';import { parkAfterMs, RESET_HOLD_MS, runSharedHost, sessionBusy } from './shared-host';import { hostParked } from './shared-state';@@ -89,6 +89,8 @@ type Harness = {switchCore: ReturnType<typeof stubSwitchFetch>;media: Map<string, Uint8Array>;parent: ReturnType<typeof fakeParent>;+ /** The host's end of the pipe, as its Switch tools use it. */+ channel: ParentChannel;stop: () => Promise<unknown>;snapshotEpoch: () => Promise<string>;};@@ -261,6 +263,7 @@ async function start(const session = structuredClone(SESSION);if (opts.rooms) session.capabilities.attachmentMimeTypes = ['text/plain'];if (opts.resettable) session.capabilities.reset = true;+ const channel = connectParent(parent.port);const running = runSharedHost({root,@@ -275,7 +278,7 @@ async function start(mcpServers: {},},...(opts.rooms ? { roomConnection: { connectionId: 'controller' } } : {}),- parent: connectParent(parent.port),+ parent: channel,parkAfterMs: opts.parkAfterMs ?? null,instructions: opts.instructions ?? null,},@@ -313,6 +316,7 @@ async function start(switchCore,media,parent,+ channel,stop: async () => {stop.abort();return outcome;@@ -1242,3 +1246,67 @@ it('keeps the session running when the start record cannot even be removed', asyexpect(await host.stop()).toBeNull();}}, 20000);++it('posts for a room turn that ended without the agent posting, and not for one that posted', async () => {+ const host = await start({ rooms: true });+ const asks = () =>+ host.parent.sent.filter(+ (message): message is typeof message & { id: number; ask: Record<string, unknown> } =>+ message.kind === 'ask'+ );+ const answer = (id: number, value: unknown) =>+ host.parent.port.emit('message', { kind: 'answer', id, ok: true, value });+ const turn = async (sequence: number) => {+ const before = host.turns.length;+ expect(+ await host.parent.ask({ type: 'room', handoff: roomMessage(sequence, 'hi') })+ ).toMatchObject({ ok: true });+ await vi.waitFor(() => expect(host.turns).toHaveLength(before + 1), { timeout: 5000 });+ return host.turns.at(-1)!.turnId;+ };+ try {+ const silent = await turn(1);+ host.emit({+ type: 'item.completed',+ turnId: silent,+ item: {+ id: 'a',+ type: 'assistant_message',+ status: 'completed',+ title: '',+ text: 'Hello there',+ },+ });+ host.emit({ type: 'turn.completed', turnId: silent, outcome: 'completed', usage: [] });+ await vi.waitFor(() => expect(asks()).toHaveLength(1), { timeout: 5000 });+ expect(asks()[0]!.ask).toEqual({+ type: 'room-reply',+ roomId: 'room',+ threadId: null,+ body: 'I finished without posting a reply. My last words were:\n\nHello there',+ });+ answer(asks()[0]!.id, null);++ const answered = await turn(2);+ // The provider's Switch tool call, as the session's MCP server makes it.+ const posting = host.channel.ask({+ type: 'tool',+ name: 'post_message',+ arguments: { body: 'Hi!' },+ });+ await vi.waitFor(() => expect(asks()).toHaveLength(2));+ answer(asks()[1]!.id, { content: [{ type: 'text', text: '{"event_id":"e"}' }] });+ await posting;+ host.emit({ type: 'turn.completed', turnId: answered, outcome: 'completed', usage: [] });+ await vi.waitFor(async () => {+ const { value } = await host.parent.ask({ type: 'snapshot' });+ expect((value as Snapshot).turns.find((t) => t.turnId === answered)?.status).toBe(+ 'completed'+ );+ });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(asks()).toHaveLength(2);+ } finally {+ expect(await host.stop()).toBeNull();+ }+});diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex 110da854c..59b597739 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -126,6 +126,31 @@ export function sessionBusy(return { busy: reasons.length > 0, reasons };}+/**+ * The Switch tools that put something the agent wrote in front of a room: a+ * turn that called one of them has answered. Each posts to the room the+ * session is connected to (only `send_attachment` can name another), so a+ * call counts whichever room it reached.+ */+export const ROOM_POSTING_TOOLS = new Set([+ 'post_message',+ 'send_targeted_message',+ 'send_attachment',+ 'delegate_task',+ 'update_task',+ 'finalise_task',+]);++/** Whether a Switch tool result is a post that landed. */+export function postedToRoom(name: string, result: unknown): boolean {+ if (!ROOM_POSTING_TOOLS.has(name)) return false;+ return (+ typeof result === 'object' &&+ result !== null &&+ (result as { isError?: unknown }).isError !== true+ );+}+class TransportError extends Error {}class RequestError extends Error {constructor(@@ -186,6 +211,7 @@ export async function runSharedHost(let failure: unknown = null;let shutdown: Promise<void> | null = null;let reporting: Promise<void> | null = null;+ let stopHearingTools: (() => void) | null = null;const callOnce = async (route: string,@@ -315,9 +341,17 @@ export async function runSharedHost(return { data, sha256: createHash('sha256').update(data).digest('hex') };};+ const parentChannel = options.parent;host = await HostedSession.start(options.root,{+ ...(parentChannel && options.roomConnection+ ? {+ replyToRoom: async (reply) => {+ await parentChannel.ask({ type: 'room-reply', ...reply });+ },+ }+ : {}),session: options.session,input: options.input,resumeOperationId: options.resumeOperationId,@@ -341,6 +375,13 @@ export async function runSharedHost(},adapter);+ // Every Switch tool call the provider makes goes up this pipe, whatever+ // the provider calls the tool in its own transcript.+ const hosted = host;+ stopHearingTools =+ parentChannel?.onToolAnswered((name, result) => {+ if (postedToRoom(name, result)) hosted.agentPostedToRoom();+ }) ?? null;// ── What the host reports ────────────────────────────────────────────────const reporter = await ActivityReporter.load(options.root);@@ -858,6 +899,7 @@ export async function runSharedHost(} catch (error) {if (!signal.aborted) failure ??= error;} finally {+ stopHearingTools?.();stopped.abort();await reporting;try {diff --git a/console/packages/agent-providers/src/host/watcher-tools.test.ts b/console/packages/agent-providers/src/host/watcher-tools.test.tsindex ad7b7997e..52931f25f 100644--- a/console/packages/agent-providers/src/host/watcher-tools.test.ts+++ b/console/packages/agent-providers/src/host/watcher-tools.test.ts@@ -119,3 +119,38 @@ it('keeps telling the other listeners when one of them throws', () => {expect(error.mock.calls[0]?.[0]).toContain('broken listener');error.mockRestore();});++it('posts a session’s room reply only into the room it still attends', async () => {+ const base = await mkdtemp(join(tmpdir(), 'watcher-tools-'));+ roots.push(base);+ const placements = await SessionPlacements.open(base, () => []);+ const answer = sessionToolAnswerer({+ identity: { agentId: 'agent', apiEndpoint: 'http://127.0.0.1', token: 't' } as never,+ connectionId: 'connection',+ placements,+ publish: async () => {},+ });+ calls.connect.mockResolvedValue({ content: [{ type: 'text', text: '{"event_id":"e"}' }] });+ const session = await caller(base, 'session');+ await placements.place('session', 'room');++ await expect(+ answer(session, { type: 'room-reply', roomId: 'room', threadId: 'thread', body: 'Hello' })+ ).resolves.toBeNull();+ await answer(session, { type: 'room-reply', roomId: 'room', threadId: null, body: 'Top' });+ expect(calls.connect.mock.calls).toEqual([+ ['session', 'post_message', { body: 'Hello', thread_id: 'thread' }],+ ['session', 'post_message', { body: 'Top' }],+ ]);++ await placements.place('session', 'elsewhere');+ await expect(+ answer(session, { type: 'room-reply', roomId: 'room', threadId: null, body: 'Late' })+ ).rejects.toThrow('no longer attends room room (it attends elsewhere)');+ expect(calls.connect).toHaveBeenCalledTimes(2);++ calls.connect.mockResolvedValue({ isError: true, content: [{ type: 'text', text: 'refused' }] });+ await expect(+ answer(session, { type: 'room-reply', roomId: 'elsewhere', threadId: null, body: 'Nope' })+ ).rejects.toThrow('refused');+});diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.tsindex a71443e70..e52726b83 100644--- a/console/packages/agent-providers/src/host/watcher-tools.ts+++ b/console/packages/agent-providers/src/host/watcher-tools.ts@@ -11,7 +11,7 @@ import {} from '@sandboxaq/switch-agent-runtime/hosted';import { z } from 'zod';import type { PlacementMap, SessionPlacements } from './placements';-import type { AskHandler, Caller } from './session-channel';+import type { AskHandler, Caller, HostAsk } from './session-channel';import { sharedConfigSchema } from './shared-config';/**@@ -122,9 +122,34 @@ export function sessionToolAnswerer(deps: {};};+ /**+ * Posts, as the session, a reply its turn left unposted. Only into the room+ * the turn came from, and only while the session still attends it: a post+ * goes to whichever room the session holds, and one it has moved to since+ * did not ask.+ */+ const roomReply = async (+ caller: Caller,+ catalog: SwitchToolCatalog,+ ask: Extract<HostAsk, { type: 'room-reply' }>+ ): Promise<null> => {+ const attended = deps.placements.roomOf(caller.sessionId);+ if (attended !== ask.roomId)+ throw new Error(+ `Session ${caller.sessionId} no longer attends room ${ask.roomId}${attended ? ` (it attends ${attended})` : ''}, so its reply was not posted there.`+ );+ const posted = await catalog.call(await context(caller), 'post_message', {+ body: ask.body,+ ...(ask.threadId ? { thread_id: ask.threadId } : {}),+ });+ if (posted.isError) throw new Error(resultText(posted));+ return null;+ };+return async (caller, ask) => {const catalog = await tools();if (ask.type === 'tools') return catalog.tools();+ if (ask.type === 'room-reply') return roomReply(caller, catalog, ask);if (ask.name === 'connect_to_room') return connect(caller, catalog, ask.arguments);return catalog.call(await context(caller), ask.name, ask.arguments);};