Skip to content

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

Tell a session a room's instructions with its first message from the room

Petr Bauchdc3003549205
diff --git a/console/packages/agent-providers/src/host/session-channel.ts b/console/packages/agent-providers/src/host/session-channel.ts
index 51feb8816..9cbb1c498 100644
--- a/console/packages/agent-providers/src/host/session-channel.ts
+++ b/console/packages/agent-providers/src/host/session-channel.ts
@@ -93,6 +93,14 @@ export const hostAskSchema = z.discriminatedUnion('type', [
threadId: z.string().min(1).nullable(),
body: z.string().min(1),
}),
+ /**
+ * The room's own instructions, answered with `{ instructions }` ('' for a
+ * room with none). Refused unless the session still attends `roomId`.
+ */
+ z.object({
+ type: z.literal('room-instructions'),
+ roomId: z.string().min(1),
+ }),
/**
* A token for one of the agent's granted services, answered with a
* `ServiceTokenAnswer`. `rejected` is a token the service refused (Git
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 cc23625d3..82b323d1c 100644
--- a/console/packages/agent-providers/src/host/shared-host.test.ts
+++ b/console/packages/agent-providers/src/host/shared-host.test.ts
@@ -56,12 +56,28 @@ function fakeParent() {
error?: string;
event?: { sequence: number };
identity?: Record<string, string>;
+ ask?: { type: string; roomId?: string };
};
const sent: Sent[] = [];
+ // The controller's answer to a host asking for a room's instructions: the
+ // text, or an Error to refuse with.
+ const roomInstructions: { value: string | Error } = { value: '' };
const port = Object.assign(new EventEmitter(), {
connected: true,
send: (message: unknown) => {
- sent.push(message as Sent);
+ const sentMessage = message as Sent;
+ if (sentMessage.kind === 'ask' && sentMessage.ask?.type === 'room-instructions') {
+ const { value } = roomInstructions;
+ queueMicrotask(() =>
+ port.emit(
+ 'message',
+ value instanceof Error
+ ? { kind: 'answer', id: sentMessage.id, ok: false, error: value.message }
+ : { kind: 'answer', id: sentMessage.id, ok: true, value: { instructions: value } }
+ )
+ );
+ }
+ sent.push(sentMessage);
return true;
},
});
@@ -79,7 +95,7 @@ function fakeParent() {
);
return reply!;
};
- return { port, sent, ask };
+ return { port, sent, ask, roomInstructions };
}
type Harness = {
@@ -474,6 +490,53 @@ it('tells a running conversation once that its instructions changed, across rest
}
}, 30_000);
+it('tells a conversation a room’s instructions with its first message there, and again when they change', async () => {
+ const restart = async (host: Harness): Promise<Harness> => {
+ expect(await host.stop()).toBeNull();
+ await rm(join(host.root, 'shared-owner.lock'));
+ return start({ rooms: true, base: host.base });
+ };
+ const answer = async (host: Harness, sequence: number, body: string): Promise<string> => {
+ const before = host.turns.length;
+ expect(
+ await host.parent.ask({ type: 'room', handoff: roomMessage(sequence, body) })
+ ).toMatchObject({ ok: true });
+ await vi.waitFor(() => expect(host.turns).toHaveLength(before + 1), { timeout: 5000 });
+ const turn = host.turns.at(-1)!;
+ host.emit({ type: 'turn.completed', turnId: turn.turnId, outcome: 'completed', usage: [] });
+ return turn.text;
+ };
+
+ const first = await start({ rooms: true });
+ first.parent.roomInstructions.value = 'End every reply with -- payments-release.';
+ expect(await answer(first, 1, 'which day?')).toMatch(
+ /^\[Switch\] Room room has instructions of its own\.[\s\S]*BEGIN ROOM INSTRUCTIONS\nEnd every reply with -- payments-release\.\nEND ROOM INSTRUCTIONS\n\n\[Switch\] A Person addressed you/
+ );
+ expect(await answer(first, 2, 'and the time?')).not.toContain('ROOM INSTRUCTIONS');
+
+ first.parent.roomInstructions.value = 'Be brief.';
+ expect(await answer(first, 3, 'still there?')).toContain(
+ "[Switch] Room room's instructions were changed. From now on, follow these there instead of the ones you were given earlier:\nBEGIN ROOM INSTRUCTIONS\nBe brief.\nEND ROOM INSTRUCTIONS"
+ );
+
+ const again = await restart(first);
+ try {
+ again.parent.roomInstructions.value = 'Be brief.';
+ expect(await answer(again, 4, 'after a restart')).not.toContain('ROOM INSTRUCTIONS');
+
+ again.parent.roomInstructions.value = new Error('Switch is unreachable');
+ expect(await answer(again, 5, 'and now?')).toContain(
+ "[Switch] Room room's instructions could not be read for you (Switch is unreachable). Before you reply, call connect_to_room with room_id room"
+ );
+ again.parent.roomInstructions.value = 'Be brief.';
+ const back = await answer(again, 6, 'back?');
+ expect(back).not.toContain('ROOM INSTRUCTIONS');
+ expect(back).not.toContain('could not be read');
+ } finally {
+ expect(await again.stop()).toBeNull();
+ }
+}, 30_000);
+
it('gives a provider that takes developer messages its changed instructions as one', async () => {
const first = await start({ rooms: true, instructions: 'Speak like Yoda.' });
expect(await first.parent.ask({ type: 'room', handoff: roomMessage(1, 'hi') })).toMatchObject({
@@ -951,7 +1014,7 @@ it('tells the room at once when it refuses a compaction asked for there mid-turn
const asks = () =>
host.parent.sent.filter(
(message): message is typeof message & { id: number; ask: Record<string, unknown> } =>
- message.kind === 'ask'
+ message.kind === 'ask' && message.ask?.type !== 'room-instructions'
);
try {
expect(
@@ -1301,7 +1364,7 @@ it('posts for a room turn that ended without the agent posting, and not for one
const asks = () =>
host.parent.sent.filter(
(message): message is typeof message & { id: number; ask: Record<string, unknown> } =>
- message.kind === 'ask'
+ 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 });
diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.ts
index e7a673551..44c8ee0e8 100644
--- a/console/packages/agent-providers/src/host/shared-host.ts
+++ b/console/packages/agent-providers/src/host/shared-host.ts
@@ -53,6 +53,12 @@ import {
readToldInstructions,
recordToldInstructions,
} from './told-instructions';
+import {
+ readToldRoomInstructions,
+ recordToldRoomInstructions,
+ roomInstructionsNote,
+ roomInstructionsUnreadNote,
+} from './told-room-instructions';
import { startVendorClis } from './vendor-cli';
import {
CALL_TIMEOUT_MS,
@@ -104,6 +110,8 @@ export type SharedHostOptions = {
};
/** How long a session sits idle before its host parks, unless the environment says otherwise. */
+const roomInstructionsAnswerSchema = z.object({ instructions: z.string() });
+
const PARK_AFTER_MS = 24 * 60 * 60 * 1000;
/**
@@ -654,6 +662,39 @@ export async function runSharedHost(
`Could not give session ${options.session.sessionId} its changed instructions as a developer message (${error instanceof Error ? error.message : String(error)}); it is told with its next room message instead.`
);
}
+ // ── Telling a conversation the instructions of the rooms it is in ─────
+ let toldRooms = await readToldRoomInstructions(options.root);
+ const roomInstructionsTold = async (rooms: Record<string, string>): Promise<void> => {
+ toldRooms = rooms;
+ await recordToldRoomInstructions(options.root, rooms);
+ };
+ /**
+ * What to tell the conversation about a room's instructions before its
+ * message, and the instructions to record as told once the message runs
+ * (null when they could not be read, so the next message tries again).
+ */
+ const roomInstructionsFor = async (
+ roomId: string
+ ): Promise<{ note: string | null; instructions: string | null }> => {
+ if (!parentChannel || !options.roomConnection) return { note: null, instructions: null };
+ if (host!.snapshot().turns.length === 0) toldRooms = {};
+ try {
+ const { instructions } = roomInstructionsAnswerSchema.parse(
+ await parentChannel.ask({ type: 'room-instructions', roomId })
+ );
+ return {
+ note: roomInstructionsNote(roomId, instructions, toldRooms[roomId]),
+ instructions,
+ };
+ } catch (error) {
+ executionSignal.throwIfAborted();
+ const reason = error instanceof Error ? error.message : String(error);
+ console.warn(
+ `Could not read room ${roomId}'s instructions for session ${options.session.sessionId} (${reason}); the session is told to read them itself.`
+ );
+ return { note: roomInstructionsUnreadNote(roomId, reason), instructions: null };
+ }
+ };
/** Runs a command, answering with what the host recorded for it, or why it did not run. */
const run = async (
value: unknown,
@@ -711,9 +752,12 @@ export async function runSharedHost(
`Could not tell room ${owed.roomId} that its ${owed.action} was refused: ${String(error)}`
)
);
- // A fresh conversation starts with the instructions this host was given.
- if (command.body.type === 'session.reset' && status?.status === 'applied')
+ // A fresh conversation starts with the instructions this host was given,
+ // and has been told no room's.
+ if (command.body.type === 'session.reset' && status?.status === 'applied') {
await instructionsTold();
+ await roomInstructionsTold({});
+ }
return status ?? 'The host did not record the command.';
};
/** Turn each room message handed over into the command it amounts to, in order. */
@@ -744,6 +788,8 @@ export async function runSharedHost(
planned.refused = `It could not be fetched: ${error instanceof Error ? error.message : String(error)}.`;
}
}
+ const room = await roomInstructionsFor(event.roomId);
+ const preface = [instructionsNote, room.note].filter((note) => note !== null);
const command = roomCommand({
agentId,
sessionId: options.session.sessionId,
@@ -752,19 +798,18 @@ export async function runSharedHost(
message: message.data,
surface: 'switch-web',
attachments,
- preface: instructionsNote,
+ preface: preface.length ? preface.join('\n\n') : null,
firstOfConversation: host!.snapshot().turns.length === 0,
});
// Taken by the host before the delivery is acknowledged: the host's
// inbox is durable, so a crash between the two runs the message once
// rather than losing it.
const outcome = await run(command, null);
- if (
- instructionsNote !== null &&
- typeof outcome !== 'string' &&
- outcome.status !== 'rejected'
- )
- await instructionsTold();
+ if (typeof outcome !== 'string' && outcome.status !== 'rejected') {
+ if (instructionsNote !== null) await instructionsTold();
+ if (room.instructions !== null)
+ await roomInstructionsTold({ ...toldRooms, [event.roomId]: room.instructions });
+ }
await inbox.acknowledge(event);
}
};
diff --git a/console/packages/agent-providers/src/host/told-room-instructions.test.ts b/console/packages/agent-providers/src/host/told-room-instructions.test.ts
new file mode 100644
index 000000000..0a5d930a0
--- /dev/null
+++ b/console/packages/agent-providers/src/host/told-room-instructions.test.ts
@@ -0,0 +1,52 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ readToldRoomInstructions,
+ recordToldRoomInstructions,
+ roomInstructionsNote,
+ roomInstructionsUnreadNote,
+} from './told-room-instructions';
+
+const roots: string[] = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
+});
+
+describe('roomInstructionsNote', () => {
+ it('tells a room’s instructions the first time, and nothing for a room without any', () => {
+ const note = roomInstructionsNote('room-1', 'Sign every reply.', undefined);
+ expect(note).toContain('Room room-1 has instructions of its own');
+ expect(note).toContain('BEGIN ROOM INSTRUCTIONS\nSign every reply.\nEND ROOM INSTRUCTIONS');
+ expect(roomInstructionsNote('room-1', '', undefined)).toBeNull();
+ });
+
+ it('says nothing again until they change, then tells the change or the removal', () => {
+ expect(roomInstructionsNote('room-1', 'Sign every reply.', 'Sign every reply.')).toBeNull();
+ expect(roomInstructionsNote('room-1', 'Be brief.', 'Sign every reply.')).toContain(
+ "Room room-1's instructions were changed"
+ );
+ expect(roomInstructionsNote('room-1', ' ', 'Sign every reply.')).toContain(
+ "Room room-1's instructions were removed"
+ );
+ expect(roomInstructionsNote('room-1', '', '')).toBeNull();
+ });
+
+ it('tells the agent how to read them itself when they could not be read', () => {
+ expect(roomInstructionsUnreadNote('room-1', 'Switch is down')).toContain(
+ 'call connect_to_room with room_id room-1 and include_general_instructions false'
+ );
+ });
+});
+
+it('keeps what each room was told across a restart, and starts empty', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'told-room-'));
+ roots.push(root);
+ expect(await readToldRoomInstructions(root)).toEqual({});
+ await recordToldRoomInstructions(root, { 'room-1': 'Sign every reply.', 'room-2': '' });
+ expect(await readToldRoomInstructions(root)).toEqual({
+ 'room-1': 'Sign every reply.',
+ 'room-2': '',
+ });
+});
diff --git a/console/packages/agent-providers/src/host/told-room-instructions.ts b/console/packages/agent-providers/src/host/told-room-instructions.ts
new file mode 100644
index 000000000..d2ec46aa5
--- /dev/null
+++ b/console/packages/agent-providers/src/host/told-room-instructions.ts
@@ -0,0 +1,71 @@
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { z } from 'zod';
+import { replaceOwner } from './ownership-lock';
+
+const FILE = 'room-instructions.json';
+
+const recordSchema = z.strictObject({ rooms: z.record(z.string(), z.string()) });
+
+/**
+ * The room instructions a session's conversation has been told, per room, as
+ * the text it was told ('' for a room that has none).
+ *
+ * A room's instructions reach an agent in `connect_to_room`'s answer, but a
+ * session its controller started for a room message is placed in the room
+ * without that call, and can answer without ever making it. So the host tells
+ * the conversation a room's instructions with its first message from the
+ * room, and again with the next one after they change. This record is how it
+ * knows, across restarts of its host; a fresh conversation starts it empty.
+ */
+export async function readToldRoomInstructions(root: string): Promise<Record<string, string>> {
+ try {
+ return recordSchema.parse(JSON.parse(await readFile(join(root, FILE), 'utf8'))).rooms;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
+ throw error;
+ }
+}
+
+export async function recordToldRoomInstructions(
+ root: string,
+ rooms: Record<string, string>
+): Promise<void> {
+ await replaceOwner(join(root, FILE), { rooms });
+}
+
+/**
+ * What a conversation is told about a room's instructions before a message
+ * from it, or null when it already has them. `told` is what it was told for
+ * this room before, undefined if nothing.
+ */
+export function roomInstructionsNote(
+ roomId: string,
+ instructions: string,
+ told: string | undefined
+): string | null {
+ if (told === instructions) return null;
+ if (instructions.trim() === '') {
+ if (told === undefined) return null;
+ return `[Switch] Room ${roomId}'s instructions were removed. The ones you were given for it earlier no longer apply.`;
+ }
+ return (
+ (told === undefined
+ ? `[Switch] Room ${roomId} has instructions of its own. They apply to everything you do in that room, and override general defaults where they differ:\n`
+ : `[Switch] Room ${roomId}'s instructions were changed. From now on, follow these there instead of the ones you were given earlier:\n`) +
+ 'BEGIN ROOM INSTRUCTIONS\n' +
+ `${instructions}\n` +
+ 'END ROOM INSTRUCTIONS'
+ );
+}
+
+/**
+ * The note for a room whose instructions could not be read: the agent is told
+ * so, and how to read them itself, rather than answering as if there were none.
+ */
+export function roomInstructionsUnreadNote(roomId: string, reason: string): string {
+ return (
+ `[Switch] Room ${roomId}'s instructions could not be read for you (${reason}). ` +
+ `Before you reply, call connect_to_room with room_id ${roomId} and include_general_instructions false, and follow the instructions it returns.`
+ );
+}
diff --git a/console/packages/agent-providers/src/host/watcher-tools.test.ts b/console/packages/agent-providers/src/host/watcher-tools.test.ts
index 4a733c144..b6ec9f214 100644
--- a/console/packages/agent-providers/src/host/watcher-tools.test.ts
+++ b/console/packages/agent-providers/src/host/watcher-tools.test.ts
@@ -219,3 +219,52 @@ it('posts a session’s room reply only into the room it still attends', async (
answer(session, { type: 'room-reply', roomId: 'elsewhere', threadId: null, body: 'Nope' })
).rejects.toThrow('refused');
});
+
+it('reads the instructions of the room a session attends, without moving it', 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 () => {},
+ redactions: new Redactions(),
+ });
+ const session = await caller(base, 'session');
+ await placements.place('session', 'room');
+ calls.connect.mockResolvedValue({
+ content: [{ type: 'text', text: '{}' }],
+ structuredContent: { instructions: '## Room-specific instructions\n\nSign every reply.' },
+ });
+
+ await expect(answer(session, { type: 'room-instructions', roomId: 'room' })).resolves.toEqual({
+ instructions: 'Sign every reply.',
+ });
+ expect(calls.connect.mock.calls).toEqual([
+ ['session', 'connect_to_room', { room_id: 'room', include_general_instructions: false }],
+ ]);
+
+ calls.connect.mockResolvedValue({
+ content: [{ type: 'text', text: '{}' }],
+ structuredContent: { instructions: '' },
+ });
+ await expect(answer(session, { type: 'room-instructions', roomId: 'room' })).resolves.toEqual({
+ instructions: '',
+ });
+
+ calls.connect.mockResolvedValue({
+ content: [{ type: 'text', text: '{}' }],
+ structuredContent: {},
+ });
+ await expect(answer(session, { type: 'room-instructions', roomId: 'room' })).rejects.toThrow(
+ 'without its instructions'
+ );
+
+ await placements.place('session', 'elsewhere');
+ await expect(answer(session, { type: 'room-instructions', roomId: 'room' })).rejects.toThrow(
+ 'no longer attends room room (it attends elsewhere)'
+ );
+ expect(calls.connect).toHaveBeenCalledTimes(3);
+ expect(placements.roomOf('session')).toBe('elsewhere');
+});
diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.ts
index c03dcc15c..90f2c9aa4 100644
--- a/console/packages/agent-providers/src/host/watcher-tools.ts
+++ b/console/packages/agent-providers/src/host/watcher-tools.ts
@@ -162,17 +162,50 @@ export function sessionToolAnswerer(deps: {
return null;
};
+ /**
+ * The instructions of the room the session attends, read through
+ * `connect_to_room`, which for an agent whose controller places its sessions
+ * checks membership and returns the room's context without claiming
+ * anything. Called directly rather than as the session's own connect: that
+ * one also places the session, and a session that has moved on since the
+ * message was handed over is not to be moved back.
+ */
+ const roomInstructions = async (
+ caller: Caller,
+ catalog: SwitchToolCatalog,
+ ask: Extract<HostAsk, { type: 'room-instructions' }>
+ ): Promise<{ instructions: string }> => {
+ 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 instructions were not read.`
+ );
+ const result = await catalog.call(await context(caller), 'connect_to_room', {
+ room_id: ask.roomId,
+ include_general_instructions: false,
+ });
+ if (result.isError) throw new Error(resultText(result));
+ const instructions = result.structuredContent?.instructions;
+ if (typeof instructions !== 'string')
+ throw new Error(`connect_to_room answered for room ${ask.roomId} without its instructions.`);
+ return { instructions: instructions.replace(ROOM_SECTION_HEADING, '').trim() };
+ };
+
return async (caller, ask) => {
if (ask.type === 'service-token') return services.answer(ask.service, ask.rejected);
const catalog = await tools();
if (ask.type === 'tools') return catalog.tools();
if (ask.type === 'room-reply') return roomReply(caller, catalog, ask);
+ if (ask.type === 'room-instructions') return roomInstructions(caller, catalog, ask);
const args = deps.redactions.value(ask.arguments);
if (ask.name === 'connect_to_room') return connect(caller, catalog, args);
return catalog.call(await context(caller), ask.name, args);
};
}
+/** The heading `connect_to_room` puts over a room's own instructions (`build_room_instructions`). */
+const ROOM_SECTION_HEADING = /^## Room-specific instructions\s*/;
+
function resultText(result: ToolResult): string {
return result.content.map((part) => part.text).join('\n');
}
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index a1be3d9f5..f9ede0c5a 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -122,6 +122,15 @@ does, and there is no polling tool to call.
`BEGIN OPENING MESSAGE` / `END OPENING MESSAGE` markers. You did not write
them, but the person sees them as yours: do not repeat them.
+ The first message you get from a room that has instructions of its own is
+ preceded by them, between `BEGIN ROOM INSTRUCTIONS` / `END ROOM
+ INSTRUCTIONS` markers (`[Switch] Room <room> has instructions of its
+ own…`), and so is the next message after they change or are removed. They
+ are the same instructions `connect_to_room` returns: follow them for
+ everything you do in that room. If they could not be read, the line says so
+ and asks you to call `connect_to_room` for that room before replying; do
+ that rather than answering as if the room had none.
+
Where a server has "follow the conversation" switched on, a person's message
can reach you without naming you: a reply in a thread where you spoke, or
were tagged, more recently than any other agent; their next message after