The Open Framework for Building Agents
[1/3] test(eve): add approval authorization rules to the HITL conformance suite (#4255)
Ben Pankowa07299af2965
diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.mdindex 7455ad46a..5843c2c87 100644--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md@@ -75,6 +75,11 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ || message after ignored sign-in gets an answer, signing in late doesn't run | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ || message after ignored sign-in tells user it was cancelled | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ |+| the requester pressing Approve on a requester-only approval runs the tool | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ❌<sup>[17](#note-17)</sup> | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| another person pressing Approve on a requester-only approval leaves it pending | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ❌<sup>[17](#note-17)</sup> | | —<sup>[19](#note-19)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |+| another person pressing Cancel on a requester-only approval leaves it pending | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ❌<sup>[17](#note-17)</sup> | | —<sup>[19](#note-19)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |+| another person's rejected press leaves the approval's buttons in place | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |+| another person pressing Approve runs a tool with no response policy | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |## Notes@@ -94,3 +99,6 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform14. <a id="note-14"></a>the rule applies only where the conversation is public or shared, and this one is private15. <a id="note-15"></a>the sign-in prompt, link included, is posted to the whole thread16. <a id="note-16"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified+17. <a id="note-17"></a>a button press responds with `auth: null`, so no one can satisfy a response policy+18. <a id="note-18"></a>the platform has no second person who can act+19. <a id="note-19"></a>the platform has no second person who can act or buttons a person can pressdiff --git a/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.tsindex 0cd434c42..999b9b561 100644--- a/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts@@ -10,9 +10,11 @@ import {parseMarkdown,toPlainText,} from "#compiled/chat/index.js";+import type { SessionAuthContext } from "#channel/types.js";import { createMemoryState } from "#compiled/@chat-adapter/state-memory/index.js";import {type ChannelDriver,+ type Person,type PlatformCall,type Surface,numberedOptions,@@ -21,13 +23,15 @@ import {const ADAPTER = "conformance";const PERSON = { fullName: "Alice", isBot: false, isMe: false, userId: "alice", userName: "alice" };-/** The signed-in person a real integration would attach from its own user directory. */-const PERSON_AUTH = {- attributes: {},- authenticator: "conformance",- principalId: "alice",- principalType: "user",-};+const PEOPLE = {+ alice: PERSON,+ bob: { fullName: "Bob", isBot: false, isMe: false, userId: "bob", userName: "bob" },+} as const;++/** The auth an app derives from a Chat SDK user, as the docs' `resolveInputAuth` example does. */+function userAuth(userId: string): SessionAuthContext {+ return { attributes: {}, authenticator: ADAPTER, principalId: userId, principalType: "user" };+}let nextThread = 0;interface CardNode {@@ -46,6 +50,7 @@ type Inbound =readonly actionId: string;/** The posted message holding the pressed button. */readonly messageId: string;+ readonly person: Person;readonly value?: string;};@@ -82,7 +87,10 @@ export function chatSdkDriver(surface: Exclude<Surface, "public"> = "shared"): C});return {...driver,- capabilities: ["buttons", "text-replies"],+ capabilities:+ surface === "private"+ ? ["buttons", "text-replies"]+ : ["another-person", "buttons", "text-replies"],surface,findOptions(call, prompt) {if (!isPost(call)) return undefined;@@ -101,12 +109,13 @@ export function chatSdkDriver(surface: Exclude<Surface, "public"> = "shared"): C};},personShownAs: [PERSON.fullName, PERSON.userName],- press(option) {+ press(option, person: Person) {const { button, messageId } = option.handle as PressHandle;return driver.inbound({actionId: button.id!,kind: "action",messageId,+ person,value: button.value,});},@@ -179,6 +188,7 @@ function chatSdkDriverWith(input: {const bridge = chatSdkChannel({adapters: { [ADAPTER]: adapter },concurrency: "concurrent",+ resolveInputAuth: (event) => userAuth(event.user.userId),routes: { [ADAPTER]: `/eve/v1/${ADAPTER}` },state: createMemoryState() as StateAdapter,streaming: false,@@ -186,17 +196,29 @@ function chatSdkDriverWith(input: {});if (dm) {bridge.bot.onDirectMessage(async (thread, message) => {- await bridge.send(message.text, { auth: PERSON_AUTH, context: [], thread });+ await bridge.send(message.text, {+ auth: userAuth(message.author.userId),+ context: [],+ thread,+ });});} else {// The wiring docs/channels/chat-sdk.mdx shows: a mention starts the session, and// subscribing lets the rest of the thread continue it without one.bridge.bot.onNewMention(async (thread, message) => {await thread.subscribe();- await bridge.send(message.text, { auth: PERSON_AUTH, context: [], thread });+ await bridge.send(message.text, {+ auth: userAuth(message.author.userId),+ context: [],+ thread,+ });});bridge.bot.onSubscribedMessage(async (thread, message) => {- await bridge.send(message.text, { auth: PERSON_AUTH, context: [], thread });+ await bridge.send(message.text, {+ auth: userAuth(message.author.userId),+ context: [],+ thread,+ });});}return bridge.channel;@@ -243,7 +265,7 @@ function fakeAdapter(messageId: body.messageId,raw: body,threadId,- user: PERSON,+ user: PEOPLE[body.person],value: body.value,},options,diff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.tsindex 0f1c8f41d..b03eef046 100644--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts@@ -87,6 +87,19 @@ function unnamedAnsweredPrompts();}+/** Presses reach a response policy without the presser's identity, so eve refuses them all. */+function anonymousPresses(+ reason: string,+ rules: readonly HitlRule[],+): Partial<Record<HitlRule, BrokenCell>> {+ return Object.fromEntries(+ rules.map((rule) => [+ rule,+ { reason, symptom: /Authentication is required to respond to this approval/ },+ ]),+ );+}+interface ConformanceChannel {readonly driver: () => ChannelDriver | ClientDriver;/**@@ -140,6 +153,14 @@ const CHAT_SDK_BROKEN = {const DISCORD_BROKEN = {...unnamedAnsweredPrompts(UNNAMED_RESPONDER, ["approvalPress", "questionPress"]),+ ...anonymousPresses(+ "a button press responds with `auth: null`, so no one can satisfy a response policy",+ [+ "the requester pressing Approve on a requester-only approval runs the tool",+ "another person pressing Approve on a requester-only approval leaves it pending",+ "another person pressing Cancel on a requester-only approval leaves it pending",+ ],+ ),...noSignInRenderer("a sign-in names the service and shows its sign-in link","a sign-in shows its confirmation code",@@ -288,6 +309,7 @@ type Cell =| { readonly kind: "broken"; readonly broken: BrokenCell };const CAPABILITY_NAMES: Record<ChannelCapability, string> = {+ "another-person": "second person who can act",buttons: "buttons a person can press","text-replies": "plain-text replies",};diff --git a/packages/eve/src/internal/testing/channel-conformance/contract.ts b/packages/eve/src/internal/testing/channel-conformance/contract.tsindex a50093524..438c0fdba 100644--- a/packages/eve/src/internal/testing/channel-conformance/contract.ts+++ b/packages/eve/src/internal/testing/channel-conformance/contract.ts@@ -5,8 +5,10 @@ import {type ChannelConversation,type ConversationOptions,GATED_TOOL,+ type GatedTool,PLAIN_TOOL,type RenderedOption,+ REQUESTER_GATED_TOOL,type Surface,SECOND_GATED_TOOL,SIGN_IN_TOOLS,@@ -93,13 +95,38 @@ function option(return found!;}-async function expectDeployed(conversation: ChannelConversation) {- const outcome = await conversation.waitForToolOutcome(GATED_TOOL);- expect(outcome, `${GATED_TOOL} settled as ${JSON.stringify(outcome)}`).toEqual({+const HOTFIX = `Use ${REQUESTER_GATED_TOOL} to ship the fix.`;+const HOTFIX_PROMPT = "Approve Release hotfix?";++async function askToReleaseHotfix(conversation: ChannelConversation) {+ await conversation.say(HOTFIX);+ return await conversation.waitForQuestion(HOTFIX_PROMPT);+}++async function expectRan(conversation: ChannelConversation, tool: GatedTool, output: unknown) {+ const outcome = await conversation.waitForToolOutcome(tool);+ expect(outcome, `${tool} settled as ${JSON.stringify(outcome)}`).toEqual({kind: "ran",- output: { deployed: true },+ output,});- expect(conversation.runsOf(GATED_TOOL)).toBe(1);+ expect(conversation.runsOf(tool)).toBe(1);+}++async function expectDeployed(conversation: ChannelConversation) {+ await expectRan(conversation, GATED_TOOL, { deployed: true });+}++async function expectReleased(conversation: ChannelConversation) {+ await expectRan(conversation, REQUESTER_GATED_TOOL, { released: true });+}++/** Once the session settles after Bob's press, the requester-only approval is still pending. */+async function expectStillPending(conversation: ChannelConversation) {+ await conversation.waitForRest();+ expect(+ conversation.runsOf(REQUESTER_GATED_TOOL),+ `${REQUESTER_GATED_TOOL} ran on Bob's press`,+ ).toBe(0);}async function expectNotDeployed(conversation: ChannelConversation) {@@ -154,6 +181,20 @@ async function expectButtonsCleared(conversation: ChannelConversation, prompt: sexpect(labels, `the answered prompt still offers ${JSON.stringify(labels)}`).toEqual([]);}+/** A press an approval policy rejected leaves the prompt answerable by someone else. */+async function expectButtonsKept(conversation: ChannelConversation, prompt: string) {+ const labels = (await conversation.shownPrompt(prompt)).options.map((option) => option.label);+ const message = `the rejected prompt offers ${JSON.stringify(labels)}`;+ expect(+ labels.some((label) => APPROVE_LABELS.includes(label)),+ message,+ ).toBe(true);+ expect(+ labels.some((label) => CANCEL_LABELS.includes(label)),+ message,+ ).toBe(true);+}+/** Once answered, the prompt's message shows everyone in the conversation who answered it. */async function expectResponderNamed(conversation: ChannelConversation, prompt: string) {const { text } = await conversation.shownPrompt(prompt);@@ -721,6 +762,63 @@ const signInRules = [await conversation.waitForShown(/\b(?:cancel|declin)/iu);},},+ {+ rule: "the requester pressing Approve on a requester-only approval runs the tool",+ source: "docs/tools/human-in-the-loop.md#authorizing-approval-responses",+ requires: ["buttons"],+ async run(conversation) {+ const options = await askToReleaseHotfix(conversation);+ await conversation.press(option(options, APPROVE_LABELS));+ await expectReleased(conversation);+ },+ },+ {+ rule: "another person pressing Approve on a requester-only approval leaves it pending",+ source: "docs/tools/human-in-the-loop.md#authorizing-approval-responses",+ requires: ["another-person", "buttons"],+ async run(conversation) {+ const options = await askToReleaseHotfix(conversation);+ const approve = option(options, APPROVE_LABELS);+ await conversation.press(approve, "bob");+ await expectStillPending(conversation);+ await conversation.press(approve);+ await expectReleased(conversation);+ },+ },+ {+ rule: "another person pressing Cancel on a requester-only approval leaves it pending",+ source: "docs/tools/human-in-the-loop.md#authorizing-approval-responses",+ requires: ["another-person", "buttons"],+ async run(conversation) {+ const options = await askToReleaseHotfix(conversation);+ await conversation.press(option(options, CANCEL_LABELS), "bob");+ await expectStillPending(conversation);+ // A cancel that got through would settle the call as denied before this approval.+ await conversation.press(option(options, APPROVE_LABELS));+ await expectReleased(conversation);+ },+ },+ {+ rule: "another person's rejected press leaves the approval's buttons in place",+ source: "docs/tools/human-in-the-loop.md#authorizing-approval-responses",+ requires: ["another-person", "buttons"],+ async run(conversation) {+ const options = await askToReleaseHotfix(conversation);+ await conversation.press(option(options, APPROVE_LABELS), "bob");+ await expectStillPending(conversation);+ await expectButtonsKept(conversation, HOTFIX_PROMPT);+ },+ },+ {+ rule: "another person pressing Approve runs a tool with no response policy",+ source: "docs/tools/human-in-the-loop.md#authorizing-approval-responses",+ requires: ["another-person", "buttons"],+ async run(conversation) {+ const options = await askToDeploy(conversation);+ await conversation.press(option(options, APPROVE_LABELS), "bob");+ await expectDeployed(conversation);+ },+ },] as const satisfies readonly ContractRule[];/** The contract's rules, grouped by the kind of prompt they cover. */diff --git a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts b/packages/eve/src/internal/testing/channel-conformance/discord-driver.tsindex 5e632a60c..233502701 100644--- a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts@@ -3,6 +3,7 @@ import { generateKeyPairSync, sign, type KeyObject } from "node:crypto";import { discordChannel } from "#public/channels/discord/index.js";import {type ChannelDriver,+ type Person,type PlatformCall,type RenderedOption,type Surface,@@ -12,6 +13,7 @@ import {let nextChannel = 0;const PERSON = { id: "U_CONFORMANCE", username: "alice" } as const;+const PEOPLE = { alice: PERSON, bob: { id: "U_BOB", username: "bob" } } as const;/** A message component eve renders for a choice: a button (type 2) or a select menu (type 3). */interface DiscordComponent {@@ -44,9 +46,10 @@ function testKeys(): { privateKey: KeyObject; publicKeyHex: string } {export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): ChannelDriver {const dm = surface === "private";// In a server, Discord names the actor as a member; in a DM, as a user.- const where = dm- ? { channel: { type: 1 }, user: PERSON }- : { channel: { type: 0 }, guild_id: "G_CONFORMANCE", member: { roles: [], user: PERSON } };+ const where = (user: (typeof PEOPLE)[Person] = PERSON) =>+ dm+ ? { channel: { type: 1 }, user }+ : { channel: { type: 0 }, guild_id: "G_CONFORMANCE", member: { roles: [], user } };nextChannel += 1;const channelId = `C_CONFORMANCE_${nextChannel}`;const { privateKey, publicKeyHex } = testKeys();@@ -111,7 +114,7 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Creturn {name: dm ? "discord-dm" : "discord",- capabilities: ["buttons"],+ capabilities: dm ? ["buttons"] : ["another-person", "buttons"],surface,createChannel: (record) =>discordChannel({@@ -122,7 +125,7 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Cconst id = nextInteraction();return signed(JSON.stringify({- ...where,+ ...where(),application_id: "APP1",channel_id: channelId,data: { name: "ask", options: [{ name: "message", type: 3, value: text }] },@@ -152,7 +155,7 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): C};},personShownAs: [`<@${PERSON.id}>`, PERSON.username],- press(option) {+ press(option, person: Person) {const handle = option.handle as PressHandle;const id = nextInteraction();// A component interaction's `@original` response is the message holding the component.@@ -166,7 +169,7 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): C? { component_type: 2, custom_id: handle.customId }: { component_type: 3, custom_id: handle.customId, values: [handle.value] },id,- ...where,+ ...where(PEOPLE[person]),message: { id: handle.messageId },token: `tok-${id}`,type: 3,diff --git a/packages/eve/src/internal/testing/channel-conformance/harness.ts b/packages/eve/src/internal/testing/channel-conformance/harness.tsindex 6bb9b5914..76873f8c7 100644--- a/packages/eve/src/internal/testing/channel-conformance/harness.ts+++ b/packages/eve/src/internal/testing/channel-conformance/harness.ts@@ -8,8 +8,10 @@ import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-aimport { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import { createAttachSessionFn, type Session } from "#channel/session.js";import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";+import type { SessionAuthContext } from "#channel/types.js";import { eveChannel } from "#public/channels/eve.js";import { z } from "#compiled/zod/index.js";+import type { ApprovalResponsePolicy } from "#approval/definition.js";import { always } from "#tools/approval/policies.js";import { defineTool } from "#tools/definition.js";import { askQuestion } from "#tools/provided/ask-question.js";@@ -89,6 +91,8 @@ export function linkTargets(value: unknown): string[] {* capability a driver lacks is skipped for that channel as "not supported".*/export type ChannelCapability =+ /** Someone besides the person who started the conversation can act in it. */+ | "another-person"/** A person can press a rendered choice. */| "buttons"/** A person can send a plain-text message to the conversation. */@@ -134,8 +138,11 @@ export interface ChannelDriver {* request metadata.*/findOptions(call: PlatformCall, prompt: string): readonly RenderedOption[] | undefined;- /** A webhook request pressing a rendered option. */- press(option: RenderedOption): Request;+ /**+ * A webhook request in which `person` presses a rendered option. Drivers+ * with the `another-person` capability must press as `"bob"` when asked.+ */+ press(option: RenderedOption, person: Person): Request;/** Text the bot posted in one outbound call, if any. */postedText(call: PlatformCall): string | undefined;/**@@ -149,6 +156,12 @@ export interface ChannelDriver {readonly personShownAs?: readonly string[];}+/**+ * Who acts in a conversation: Alice starts it and asks for every request; Bob+ * is someone else in it, and needs the `another-person` capability.+ */+export type Person = "alice" | "bob";+/** What a person can do and see in one channel conversation. Contract rules use only this. */export interface ChannelConversation {/** The person sends a plain-text message. */@@ -168,8 +181,8 @@ export interface ChannelConversation {* yet. A client may show several pending requests one at a time.*/waitForRequest(prompt: string): Promise<void>;- /** The person presses one rendered choice. */- press(option: RenderedOption): Promise<void>;+ /** `person`, Alice unless given, presses one rendered choice. */+ press(option: RenderedOption, person?: Person): Promise<void>;/** Waits until `tool` returns, as visible in the bot's reply, and returns its output. */waitForToolResult(tool: string): Promise<unknown>;/** Waits until the bot replies to input that carried `text`, however the channel framed it. */@@ -233,8 +246,8 @@ export interface ClientView {* choices. A client may show several pending requests one at a time.*/waitForQuestion(prompts: readonly string[]): Promise<ShownQuestion>;- /** The person presses one shown choice. */- press(option: RenderedOption): Promise<void>;+ /** `person` presses one shown choice. */+ press(option: RenderedOption, person: Person): Promise<void>;/** The bot replies the client shows now. */replies(): readonly string[] | Promise<readonly string[]>;/** The message that asked `prompt` as it stands now; see {@link ChannelConversation.shownPrompt}. */@@ -280,7 +293,13 @@ export const GATED_TOOL = "deploy_release";/** A second always-gated tool, so two approvals can be pending at once. */export const SECOND_GATED_TOOL = "publish_notes";-export type GatedTool = typeof GATED_TOOL | typeof SECOND_GATED_TOOL;+/**+ * An always-gated tool whose response policy lets only the person who asked+ * for the call approve or cancel it.+ */+export const REQUESTER_GATED_TOOL = "release_hotfix";++export type GatedTool = typeof GATED_TOOL | typeof SECOND_GATED_TOOL | typeof REQUESTER_GATED_TOOL;/** The test agent's plain tool: it runs without asking anyone. */export const PLAIN_TOOL = "look_up_notes";@@ -421,7 +440,7 @@ function webhookView(return {say: (text) => post(driver.message(text)),- press: (option) => post(driver.press(option)),+ press: (option, person) => post(driver.press(option, person)),waitForQuestion: (prompts) =>wait(`one of the questions ${JSON.stringify(prompts)}`,@@ -515,6 +534,7 @@ async function converse(const channel: CompiledChannel = created;const runs: Record<CountedTool, number> = {[GATED_TOOL]: 0,+ [REQUESTER_GATED_TOOL]: 0,[SECOND_GATED_TOOL]: 0,[PLAIN_TOOL]: 0,read_calendar: 0,@@ -586,6 +606,19 @@ async function converse(runs[SECOND_GATED_TOOL] += 1;return { published: true };}),+ gatedTool(+ REQUESTER_GATED_TOOL,+ "Releases a hotfix.",+ () => {+ runs[REQUESTER_GATED_TOOL] += 1;+ return { released: true };+ },+ // The requester-only policy from docs/tools/human-in-the-loop.md.+ ({ request, response }) =>+ request.principal !== null && samePrincipal(response.principal, request.principal)+ ? { status: "allowed" }+ : { reason: "Only the person who asked can respond.", status: "rejected" },+ ),{logicalPath: `tools/${TWO_QUESTIONS_TOOL}.ts`,loadNamespace: async () => ({@@ -699,7 +732,7 @@ async function converse(await waitForStepsToFinish([...sessions.values()], wait);await view.say(text);},- press: (option) => view.press(option),+ press: (option, person = "alice") => view.press(option, person),async waitForQuestion(prompt) {const { options } = await view.waitForQuestion([prompt]);await holdForInput(prompt);@@ -710,7 +743,7 @@ async function converse(while (remaining.length > 0) {const { options, prompt } = await view.waitForQuestion(remaining);await holdForInput(prompt);- await view.press(choose(prompt, options));+ await view.press(choose(prompt, options), "alice");remaining.splice(remaining.indexOf(prompt), 1);}},@@ -973,12 +1006,17 @@ async function holdsFor(return held;}-function gatedTool(name: GatedTool, description: string, execute: () => unknown) {+function gatedTool(+ name: GatedTool,+ description: string,+ execute: () => unknown,+ response?: ApprovalResponsePolicy,+) {return {logicalPath: `tools/${name}.ts`,loadNamespace: async () => ({default: defineTool({- approval: always(),+ approval: response === undefined ? always() : { request: always(), response },description: `${description} Only call when asked to use ${name}.`,execute: async () => execute(),inputSchema: z.object({ release: z.string().optional() }),@@ -987,6 +1025,15 @@ function gatedTool(name: GatedTool, description: string, execute: () => unknown)};}+function samePrincipal(a: SessionAuthContext, b: SessionAuthContext): boolean {+ return (+ a.authenticator === b.authenticator &&+ a.issuer === b.issuer &&+ a.principalType === b.principalType &&+ a.principalId === b.principalId+ );+}+function findRoute(channel: CompiledChannel, request: Request) {const { pathname } = new URL(request.url);for (const route of channel.routes) {diff --git a/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts b/packages/eve/src/internal/testing/channel-conformance/slack-driver.tsindex f57f5aa7e..178a71cf2 100644--- a/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts@@ -4,6 +4,7 @@ import { slackChannel } from "#public/channels/slack/index.js";import { HITL_ACTION_PREFIX } from "#public/channels/slack/hitl.js";import {type ChannelDriver,+ type Person,type Surface,type PlatformCall,type RenderedOption,@@ -15,6 +16,10 @@ import { decodeSlackApiBody } from "#internal/testing/slack-api-body.js";const SIGNING_SECRET = "slack-conformance-secret";const PERSON = "U_ALICE";const BOT = "U_EVE";+const PEOPLE = {+ alice: { id: PERSON, name: "alice" },+ bob: { id: "U_BOB", name: "bob" },+} as const;let nextChannel = 0;const TEAM = "T01";@@ -107,7 +112,7 @@ export function slackDriver(surface: Exclude<Surface, "public"> = "shared"): Chareturn {name: dm ? "slack-dm" : "slack",- capabilities: ["buttons", "text-replies"],+ capabilities: dm ? ["buttons", "text-replies"] : ["another-person", "buttons", "text-replies"],surface,createChannel: (record) =>slackChannel({@@ -171,15 +176,16 @@ export function slackDriver(surface: Exclude<Surface, "public"> = "shared"): Cha};},personShownAs: [`<@${PERSON}>`],- press: (option) => {+ press: (option, person: Person) => {const { action, blocks, messageTs } = option.handle as PressHandle;+ const { id, name } = PEOPLE[person];const payload = {actions: [action],channel: { id: CHANNEL },message: { blocks, thread_ts: threadTs, ts: messageTs },team: { id: TEAM },type: "block_actions",- user: { id: PERSON, name: "alice", team_id: TEAM, username: "alice" },+ user: { id, name, team_id: TEAM, username: name },};return signed(new URLSearchParams({ payload: JSON.stringify(payload) }).toString(),diff --git a/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts b/packages/eve/src/internal/testing/channel-conformance/teams-driver.tsindex dc3776f55..aa4b90375 100644--- a/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts@@ -1,6 +1,7 @@import { teamsChannel } from "#public/channels/teams/index.js";import {type ChannelDriver,+ type Person,type PlatformCall,type RenderedOption,type Surface,@@ -11,6 +12,7 @@ import {let nextConversation = 0;const TENANT = "TENANT";const PERSON = { id: "USER", name: "Alice" } as const;+const PEOPLE = { alice: PERSON, bob: { id: "USER-BOB", name: "Bob" } } as const;const BOT = { id: "BOT", name: "eve Bot" } as const;const SERVICE_URL = "https://smba.example.test/teams";const MENTION = `<at>${BOT.name}</at>`;@@ -102,7 +104,9 @@ export function teamsDriver(surface: Exclude<Surface, "public"> = "shared"): Chareturn {name: personal ? "teams-dm" : "teams",- capabilities: ["buttons", "text-replies"],+ capabilities: personal+ ? ["buttons", "text-replies"]+ : ["another-person", "buttons", "text-replies"],surface,createChannel: (record) =>teamsChannel({@@ -139,9 +143,10 @@ export function teamsDriver(surface: Exclude<Surface, "public"> = "shared"): Cha};},personShownAs: [PERSON.name],- press: (option: RenderedOption) => {+ press: (option: RenderedOption, person: Person) => {const { activityId: cardActivityId, data, value } = option.handle as PressHandle;return activity({+ from: PEOPLE[person],id: `INVOKE-${activityId + 1}`,name: "adaptiveCard/action",replyToId: cardActivityId,diff --git a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.tsindex 20f317a5b..3c6c02e8a 100644--- a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts@@ -1,6 +1,7 @@import { telegramChannel } from "#public/channels/telegram/index.js";import {type ChannelDriver,+ type Person,type PlatformCall,type RenderedOption,type Surface,@@ -67,6 +68,10 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):? { id: -nextChatId, title: "Release crew", type: "supergroup" }: { id: nextChatId, type: "private" };const PERSON = { first_name: "Alice", id: nextChatId, is_bot: false } as const;+ const PEOPLE = {+ alice: PERSON,+ bob: { first_name: "Bob", id: nextChatId + 500_000, is_bot: false },+ } as const;let updateId = 0;let messageId = 0;/** The bot's latest message, which a person in a group replies to so the bot hears them. */@@ -113,7 +118,9 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):return {name: group ? "telegram" : "telegram-dm",- capabilities: ["buttons", "text-replies"],+ capabilities: !group+ ? ["buttons", "text-replies"]+ : ["another-person", "buttons", "text-replies"],surface,createChannel: (record) =>telegramChannel({@@ -149,12 +156,12 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):};},personShownAs: [PERSON.first_name],- press: (option) => {+ press: (option, person: Person) => {const { data, messageId } = option.handle as PressHandle;return update({callback_query: {data,- from: PERSON,+ from: PEOPLE[person],id: `callback-${updateId}`,message: { chat: CHAT, date: 0, message_id: messageId },},