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(agent-providers): a turn whose every post was refused tells the room so

raullopez-sandbox3273ad7314fd
diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.ts
index 6331a8c3e..dfc9dc573 100644
--- a/console/packages/agent-providers/src/host/session-host.ts
+++ b/console/packages/agent-providers/src/host/session-host.ts
@@ -107,6 +107,8 @@ export class HostedSession {
private readonly finished = new Set<string>();
private readonly roomReplies = new Set<string>();
private readonly postedTurns = new Set<string>();
+ /** Turns whose posts to the room were refused, with the last refusal. */
+ private readonly failedPosts = new Map<string, string>();
private readonly usage = new Map<string, TokenUsage[]>();
private readonly resumeOperations = new Set<string>();
private readonly queue: Command[] = [];
@@ -580,6 +582,11 @@ export class HostedSession {
if (this.activeTurn) this.postedTurns.add(this.activeTurn);
}
+ /** A post to the room in the running turn was refused: why, the last one kept. */
+ agentPostFailed(reason: string): void {
+ if (this.activeTurn) this.failedPosts.set(this.activeTurn, reason);
+ }
+
/** 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;
@@ -1089,13 +1096,18 @@ export class HostedSession {
detail: string | null
): Promise<void> {
const posted = this.postedTurns.delete(turnId);
+ const failedPost = this.failedPosts.get(turnId) ?? null;
+ this.failedPosts.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(outcome, detail);
+ // A turn whose every post was refused ended in silence as far as the room
+ // could tell: it is told that, once, unless the turn failed and says so already.
+ const body =
+ unpostedReply(outcome, detail) ?? (failedPost !== null ? postFailedReply(failedPost) : null);
if (body === null) return;
await this.inbox.append({ type: 'room-reply', commandId: turnId });
this.roomReplies.add(turnId);
@@ -1385,6 +1397,11 @@ export function unpostedReply(outcome: TurnOutcome, detail: string | null): stri
return `I finished without replying. The turn failed${reason}`;
}
+/** What the host posts for a turn whose every post to the room was refused. */
+export function postFailedReply(reason: string): string {
+ return `I couldn't post my reply here: ${cap(reason.trim(), 1000)}`;
+}
+
function cap(text: string, limit: number): string {
const characters = Array.from(text);
return characters.length <= limit
diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.ts
index e2c3dc92b..09d6a5167 100644
--- a/console/packages/agent-providers/src/host/shared-host.test.ts
+++ b/console/packages/agent-providers/src/host/shared-host.test.ts
@@ -1487,3 +1487,56 @@ it('runs a room message again on a retry asked for there, and says so when it ca
await host.stop();
}
}, 20000);
+
+it('tells the room once when every post of a turn was refused, and not when one landed', 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' && message.ask?.type !== 'room-instructions'
+ );
+ const answer = (id: number, value: unknown) =>
+ host.parent.port.emit('message', { kind: 'answer', id, ok: true, value });
+ const refused = {
+ isError: true,
+ content: [{ type: 'text', text: 'Not connected to a room. Call connect_to_room first.' }],
+ };
+ const turn = async (sequence: number) => {
+ const before = host.turns.length;
+ await host.parent.ask({ type: 'room', handoff: roomMessage(sequence, 'reply please') });
+ await until(() => expect(host.turns).toHaveLength(before + 1));
+ return host.turns.at(-1)!.turnId;
+ };
+ const post = async (result: unknown) => {
+ const before = asks().length;
+ const posting = host.channel.ask({
+ type: 'tool',
+ name: 'post_message',
+ arguments: { body: 'x' },
+ });
+ await until(() => expect(asks()).toHaveLength(before + 1));
+ answer(asks().at(-1)!.id, result);
+ await posting.catch(() => {});
+ };
+ try {
+ const silent = await turn(1);
+ await post(refused);
+ await post(refused);
+ host.emit({ type: 'turn.completed', turnId: silent, outcome: 'completed', usage: [] });
+ await until(() => expect(asks().filter((m) => m.ask.type === 'room-reply')).toHaveLength(1));
+ expect(asks().find((m) => m.ask.type === 'room-reply')!.ask).toMatchObject({
+ roomId: 'room',
+ body: "I couldn't post my reply here: Not connected to a room. Call connect_to_room first.",
+ });
+ answer(asks().find((m) => m.ask.type === 'room-reply')!.id, null);
+
+ const landed = await turn(2);
+ await post(refused);
+ await post({ content: [{ type: 'text', text: '{"event_id":"e"}' }] });
+ host.emit({ type: 'turn.completed', turnId: landed, outcome: 'completed', usage: [] });
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(asks().filter((m) => m.ask.type === 'room-reply')).toHaveLength(1);
+ } finally {
+ expect(await host.stop()).toBeNull();
+ }
+}, 20000);
diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.ts
index c931e8cbc..69c8a1c01 100644
--- a/console/packages/agent-providers/src/host/shared-host.ts
+++ b/console/packages/agent-providers/src/host/shared-host.ts
@@ -180,6 +180,22 @@ export const ROOM_POSTING_TOOLS = new Set([
'send_attachment',
]);
+/** Why a post to the room was refused, when the result is one; null for anything else. */
+export function postFailure(name: string, result: unknown): string | null {
+ if (!ROOM_POSTING_TOOLS.has(name)) return null;
+ if (typeof result !== 'object' || result === null) return null;
+ const { isError, content } = result as { isError?: unknown; content?: unknown };
+ if (isError !== true) return null;
+ const text = Array.isArray(content)
+ ? content
+ .map((part) => (part as { text?: unknown }).text)
+ .filter((part): part is string => typeof part === 'string')
+ .join(' ')
+ .trim()
+ : '';
+ return text || 'Switch refused the post.';
+}
+
/** 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;
@@ -422,6 +438,8 @@ export async function runSharedHost(
stopHearingTools =
parentChannel?.onToolAnswered((name, result) => {
if (postedToRoom(name, result)) hosted.agentPostedToRoom();
+ const failure = postFailure(name, result);
+ if (failure !== null) hosted.agentPostFailed(failure);
}) ?? null;
options.serviceNotices.attach((message) => host!.serviceFallback(message));
diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.ts
index 90f2c9aa4..70e49f46d 100644
--- a/console/packages/agent-providers/src/host/watcher-tools.ts
+++ b/console/packages/agent-providers/src/host/watcher-tools.ts
@@ -154,6 +154,16 @@ export function sessionToolAnswerer(deps: {
throw new Error(
`Session ${caller.sessionId} no longer attends room ${ask.roomId}${attended ? ` (it attends ${attended})` : ''}, so its reply was not posted there.`
);
+ // Stated again first: a reply is posted as the session, in the room Switch
+ // holds it in, and the placement it was refused on may be the reason the
+ // turn could not post itself.
+ await deps
+ .publish()
+ .catch((error: unknown) =>
+ console.warn(
+ `Could not state the session placements before posting a reply for session ${caller.sessionId}: ${error instanceof Error ? error.message : String(error)}`
+ )
+ );
const posted = await catalog.call(await context(caller), 'post_message', {
body: deps.redactions.text(ask.body),
...(ask.threadId ? { thread_id: ask.threadId } : {}),