Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[1/7] test(eve): add complex HITL, ctx.ask cases to conformance suite (#4231)

Ben Pankow8521b5d27f4b
diff --git a/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts
index f0fea5d0e..8bcaea2b4 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
@@ -49,7 +49,7 @@ export function chatSdkDriver(): ChannelDriver {
if (!isPost(call)) return undefined;
const card = cardOf(call.body as AdapterPostableMessage);
if (card === undefined || !texts(card).includes(prompt)) return undefined;
- return nodes(card)
+ return nodes(requestSection(card, prompt))
.filter((node) => node.type === "button" && node.id !== undefined)
.map((button) => ({ handle: button, label: button.label ?? "" }));
},
@@ -243,6 +243,20 @@ function cardOf(posted: AdapterPostableMessage): CardNode | undefined {
return (posted as CardNode).type === "card" ? (posted as CardNode) : undefined;
}
+/**
+ * A card batching several requests lists each one's prompt text, then its
+ * actions. Returns the part of `card` that belongs to `prompt`.
+ */
+function requestSection(card: CardNode, prompt: string): CardNode {
+ const children = card.children ?? [];
+ const start = children.findIndex(
+ (child) => child.type === "text" && child.content?.includes(prompt),
+ );
+ if (start < 0) return card;
+ const next = children.findIndex((child, index) => index > start && child.type === "text");
+ return { ...card, children: children.slice(start, next < 0 ? undefined : next) };
+}
+
function nodes(node: CardNode): CardNode[] {
return [node, ...(node.children ?? []).flatMap(nodes)];
}
diff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
index a7dd9efa4..25906acdf 100644
--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
@@ -33,6 +33,12 @@ interface ConformanceChannel {
readonly unsupported?: Partial<Record<HitlRule, string>>;
}
+const DISCORD_ALIAS: BrokenCell = {
+ reason:
+ "a press finds the session by its message id, and only the first message the bot posts is aliased to the session",
+ symptom: /Timed out waiting for \w+ to (return|run or be denied) on discord/,
+};
+
const TUI_TYPED_APPROVAL =
"the approval drawer holds the keyboard; a person answers it with y or n";
@@ -50,17 +56,39 @@ const TUI_TYPED_APPROVAL =
*/
const hitlConformance = {
"chat-sdk": [{ driver: chatSdkDriver }, { driver: chatSdkTextDriver }],
- discord: [{ driver: discordDriver }],
+ discord: [
+ {
+ driver: discordDriver,
+ broken: {
+ "pressing options of two pending questions answers each with its own option": DISCORD_ALIAS,
+ "pressing Approve on one of two pending approvals runs only that tool": DISCORD_ALIAS,
+ "answering an approval and a question pending together settles both": DISCORD_ALIAS,
+ },
+ },
+ ],
github: [{ driver: githubDriver }],
linear: [{ driver: linearDriver }],
linq: [{ driver: linqDriver }],
slack: [{ driver: slackDriver }],
teams: [{ driver: teamsDriver }],
- telegram: [{ driver: telegramDriver }],
+ telegram: [
+ {
+ driver: telegramDriver,
+ broken: {
+ "pressing an option of an answered question sends it to the agent as new input": {
+ reason:
+ "the first press consumes the button's callback id, so a later press is acknowledged and dropped",
+ symptom: /Timed out waiting for a reply to "Saturday" on telegram/,
+ },
+ },
+ },
+ ],
tui: [
{
driver: tuiDriver,
unsupported: {
+ "pressing an option of an answered question sends it to the agent as new input":
+ "an answered question's drawer closes, so nothing is left to press",
"a text reply of approve runs the gated tool": TUI_TYPED_APPROVAL,
"a text reply of cancel stops the gated tool without running it": TUI_TYPED_APPROVAL,
},
diff --git a/packages/eve/src/internal/testing/channel-conformance/contract.ts b/packages/eve/src/internal/testing/channel-conformance/contract.ts
index 6ee2ba8d3..51328285e 100644
--- a/packages/eve/src/internal/testing/channel-conformance/contract.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/contract.ts
@@ -4,7 +4,14 @@ import {
type ChannelCapability,
type ChannelConversation,
GATED_TOOL,
+ type RenderedOption,
+ SECOND_GATED_TOOL,
+ TWO_QUESTIONS_TOOL,
} from "#internal/testing/channel-conformance/harness.js";
+import {
+ DAY_PROMPT,
+ TIME_PROMPT,
+} from "#internal/testing/channel-conformance/two-questions-workflow.js";
/**
* One behavior every first-party channel owes a person, stated once and run
@@ -21,13 +28,19 @@ export interface ContractRule {
const ASK =
'Use ask_question and set question to: "Which day works for the review?" with label "Saturday" and label "Sunday".';
-const PROMPT = "Which day works for the review?";
+const PROMPT = DAY_PROMPT;
async function askWhichDay(conversation: ChannelConversation) {
await conversation.say(ASK);
return await conversation.waitForQuestion(PROMPT);
}
+const OPEN_PROMPT = "What should the review cover?";
+const ASK_OPEN = `Use ask_question and set question to: "${OPEN_PROMPT}"`;
+const OWN_WORDS = "Mostly the billing migration";
+
+const PLAN_REVIEW = `Use ${TWO_QUESTIONS_TOOL} to plan the review.`;
+
const DEPLOY = `Use ${GATED_TOOL} to ship the release.`;
// Channels word the two approval choices differently; the TUI asks Yes or No.
const APPROVE_LABELS = ["Approve", "Yes"];
@@ -39,13 +52,39 @@ async function askToDeploy(conversation: ChannelConversation) {
return await conversation.waitForQuestion(APPROVAL_PROMPT);
}
+const PUBLISH_PROMPT = "Approve Publish notes?";
+
+const DEPLOY_AND_PUBLISH = `Call tools in parallel: ${GATED_TOOL}, ${SECOND_GATED_TOOL}`;
+const ASK_AND_DEPLOY = `Call tools in parallel: ask_question, ${GATED_TOOL}\n${ASK}`;
+
+/** Answers each prompt with its option, in whatever order the client shows them. */
+function answerEach(
+ conversation: ChannelConversation,
+ choices: Record<string, string | readonly string[]>,
+): Promise<void> {
+ return conversation.answerEach(Object.keys(choices), (prompt, options) =>
+ option(options, choices[prompt]!),
+ );
+}
+
+/** The option a person would press for `label`, or any of its channel-specific wordings. */
+function option(
+ options: readonly RenderedOption[] | undefined,
+ label: string | readonly string[],
+): RenderedOption {
+ const labels = typeof label === "string" ? [label] : label;
+ const found = options?.find((candidate) => labels.includes(candidate.label));
+ expect(found, `a ${labels.join(" or ")} option to press`).toBeDefined();
+ return found!;
+}
+
async function expectDeployed(conversation: ChannelConversation) {
const outcome = await conversation.waitForToolOutcome(GATED_TOOL);
expect(outcome, `${GATED_TOOL} settled as ${JSON.stringify(outcome)}`).toEqual({
kind: "ran",
output: { deployed: true },
});
- expect(conversation.gatedToolRuns).toBe(1);
+ expect(conversation.runsOf(GATED_TOOL)).toBe(1);
}
async function expectNotDeployed(conversation: ChannelConversation) {
@@ -53,17 +92,21 @@ async function expectNotDeployed(conversation: ChannelConversation) {
expect(outcome, `${GATED_TOOL} settled as ${JSON.stringify(outcome)}`).toEqual({
kind: "denied",
});
- expect(conversation.gatedToolRuns).toBe(0);
+ expect(conversation.runsOf(GATED_TOOL)).toBe(0);
}
-function expectAnsweredSaturday(output: unknown) {
+function expectAnswered(output: unknown, answer: string) {
// The message carries the real output so a broken cell's symptom can match it.
expect(output, `ask_question returned ${JSON.stringify(output)}`).toEqual({
- answer: "Saturday",
+ answer,
status: "answered",
});
}
+function expectAnsweredSaturday(output: unknown) {
+ expectAnswered(output, "Saturday");
+}
+
export const hitlContract = [
{
rule: "a rendered question shows every option a person can choose",
@@ -99,6 +142,68 @@ export const hitlContract = [
expectAnsweredSaturday(await conversation.waitForToolResult("ask_question"));
},
},
+ {
+ rule: "a text reply that matches no option answers the question with the person's words",
+ source: "docs/tools/human-in-the-loop.md#questions",
+ requires: ["text-replies"],
+ async run(conversation) {
+ await askWhichDay(conversation);
+ await conversation.say(OWN_WORDS);
+ expectAnswered(await conversation.waitForToolResult("ask_question"), OWN_WORDS);
+ },
+ },
+ {
+ rule: "a text reply answers an open-ended question with the person's words",
+ source: "docs/tools/human-in-the-loop.md#questions",
+ requires: ["text-replies"],
+ async run(conversation) {
+ await conversation.say(ASK_OPEN);
+ await conversation.waitForQuestion(OPEN_PROMPT);
+ await conversation.say(OWN_WORDS);
+ expectAnswered(await conversation.waitForToolResult("ask_question"), OWN_WORDS);
+ },
+ },
+ {
+ rule: "pressing an option of an answered question sends it to the agent as new input",
+ source: "docs/tools/workflows.mdx#ask-a-human-ctxask",
+ requires: ["buttons"],
+ async run(conversation) {
+ const options = await askWhichDay(conversation);
+ const saturday = options.find((option) => option.label === "Saturday");
+ expect(saturday, "a Saturday option to press").toBeDefined();
+ await conversation.press(saturday!);
+ expectAnsweredSaturday(await conversation.waitForToolResult("ask_question"));
+ await conversation.press(saturday!);
+ await conversation.waitForReplyTo("Saturday");
+ },
+ },
+ {
+ rule: "pressing options of two pending questions answers each with its own option",
+ source: "docs/tools/workflows.mdx#ask-a-human-ctxask",
+ requires: ["buttons"],
+ async run(conversation) {
+ await conversation.say(PLAN_REVIEW);
+ await answerEach(conversation, { [DAY_PROMPT]: "Saturday", [TIME_PROMPT]: "Afternoon" });
+ const output = await conversation.waitForToolResult(TWO_QUESTIONS_TOOL);
+ expect(output, `${TWO_QUESTIONS_TOOL} returned ${JSON.stringify(output)}`).toEqual({
+ day: "Saturday",
+ time: "Afternoon",
+ });
+ },
+ },
+ {
+ rule: "a text reply matching an option does not answer either of two pending questions",
+ source: "docs/tools/human-in-the-loop.md#how-pause-and-resume-works",
+ requires: ["text-replies"],
+ async run(conversation) {
+ await conversation.say(PLAN_REVIEW);
+ await conversation.waitForRequest(DAY_PROMPT);
+ await conversation.waitForRequest(TIME_PROMPT);
+ await conversation.say("Saturday");
+ // Answering only the day question would leave the tool waiting, with no reply.
+ await conversation.waitForReplyTo("Saturday");
+ },
+ },
{
rule: "a tool approval shows a choice to approve and one to cancel",
source: "docs/tools/human-in-the-loop.md#approvals",
@@ -130,6 +235,47 @@ export const hitlContract = [
await expectDeployed(conversation);
},
},
+ {
+ rule: "pressing Approve twice runs the gated tool once",
+ source: "docs/tools/human-in-the-loop.md#approvals",
+ requires: ["buttons"],
+ async run(conversation) {
+ const options = await askToDeploy(conversation);
+ const approve = option(options, APPROVE_LABELS);
+ await conversation.press(approve);
+ await conversation.press(approve);
+ await expectDeployed(conversation);
+ // However the channel reads the second press, the session must finish with it.
+ await conversation.waitForRest();
+ expect(conversation.runsOf(GATED_TOOL)).toBe(1);
+ },
+ },
+ {
+ rule: "pressing Approve on one of two pending approvals runs only that tool",
+ source: "docs/tools/human-in-the-loop.md#approvals",
+ requires: ["buttons"],
+ async run(conversation) {
+ await conversation.say(DEPLOY_AND_PUBLISH);
+ await answerEach(conversation, {
+ [APPROVAL_PROMPT]: APPROVE_LABELS,
+ [PUBLISH_PROMPT]: CANCEL_LABELS,
+ });
+ // Results reach the model in the order they settle, so the reply names the approved call.
+ await expectDeployed(conversation);
+ expect(conversation.runsOf(SECOND_GATED_TOOL)).toBe(0);
+ },
+ },
+ {
+ rule: "answering an approval and a question pending together settles both",
+ source: "docs/tools/human-in-the-loop.md#how-pause-and-resume-works",
+ requires: ["buttons"],
+ async run(conversation) {
+ await conversation.say(ASK_AND_DEPLOY);
+ await answerEach(conversation, { [APPROVAL_PROMPT]: APPROVE_LABELS, [PROMPT]: "Saturday" });
+ // The turn replies only once both calls settle.
+ await expectDeployed(conversation);
+ },
+ },
{
rule: "pressing Cancel stops the gated tool without running it",
source: "docs/tools/human-in-the-loop.md#approvals",
diff --git a/packages/eve/src/internal/testing/channel-conformance/harness.ts b/packages/eve/src/internal/testing/channel-conformance/harness.ts
index 1e2f88138..65ca56f56 100644
--- a/packages/eve/src/internal/testing/channel-conformance/harness.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/harness.ts
@@ -14,6 +14,8 @@ import { z } from "#compiled/zod/index.js";
import { always } from "#tools/approval/policies.js";
import { defineTool } from "#tools/definition.js";
import { askQuestion } from "#tools/provided/ask-question.js";
+import { defineWorkflowTool } from "#public/tools/index.js";
+import { askDayAndTimeWorkflow } from "#internal/testing/channel-conformance/two-questions-workflow.js";
import { getWorld } from "#internal/workflow/runtime.js";
/** One outbound call a channel made to its platform API. */
@@ -88,14 +90,31 @@ export interface ChannelConversation {
say(text: string): Promise<void>;
/** Waits for the bot to post `prompt` with choices, returning them. */
waitForQuestion(prompt: string): Promise<readonly RenderedOption[]>;
+ /**
+ * Answers each of `prompts` with the option `choose` picks, in whatever order
+ * the client shows them.
+ */
+ answerEach(
+ prompts: readonly string[],
+ choose: (prompt: string, options: readonly RenderedOption[]) => RenderedOption,
+ ): Promise<void>;
+ /**
+ * Waits until the turn holds for `prompt`, whether or not the client shows it
+ * 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>;
/** 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. */
+ waitForReplyTo(text: string): Promise<void>;
/** Waits until the bot's reply shows `tool` ran or was denied. */
waitForToolOutcome(tool: string): Promise<ToolOutcome>;
- /** How many times {@link GATED_TOOL} actually executed, as its side effect would show. */
- readonly gatedToolRuns: number;
+ /** Waits until every session has stopped working and waits only on a person. */
+ waitForRest(): Promise<void>;
+ /** How many times a gated tool actually executed, as its side effect would show. */
+ runsOf(tool: GatedTool): number;
}
/**
@@ -117,8 +136,11 @@ export interface ClientDriver {
export interface ClientView {
/** The person sends a plain-text message. */
say(text: string): Promise<void>;
- /** Waits for the client to show `prompt` with choices, returning them. */
- waitForQuestion(prompt: string): Promise<readonly RenderedOption[]>;
+ /**
+ * Waits for the client to show one of `prompts`, returning which one and its
+ * 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>;
/** The bot replies the client shows now. */
@@ -129,6 +151,12 @@ export interface ClientView {
close(): Promise<void>;
}
+/** A question a client shows, with the choices it offers. */
+export interface ShownQuestion {
+ readonly options: readonly RenderedOption[];
+ readonly prompt: string;
+}
+
/**
* Polls `select` until it returns a value. On timeout, the error names
* `label`, the driver, and `describe()`'s account of what a person sees.
@@ -151,6 +179,14 @@ const CLIENT_HOST = "https://agent.example.com";
/** The test agent's tool that always needs a person's approval before it runs. */
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;
+
+/** The test agent's tool that asks {@link DAY_PROMPT} and {@link TIME_PROMPT} at once. */
+export const TWO_QUESTIONS_TOOL = "plan_review";
+
/** What a person sees once a tool call settles. */
export type ToolOutcome =
| { readonly kind: "ran"; readonly output: unknown }
@@ -241,13 +277,15 @@ function webhookView(
return {
say: (text) => post(driver.message(text)),
press: (option) => post(driver.press(option)),
- waitForQuestion: (prompt) =>
+ waitForQuestion: (prompts) =>
wait(
- `the question "${prompt}"`,
+ `one of the questions ${JSON.stringify(prompts)}`,
() => {
for (const call of calls) {
- const options = driver.findOptions(call, prompt);
- if (options !== undefined) return options;
+ for (const prompt of prompts) {
+ const options = driver.findOptions(call, prompt);
+ if (options !== undefined) return { options, prompt };
+ }
}
return undefined;
},
@@ -300,7 +338,7 @@ async function converse(
): Promise<void> {
if (!isCompiledChannel(created)) throw new Error(`${label} is not a compiled channel.`);
const channel: CompiledChannel = created;
- let gatedToolRuns = 0;
+ const runs: Record<GatedTool, number> = { [GATED_TOOL]: 0, [SECOND_GATED_TOOL]: 0 };
const runtime = await createTestRuntime({
agent: { name: `${label}-hitl-conformance` },
@@ -309,17 +347,21 @@ async function converse(
logicalPath: "tools/ask_question.ts",
loadNamespace: async () => ({ default: askQuestion() }),
},
+ gatedTool(GATED_TOOL, "Deploys a release.", () => {
+ runs[GATED_TOOL] += 1;
+ return { deployed: true };
+ }),
+ gatedTool(SECOND_GATED_TOOL, "Publishes release notes.", () => {
+ runs[SECOND_GATED_TOOL] += 1;
+ return { published: true };
+ }),
{
- logicalPath: `tools/${GATED_TOOL}.ts`,
+ logicalPath: `tools/${TWO_QUESTIONS_TOOL}.ts`,
loadNamespace: async () => ({
- default: defineTool({
- approval: always(),
- description: `Deploys a release. Only call when asked to use ${GATED_TOOL}.`,
- async execute() {
- gatedToolRuns += 1;
- return { deployed: true };
- },
- inputSchema: z.object({ release: z.string().optional() }),
+ default: defineWorkflowTool({
+ description: `Plans a review. Only call when asked to use ${TWO_QUESTIONS_TOOL}.`,
+ execute: askDayAndTimeWorkflow,
+ inputSchema: z.object({}),
}),
}),
},
@@ -401,8 +443,6 @@ async function converse(
return { response, settled };
};
- /** How many times each session's turn has held for input, as of the last wait. */
- const inputHolds = new Map<string, number>();
const view = await open(dispatch);
const replyWait = <T>(label: string, select: (reply: string) => T | undefined) =>
wait(
@@ -421,21 +461,34 @@ async function converse(
say: (text) => view.say(text),
press: (option) => view.press(option),
async waitForQuestion(prompt) {
- const options = await view.waitForQuestion(prompt);
- await holdForInput();
+ const { options } = await view.waitForQuestion([prompt]);
+ await holdForInput(prompt);
return options;
},
+ async answerEach(prompts, choose) {
+ const remaining = [...prompts];
+ while (remaining.length > 0) {
+ const { options, prompt } = await view.waitForQuestion(remaining);
+ await holdForInput(prompt);
+ await view.press(choose(prompt, options));
+ remaining.splice(remaining.indexOf(prompt), 1);
+ }
+ },
+ waitForRequest: (prompt) => holdForInput(prompt),
waitForToolResult: (tool) =>
replyWait(`${tool} to return`, (reply) => readMockToolReply(reply, tool)),
+ waitForReplyTo: (message) =>
+ replyWait(`a reply to "${message}"`, (reply) =>
+ isMockReplyTo(reply, message) ? true : undefined,
+ ).then(() => {}),
waitForToolOutcome: (tool) =>
replyWait(`${tool} to run or be denied`, (reply): ToolOutcome | undefined => {
const output = readMockToolReply(reply, tool);
if (output !== undefined) return { kind: "ran", output };
return isMockDenialReply(reply) ? { kind: "denied" } : undefined;
}),
- get gatedToolRuns() {
- return gatedToolRuns;
- },
+ runsOf: (tool) => runs[tool],
+ waitForRest: () => waitForRest([...sessions.values()], wait),
};
/**
@@ -463,16 +516,12 @@ async function converse(
* the question appears races the turn's own bookkeeping for it; see also
* {@link waitForAddress}.
*/
- function holdForInput(): Promise<true> {
- return wait(
- "the turn to hold for input",
+ async function holdForInput(prompt: string): Promise<void> {
+ await wait(
+ `the turn to hold for "${prompt}"`,
async () => {
for (const session of sessions.values()) {
- const holds = await countInputHolds(session);
- if (holds > (inputHolds.get(session.id) ?? 0)) {
- inputHolds.set(session.id, holds);
- return true;
- }
+ if (await holdsFor(session, prompt)) return true;
}
return undefined;
},
@@ -521,21 +570,90 @@ async function cancelUntilResting(session: Session): Promise<void> {
throw new Error(`Timed out waiting for session ${session.id} to rest.`);
}
-async function countInputHolds(session: Session): Promise<number> {
+/** How long a session's stream must stay unchanged to count as resting. */
+const REST_QUIET_MS = 250;
+
+/**
+ * Waits until each session's stream ends waiting on its next message or on a
+ * person, with no step running, and stays that way. A response just delivered
+ * may not have reached the stream yet, so one quiet read is not enough.
+ */
+async function waitForRest(sessions: readonly Session[], wait: Wait): Promise<void> {
+ const world = await getWorld();
+ let quietSince: number | undefined;
+ let lastTails = "";
+ await wait(
+ "every session to rest",
+ async () => {
+ const states = await Promise.all(
+ sessions.map(async (session) => {
+ const tail = await session.getStreamTailIndex();
+ const reader = (await session.getEventStream({ startIndex: tail })).getReader();
+ const last = await reader.read().finally(() => reader.cancel());
+ const waiting =
+ last.value?.type === "session.waiting" ||
+ (last.value?.type === "turn.waiting" && last.value.data.on === "input");
+ const steps = await world.steps.list({ resolveData: "none", runId: session.id });
+ const idle = steps.data.every((step) => TERMINAL_STEP_STATUSES.has(step.status));
+ return { resting: waiting && idle, tail };
+ }),
+ );
+ const tails = states.map((state) => state.tail).join(",");
+ const quiet = states.every((state) => state.resting) && tails === lastTails;
+ lastTails = tails;
+ if (!quiet) {
+ quietSince = undefined;
+ return undefined;
+ }
+ quietSince ??= Date.now();
+ return Date.now() - quietSince >= REST_QUIET_MS ? true : undefined;
+ },
+ () => "",
+ );
+}
+
+/**
+ * Whether the turn held for input after it last asked `prompt`. The turn emits
+ * `turn.waiting` after each request, or once after requests raised together.
+ */
+async function holdsFor(session: Session, prompt: string): Promise<boolean> {
const tail = await session.getStreamTailIndex();
- if (tail < 0) return 0;
+ if (tail < 0) return false;
const reader = (await session.getEventStream({ startIndex: 0 })).getReader();
- let holds = 0;
+ let asked = false;
+ let held = false;
try {
for (let index = 0; index <= tail; index += 1) {
const { done, value } = await reader.read();
if (done) break;
- if (value.type === "turn.waiting" && value.data.on === "input") holds += 1;
+ if (
+ value.type === "input.requested" &&
+ value.data.requests.some((request) => request.prompt === prompt)
+ ) {
+ asked = true;
+ held = false;
+ } else if (asked && value.type === "turn.waiting" && value.data.on === "input") {
+ held = true;
+ }
}
} finally {
await reader.cancel();
}
- return holds;
+ return held;
+}
+
+function gatedTool(name: GatedTool, description: string, execute: () => unknown) {
+ return {
+ logicalPath: `tools/${name}.ts`,
+ loadNamespace: async () => ({
+ default: defineTool({
+ approval: always(),
+ description: `${description} Only call when asked to use ${name}.`,
+ execute: async () => execute(),
+ inputSchema: z.object({ release: z.string().optional() }),
+ }),
+ }),
+ };
}
function findRoute(channel: CompiledChannel, request: Request) {
@@ -584,6 +702,14 @@ export function readMockToolReply(text: string, tool: string): unknown {
}
}
+/**
+ * Without a tool to call, the test model replies `Bootstrap reply: <input>`,
+ * echoing the input with any context the channel wrapped around it.
+ */
+function isMockReplyTo(text: string, message: string): boolean {
+ return text.startsWith("Bootstrap reply") && text.includes(message);
+}
+
/** The test model reports a denied call's `execution-denied` result in its reply. */
function isMockDenialReply(text: string): boolean {
return text.includes('"type":"execution-denied"');
diff --git a/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts b/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts
index 6d19f7c15..8bd575139 100644
--- a/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts
@@ -125,17 +125,20 @@ export function slackDriver(): ChannelDriver {
if (body.blocks === undefined || !JSON.stringify(body.blocks).includes(prompt))
return undefined;
const messageTs = (call.response as { readonly ts: string }).ts;
- const options = body.blocks.flatMap((block) =>
- // Questions use `actions` blocks (`elements`); approval cards keep buttons in `actions`.
- (
- (block as { readonly elements?: readonly SlackElement[] }).elements ??
- (block as { readonly actions?: readonly SlackElement[] }).actions ??
- []
- )
- .filter((element) => element.action_id.startsWith(HITL_ACTION_PREFIX))
- .flatMap((element) => renderedOptions(element, messageTs)),
- );
- return options.length === 0 ? undefined : options;
+ const optionsIn = (blocks: readonly unknown[]) =>
+ blocks.flatMap((block) =>
+ // Questions use `actions` blocks (`elements`); approval cards keep buttons in `actions`.
+ (
+ (block as { readonly elements?: readonly SlackElement[] }).elements ??
+ (block as { readonly actions?: readonly SlackElement[] }).actions ??
+ []
+ )
+ .filter((element) => element.action_id.startsWith(HITL_ACTION_PREFIX))
+ .flatMap((element) => renderedOptions(element, messageTs)),
+ );
+ // A batch of approvals posts one card per request, each holding its own buttons.
+ const card = optionsIn(body.blocks.filter((block) => JSON.stringify(block).includes(prompt)));
+ return card.length > 0 ? card : optionsIn(body.blocks);
},
press: (option) => {
const { action, messageTs } = option.handle as PressHandle;
diff --git a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts
index a724288c5..7d832c80d 100644
--- a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts
@@ -61,8 +61,9 @@ export function telegramDriver(): ChannelDriver {
readonly text?: string;
};
if (call.method !== "sendMessage" || body.text?.includes(prompt) !== true) return undefined;
- return body.reply_markup?.inline_keyboard
- ?.flat()
+ // An open-ended question posts a ForceReply prompt with no keyboard.
+ return (body.reply_markup?.inline_keyboard ?? [])
+ .flat()
.filter((button) => button.callback_data !== undefined)
.map((button) => ({ handle: button.callback_data, label: button.text }));
},
diff --git a/packages/eve/src/internal/testing/channel-conformance/tui-driver.ts b/packages/eve/src/internal/testing/channel-conformance/tui-driver.ts
index 1fd0601e9..b3e03c710 100644
--- a/packages/eve/src/internal/testing/channel-conformance/tui-driver.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/tui-driver.ts
@@ -7,11 +7,16 @@ import type {
RenderedOption,
} from "#internal/testing/channel-conformance/harness.js";
-/** Each drawer's footer: a question's, then a tool approval's. */
+/** An open-ended question's drawer: a text field and no options. */
+const FREEFORM_FOOTER = "Enter submit · Esc dismiss";
+/** Each drawer's footer: a question's, a tool approval's, then an open-ended question's. */
const DRAWER_FOOTERS = [
"↑/↓ move · enter to select · esc to dismiss",
"y yes · n no · Ctrl-C cancel",
+ FREEFORM_FOOTER,
] as const;
+/** More drawers than any rule leaves pending at once. */
+const MAX_DRAWERS = 5;
const FREEFORM_ROW = "Type your own answer…";
/**
@@ -51,15 +56,31 @@ export function tuiDriver(): ClientDriver {
return {
async say(text) {
- // A question drawer holds the keyboard until Esc hands it back to the composer.
- if (drawerOpen(screen)) keyboard.send("\x1b");
+ // A drawer holds the keyboard until Esc hands it back to the composer.
+ // Dismissing one shows the next pending request's, if any.
+ // Esc in the composer cancels the turn, so wait out each repaint first.
+ for (let drawers = 0; drawers < MAX_DRAWERS && drawerOpen(screen); drawers += 1) {
+ const before = screen.snapshot();
+ keyboard.send("\x1b");
+ await wait(
+ "the drawer to close",
+ () => (screen.snapshot() !== before ? true : undefined),
+ describe,
+ );
+ }
await wait("the composer", () => (composerOpen(screen) ? true : undefined), describe);
- keyboard.type(text);
+ // A typed newline submits, so multi-line text arrives as a bracketed paste.
+ keyboard.send(text.includes("\n") ? `\x1b[200~${text}\x1b[201~` : text);
keyboard.enter();
},
- async waitForQuestion(prompt) {
- await wait(`the question "${prompt}"`, () => focusedRow(screen, prompt), describe);
- return readOptions(screen, keyboard, prompt);
+ async waitForQuestion(prompts) {
+ const prompt = await wait(
+ `one of the questions ${JSON.stringify(prompts)}`,
+ () => prompts.find((candidate) => focusedRow(screen, candidate) !== undefined),
+ describe,
+ );
+ if (screen.snapshot().includes(FREEFORM_FOOTER)) return { options: [], prompt };
+ return { options: readOptions(screen, keyboard, prompt), prompt };
},
async press(option) {
// `waitForQuestion` leaves the cursor on the first option.
diff --git a/packages/eve/src/internal/testing/channel-conformance/two-questions-workflow.ts b/packages/eve/src/internal/testing/channel-conformance/two-questions-workflow.ts
new file mode 100644
index 000000000..0b79162ae
--- /dev/null
+++ b/packages/eve/src/internal/testing/channel-conformance/two-questions-workflow.ts
@@ -0,0 +1,29 @@
+import type { ToolInputResponse, WorkflowToolContext } from "#public/tools/index.js";
+
+export const DAY_PROMPT = "Which day works for the review?";
+export const TIME_PROMPT = "Which time works for the review?";
+
+/**
+ * Asks two questions at once, so both are pending together. The test tier's
+ * bundler registers this `"use workflow"` body, as it would an app's tool.
+ */
+export async function askDayAndTimeWorkflow(
+ _input: unknown,
+ ctx: WorkflowToolContext,
+): Promise<{ readonly day: string; readonly time: string }> {
+ "use workflow";
+
+ const [day, time] = await Promise.all([
+ ctx.ask({ display: "select", options: choices("Saturday", "Sunday"), prompt: DAY_PROMPT }),
+ ctx.ask({ display: "select", options: choices("Morning", "Afternoon"), prompt: TIME_PROMPT }),
+ ]);
+ return { day: summarize(day), time: summarize(time) };
+}
+
+function choices(...labels: string[]) {
+ return labels.map((label) => ({ id: label, label }));
+}
+
+function summarize(answer: ToolInputResponse): string {
+ return answer.status === "answered" ? (answer.optionId ?? answer.text ?? "") : answer.status;
+}