Multiplayer agent harness for work.
Carry conversation roster into ambient replies (#613)
Joshua Franced2d43d48c24d
diff --git a/src/api/app-ambient.ts b/src/api/app-ambient.tsindex c3572672b..da19b54f6 100644--- a/src/api/app-ambient.ts+++ b/src/api/app-ambient.ts@@ -1,4 +1,4 @@-import type { TurnRequest } from "../types.ts";+import type { ActorAssertion, TurnRequest } from "../types.ts";import { orgId as orgIdOf } from "../config.ts";import type { OrchestratorInput } from "../core/orchestrator.ts";import { samePerson } from "../directory/person.ts";@@ -207,17 +207,43 @@ export function createAmbientHelpers(deps: AppDeps, app: App) {function workerConversation(batch: AmbientBatch,threadRef: string,- ): { kind: "channel" | "group"; threadRef: string; channelRef: string; isMpim?: boolean } {+ audience: ActorAssertion[],+ ): TurnRequest["conversation"] {+ const roster: Pick<TurnRequest["conversation"], "audience" | "publishMembers"> = audience.length+ ? { audience, publishMembers: audience }+ : { audience };return batch.kind === "group"- ? { kind: "group", threadRef, channelRef: batch.container, isMpim: true }- : { kind: "channel", threadRef, channelRef: batch.container };+ ? { kind: "group" as const, threadRef, channelRef: batch.container, isMpim: true, ...roster }+ : { kind: "channel" as const, threadRef, channelRef: batch.container, ...roster };+ }++ async function conversationAudience(batch: AmbientBatch): Promise<ActorAssertion[] | undefined> {+ const members = await deps.directory+ .conversationMembers(batch.kind === "group" ? "group" : "channel", batch.container)+ .catch(() => undefined);+ if (!members?.length) return undefined;+ return members.map((member) => ({+ externalId: member.principalId,+ ...(member.displayName ? { displayName: member.displayName } : {}),+ }));}async function spawnAmbientWorker(batch: AmbientBatch, decision: AmbientDecision): Promise<void> {const latestTs = batch.messages.reduce((max, m) => (m.ts > max ? m.ts : max), "");const threadRef = `${batch.surface}:${batch.container}:ambient:${latestTs}`;- const conversation = workerConversation(batch, threadRef);- const solicited = await solicitedAsker(batch, decision);+ let solicited = await solicitedAsker(batch, decision);+ let audience: ActorAssertion[] = [];+ if (solicited) {+ const askerId = solicited.member.principalId;+ const resolved = await conversationAudience(batch);+ if (!resolved?.some((member) => samePerson(member.externalId, askerId))) {+ console.error(`[ambient] solicited wake has no complete roster (container=${batch.container})`);+ solicited = undefined;+ } else {+ audience = resolved;+ }+ }+ const conversation = workerConversation(batch, threadRef, audience);if (decision.askedBy && !solicited)console.error(`[ambient] solicited wake degraded to proactive (asked_by=${decision.askedBy}, container=${batch.container})`,@@ -284,7 +310,10 @@ export function createAmbientHelpers(deps: AppDeps, app: App) {.screenSecuritySteer({payload: req.text,actor: { id: `system:ambient:${orgIdOf()}`, type: "internal" },- conversation: { ...workerConversation(batch, liveRef), audience: [] },+ conversation:+ batch.kind === "group"+ ? { kind: "group", threadRef: liveRef, channelRef: batch.container, isMpim: true, audience: [] }+ : { kind: "channel", threadRef: liveRef, channelRef: batch.container, audience: [] },...(session ? { sessionId: session.id } : {}),}).catch(() => "block" as const);diff --git a/src/directory/directory-store.ts b/src/directory/directory-store.tsindex 6e128c500..8fe4b9bf2 100644--- a/src/directory/directory-store.ts+++ b/src/directory/directory-store.ts@@ -70,6 +70,7 @@ export interface DirectoryStore {groupMember(groupId: string, principalId: string): Promise<boolean>;groupMembership(groupId: string, principalId: string): Promise<boolean | undefined>;listGroupsFor(principalId: string): Promise<string[]>;+ conversationMembers(kind: "channel" | "group", id: string): Promise<DirectoryMember[] | undefined>;listChannelsFor(principalId: string): Promise<DirectoryChannel[]>;setWorkspaceUrl(url: string): Promise<void>;meta(): Promise<DirectoryMeta>;@@ -239,6 +240,22 @@ export function createDirectoryStore(): DirectoryStore {if (!memberships) return [];return [...memberships].filter(([, members]) => members.has(principalId)).map(([groupId]) => groupId);},+ async conversationMembers(kind, id) {+ let ids: string[];+ if (kind === "channel") {+ const channel = channels.find((candidate) => candidate.channelId === id);+ if (!channel || channel.isExternal || !knownChannelRosters?.has(id)) return undefined;+ ids = [...(channelMembers?.get(id) ?? [])];+ } else {+ if (!knownGroupRosters?.has(id)) return undefined;+ ids = [...(groupMembers?.get(id) ?? [])];+ }+ if (!ids.length) return undefined;+ const roster = ids+ .map((principalId) => members.find((member) => samePerson(member.principalId, principalId)))+ .filter((member): member is DirectoryMember => member !== undefined);+ return roster.length === ids.length ? roster : undefined;+ },async listChannelsFor(principalId) {return channels.filter((channel) =>diff --git a/src/directory/postgres-directory-store.ts b/src/directory/postgres-directory-store.tsindex e44b70821..563ef59e0 100644--- a/src/directory/postgres-directory-store.ts+++ b/src/directory/postgres-directory-store.ts@@ -553,6 +553,38 @@ export function createPostgresDirectoryStore(connectionString: string): Directorreturn rows.map((row) => row.group_id as string);},+ async conversationMembers(kind, id) {+ const rows =+ kind === "channel"+ ? await q(+ `SELECT channel.roster_known, channel.is_external, roster.principal_id AS roster_principal_id,+ member.principal_id, member.display_name, member.type, member.slack_id+ FROM directory_channels channel+ LEFT JOIN directory_channel_members roster+ ON roster.org_id = channel.org_id AND roster.channel_id = channel.channel_id+ LEFT JOIN directory_members member+ ON member.org_id = roster.org_id AND member.principal_id = roster.principal_id+ WHERE channel.org_id = $1 AND channel.channel_id = $2+ ORDER BY roster.principal_id`,+ [orgId, id],+ )+ : await q(+ `SELECT group_row.roster_known, FALSE AS is_external, roster.principal_id AS roster_principal_id,+ member.principal_id, member.display_name, member.type, member.slack_id+ FROM directory_groups group_row+ LEFT JOIN directory_group_members roster+ ON roster.org_id = group_row.org_id AND roster.group_id = group_row.group_id+ LEFT JOIN directory_members member+ ON member.org_id = roster.org_id AND member.principal_id = roster.principal_id+ WHERE group_row.org_id = $1 AND group_row.group_id = $2+ ORDER BY roster.principal_id`,+ [orgId, id],+ );+ if (!rows.length || rows[0]?.roster_known !== true || rows[0]?.is_external === true) return undefined;+ if (rows.some((row) => !row.roster_principal_id || !row.principal_id)) return undefined;+ return rows.map(memberRow);+ },+async listChannelsFor(principalId) {const rows = await q(`SELECT channel_id, name, is_private, is_external FROM directory_channels cdiff --git a/test/directory-store.test.ts b/test/directory-store.test.tsindex c1efc1227..c2a2c39b5 100644--- a/test/directory-store.test.ts+++ b/test/directory-store.test.ts@@ -123,6 +123,11 @@ describe("member slackId (the real <@…> mention id for an email principal)", (describe("group-DM (mpim) membership (addressed by participant set, §10)", () => {const dir = async (): Promise<DirectoryStore> => {const d = createDirectoryStore();+ await d.replace([+ { principalId: "U-alice", displayName: "Alice", type: "internal" },+ { principalId: "U-carol", displayName: "Carol", type: "internal" },+ { principalId: "U-sam", displayName: "Sam", type: "internal" },+ ]);await d.replaceGroups([{ groupId: "G-1", principalId: "U-alice" },{ groupId: "G-1", principalId: "U-carol" },@@ -154,12 +159,18 @@ describe("group-DM (mpim) membership (addressed by participant set, §10)", () =assert.equal(await d.groupMember("G-2", "U-sam"), false);assert.equal(await d.groupMember("G-unknown", "U-alice"), false);assert.deepEqual(await d.listGroupsFor("U-sam"), ["G-1"]);+ assert.deepEqual((await d.conversationMembers("group", "G-1"))?.map((member) => member.principalId).sort(), [+ "U-alice",+ "U-carol",+ "U-sam",+ ]);assert.equal(await d.groupMembership("G-2", "U-sam"), false);});it("distinguishes an unavailable group roster from a definitive nonmember", async () => {const d = createDirectoryStore();assert.equal(await d.groupMembership("G-1", "U-alice"), undefined);+ assert.equal(await d.conversationMembers("group", "G-1"), undefined);await d.replaceGroups([]);assert.equal(await d.groupMembership("G-1", "U-alice"), false);});@@ -225,6 +236,10 @@ describe("group-DM (mpim) membership (addressed by participant set, §10)", () =describe("private-channel membership (authorizes private-channel sends, §10)", () => {it("channelMember reflects pushed membership; omitting it leaves it intact; providing it is a full swap", async () => {const d = createDirectoryStore();+ await d.replace([+ { principalId: "U-alice", displayName: "Alice", type: "internal" },+ { principalId: "U-carol", displayName: "Carol", type: "internal" },+ ]);await d.replaceChannels([{ channelId: "C-sec", name: "secret", isPrivate: true }],[{ channelId: "C-sec", principalId: "U-carol" }],@@ -234,6 +249,10 @@ describe("private-channel membership (authorizes private-channel sends, §10)",assert.equal(await d.channelMembership("C-sec", "U-alice"), false);assert.equal(await d.channelMember("C-sec", "U-alice"), false);assert.equal(await d.channelMember("C-other", "U-carol"), false);+ assert.deepEqual(+ (await d.conversationMembers("channel", "C-sec"))?.map((member) => member.principalId),+ ["U-carol"],+ );await d.replaceChannels([{ channelId: "C-sec", name: "secret", isPrivate: true }]);assert.equal(await d.channelMember("C-sec", "U-carol"), true);@@ -258,6 +277,12 @@ describe("private-channel membership (authorizes private-channel sends, §10)",);assert.equal(await d.channelMembership("C-public", "U-alice"), undefined);assert.equal(await d.channelMembership("C-sec", "U-alice"), false);+ assert.equal(await d.conversationMembers("channel", "C-sec"), undefined);+ await d.replaceChannels(+ [{ channelId: "C-external", name: "external", isExternal: true }],+ [{ channelId: "C-external", principalId: "U-alice" }],+ );+ assert.equal(await d.conversationMembers("channel", "C-external"), undefined);});it("partially replaces only the channel rosters known by the source", async () => {diff --git a/test/postgres-directory-store.test.ts b/test/postgres-directory-store.test.tsindex d0823ac8c..15b3e77ad 100644--- a/test/postgres-directory-store.test.ts+++ b/test/postgres-directory-store.test.ts@@ -168,6 +168,10 @@ test({ skip },async () => {const store = createPostgresDirectoryStore(URL!);+ await store.replace([+ { principalId: "U-alice", displayName: "Alice", type: "internal" },+ { principalId: "U-carol", displayName: "Carol", type: "internal" },+ ]);await store.replaceChannels([{ channelId: "C-sec", name: "secret", isPrivate: true }],[{ channelId: "C-sec", principalId: "U-carol" }],@@ -177,6 +181,10 @@ test(assert.equal(await store.channelMembership("C-sec", "U-alice"), false);assert.equal(await store.channelMember("C-sec", "U-alice"), false);assert.equal(await store.channelMember("C-other", "U-carol"), false);+ assert.deepEqual(+ (await store.conversationMembers("channel", "C-sec"))?.map((member) => member.principalId),+ ["U-carol"],+ );await store.replaceChannels([{ channelId: "C-sec", name: "secret", isPrivate: true }]);assert.equal(await store.channelMember("C-sec", "U-carol"), true);@@ -211,6 +219,11 @@ test({ skip },async () => {const store = createPostgresDirectoryStore(URL!);+ await store.replace([+ { principalId: "U-alice", displayName: "Alice", type: "internal" },+ { principalId: "U-carol", displayName: "Carol", type: "internal" },+ { principalId: "U-sam", displayName: "Sam", type: "internal" },+ ]);await store.replaceGroups([{ groupId: "G-1", principalId: "U-alice" },{ groupId: "G-1", principalId: "U-carol" },@@ -229,6 +242,10 @@ test(assert.equal(await store.groupMember("G-1", "U-sam"), true);assert.equal(await store.groupMember("G-2", "U-sam"), false);assert.equal(await store.groupMembership("G-2", "U-sam"), false);+ assert.deepEqual(+ (await store.conversationMembers("group", "G-1"))?.map((member) => member.principalId),+ ["U-alice", "U-carol", "U-sam"],+ );assert.deepEqual(await store.listGroupsFor("U-sam"), ["G-1"]);const direct = (await freshPg(URL!)).query;@@ -405,12 +422,14 @@ test("pg directory: removals apply without clearing a failed channel refresh", {test("pg directory: a private Slack Connect roster is not an ordinary send target", { skip }, async () => {const store = createPostgresDirectoryStore(URL!);+ await store.replace([{ principalId: "U-member", displayName: "Member", type: "internal" }]);await store.replaceChannels([{ channelId: "C-connect", name: "connect", isPrivate: true, isExternal: true }],[{ channelId: "C-connect", principalId: "U-member" }],);assert.equal(await store.channelMembership("C-connect", "U-member"), true);assert.equal(await store.channelMember("C-connect", "U-member"), false);+ assert.equal(await store.conversationMembers("channel", "C-connect"), undefined);assert.deepEqual(await store.listChannelsFor("U-member"), []);});diff --git a/test/surface-cache-ambient.test.ts b/test/surface-cache-ambient.test.tsindex 27c70b769..edd9d8c64 100644--- a/test/surface-cache-ambient.test.ts+++ b/test/surface-cache-ambient.test.ts@@ -772,7 +772,10 @@ test("a solicited ambient wake runs as the asking person, not the system actor",await built.directory.replace([{ principalId: "[email protected]", displayName: "Alice", type: "internal", slackId: "U1" },]);- await built.directory.replaceChannels([{ channelId: container, name: "solicited-chan", isPrivate: false }]);+ await built.directory.replaceChannels(+ [{ channelId: container, name: "solicited-chan", isPrivate: false }],+ [{ channelId: container, principalId: "[email protected]" }],+ );await built.app.setChannelPolicy(container, "!engage-asked", "U-admin");await built.app.ingestSurfaceEvents([{ container, ts: "300.1", authorId: "U1", authorName: "Alice", text: "!post solicited reply", createdAt: 1 },@@ -793,6 +796,36 @@ test("a solicited ambient wake runs as the asking person, not the system actor",}});+test("a solicited ambient wake carries the complete channel roster", async () => {+ const built = freshApp();+ built.runtime.start();+ try {+ const container = "C-solicited-roster";+ await built.directory.replace([+ { principalId: "[email protected]", displayName: "Alice", type: "internal", slackId: "U1" },+ { principalId: "[email protected]", displayName: "Bob", type: "internal", slackId: "U2" },+ ]);+ await built.directory.replaceChannels(+ [{ channelId: container, name: "solicited-roster", isPrivate: false }],+ [+ { channelId: container, principalId: "[email protected]" },+ { channelId: container, principalId: "[email protected]" },+ ],+ );+ await built.app.setChannelPolicy(container, "!engage-asked", "U-admin");+ await built.app.ingestSurfaceEvents([+ { container, ts: "350.1", authorId: "U1", authorName: "Alice", text: "!sysprompt", createdAt: 1 },+ ]);++ const pending = await pollDeliveries(built.deliveries);+ assert.equal(pending.length, 1);+ assert.match(pending[0].text, /Alice \(alice@acme\.com\)/);+ assert.match(pending[0].text, /Bob \(bob@acme\.com\)/);+ } finally {+ await built.runtime.stop();+ }+});+test("an ambient worker in a group DM runs at the group scope, not a fabricated channel scope", async () => {const built = freshApp();built.runtime.start();