Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[4/7] fix(eve): clear an answered prompt's buttons on Telegram, Discord, Teams, and Chat SDK (#4246)

Ben Pankow28f406311ce0
diff --git a/.changeset/answered-prompts-clear-buttons.md b/.changeset/answered-prompts-clear-buttons.md
new file mode 100644
index 000000000..34076bd35
--- /dev/null
+++ b/.changeset/answered-prompts-clear-buttons.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Telegram, Discord, Teams, and `chatSdkChannel` now remove a question's or approval's buttons once it's answered and show the outcome, such as `Approved` or `Answered: Saturday`. This covers pressed buttons, typed replies, and requests withdrawn when a turn is cancelled. Adapters that can't edit messages keep the original prompt.
diff --git a/packages/eve/src/channel/resolved-prompt.ts b/packages/eve/src/channel/resolved-prompt.ts
new file mode 100644
index 000000000..0c7c4e08c
--- /dev/null
+++ b/packages/eve/src/channel/resolved-prompt.ts
@@ -0,0 +1,39 @@
+import type { InputResolution } from "#protocol/message.js";
+import type { InputOption } from "#shared/input.js";
+
+type PromptOption = Pick<InputOption, "id" | "label">;
+
+/**
+ * How eve resolved a posted prompt, such as `Approved` or a chosen option's
+ * label. A request that ends without an answer, such as one withdrawn when its
+ * turn is cancelled, is no longer needed.
+ */
+export function resolvedPromptAnswer(
+ resolution: InputResolution,
+ options: readonly PromptOption[] = [],
+): string | undefined {
+ switch (resolution.outcome) {
+ case "approved":
+ return "Approved";
+ case "denied":
+ return "Cancelled";
+ case "answered": {
+ const response = resolution.response;
+ return options.find((option) => option.id === response?.optionId)?.label ?? response?.text;
+ }
+ default:
+ return "No longer needed";
+ }
+}
+
+/** The line a prompt shows once resolved, such as `Approved` or `Answered: Saturday`. */
+export function resolvedPromptLabel(
+ resolution: InputResolution,
+ options: readonly PromptOption[] = [],
+): string {
+ const answer = resolvedPromptAnswer(resolution, options);
+ if (resolution.outcome === "answered") {
+ return answer === undefined ? "Answered" : `Answered: ${answer}`;
+ }
+ return answer ?? "";
+}
diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
index 32d99c7ba..8c0d336b1 100644
--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
@@ -32,46 +32,33 @@ needs, or the client declines it below)
| pressing Cancel stops the gated tool without running it | ✅ | — | ✅ | — | — | — | ✅ | ✅ | ✅ | ✅ | — |
| a text reply of approve runs the gated tool | ✅ | ✅ | — | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — | ✅ |
| a text reply of cancel stops the gated tool without running it | ✅ | ✅ | — | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — | ✅ |
-| pressing an option clears the question's buttons | ❌ | — | ❌ | — | — | — | ✅ | ❌ | ❌ | ✅ | — |
-| answering a question by text clears its buttons | ❌ | — | — | — | — | — | ❌ | ❌ | ❌ | ✅ | — |
+| pressing an option clears the question's buttons | ✅ | — | ✅ | — | — | — | ✅ | ✅ | ✅ | ✅ | — |
+| answering a question by text clears its buttons | ✅ | — | — | — | — | — | ❌ | ✅ | ✅ | ✅ | — |
| pressing an option names who answered on the question | ❌ | — | ❌ | — | — | — | ✅ | ❌ | ❌ | — | — |
| answering a question by text names who answered on the question | ❌ | — | — | — | — | — | ❌ | ❌ | ❌ | — | — |
-| pressing Approve clears the approval's buttons | ❌ | — | ❌ | — | — | — | ✅ | ✅ | ❌ | ✅ | — |
-| approving by text clears the approval's buttons | ❌ | — | — | — | — | — | ✅ | ❌ | ❌ | — | — |
+| pressing Approve clears the approval's buttons | ✅ | — | ✅ | — | — | — | ✅ | ✅ | ✅ | ✅ | — |
+| approving by text clears the approval's buttons | ✅ | — | — | — | — | — | ✅ | ✅ | ✅ | — | — |
| pressing Approve names who approved on the approval | ❌ | — | ❌ | — | — | — | ✅ | ✅ | ❌ | — | — |
| approving by text names who approved on the approval | ❌ | — | — | — | — | — | ❌ | ❌ | ❌ | — | — |
## Broken
-- **chat-sdk**, pressing an option clears the question's buttons: the bridge never edits an answered prompt
-- **chat-sdk**, answering a question by text clears its buttons: the bridge never edits an answered prompt
-- **chat-sdk**, pressing an option names who answered on the question: the bridge never edits an answered prompt
-- **chat-sdk**, answering a question by text names who answered on the question: the bridge never edits an answered prompt
-- **chat-sdk**, pressing Approve clears the approval's buttons: the bridge never edits an answered prompt
-- **chat-sdk**, approving by text clears the approval's buttons: the bridge never edits an answered prompt
-- **chat-sdk**, pressing Approve names who approved on the approval: the bridge never edits an answered prompt
-- **chat-sdk**, approving by text names who approved on the approval: the bridge never edits an answered prompt
-- **discord**, pressing an option clears the question's buttons: a press gets a deferred update and the message is never edited
-- **discord**, pressing an option names who answered on the question: a press gets a deferred update and the message is never edited
-- **discord**, pressing Approve clears the approval's buttons: a press gets a deferred update and the message is never edited
-- **discord**, pressing Approve names who approved on the approval: a press gets a deferred update and the message is never edited
+- **chat-sdk**, pressing an option names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **chat-sdk**, answering a question by text names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **chat-sdk**, pressing Approve names who approved on the approval: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **chat-sdk**, approving by text names who approved on the approval: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **discord**, pressing an option names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **discord**, pressing Approve names who approved on the approval: a resolved prompt doesn't say who answered; input.resolved carries no responder
- **slack**, answering a question by text clears its buttons: only the button interaction handler edits a question; a typed answer leaves it
- **slack**, answering a question by text names who answered on the question: only the button interaction handler edits a question; a typed answer leaves it
- **slack**, approving by text names who approved on the approval: the card loses its buttons after a typed approval but doesn't say who approved
-- **teams**, pressing an option clears the question's buttons: only a pressed approval card is recorded for editing; questions and typed approvals are not
-- **teams**, answering a question by text clears its buttons: only a pressed approval card is recorded for editing; questions and typed approvals are not
-- **teams**, pressing an option names who answered on the question: only a pressed approval card is recorded for editing; questions and typed approvals are not
-- **teams**, answering a question by text names who answered on the question: only a pressed approval card is recorded for editing; questions and typed approvals are not
-- **teams**, approving by text clears the approval's buttons: only a pressed approval card is recorded for editing; questions and typed approvals are not
-- **teams**, approving by text names who approved on the approval: only a pressed approval card is recorded for editing; questions and typed approvals are not
-- **telegram**, pressing an option clears the question's buttons: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, answering a question by text clears its buttons: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, pressing an option names who answered on the question: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, answering a question by text names who answered on the question: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, pressing Approve clears the approval's buttons: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, approving by text clears the approval's buttons: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, pressing Approve names who approved on the approval: nothing edits an answered prompt; a press only answers the callback query
-- **telegram**, approving by text names who approved on the approval: nothing edits an answered prompt; a press only answers the callback query
+- **teams**, pressing an option names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **teams**, answering a question by text names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **teams**, approving by text names who approved on the approval: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **telegram**, pressing an option names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **telegram**, answering a question by text names who answered on the question: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **telegram**, pressing Approve names who approved on the approval: a resolved prompt doesn't say who answered; input.resolved carries no responder
+- **telegram**, approving by text names who approved on the approval: a resolved prompt doesn't say who answered; input.resolved carries no responder
## Declined
diff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
index 5152f8d2c..98cbd779a 100644
--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
@@ -28,32 +28,34 @@ export interface BrokenCell {
/** Rules that check how an answered prompt's message changes, by prompt kind and how it was answered. */
const answeredPromptRules = {
- approvalPress: [
- "pressing Approve clears the approval's buttons",
- "pressing Approve names who approved on the approval",
- ],
- approvalText: [
- "approving by text clears the approval's buttons",
- "approving by text names who approved on the approval",
- ],
- questionPress: [
- "pressing an option clears the question's buttons",
- "pressing an option names who answered on the question",
- ],
- questionText: [
- "answering a question by text clears its buttons",
- "answering a question by text names who answered on the question",
- ],
-} as const satisfies Record<string, readonly HitlRule[]>;
+ approvalPress: {
+ cleared: "pressing Approve clears the approval's buttons",
+ named: "pressing Approve names who approved on the approval",
+ },
+ approvalText: {
+ cleared: "approving by text clears the approval's buttons",
+ named: "approving by text names who approved on the approval",
+ },
+ questionPress: {
+ cleared: "pressing an option clears the question's buttons",
+ named: "pressing an option names who answered on the question",
+ },
+ questionText: {
+ cleared: "answering a question by text clears its buttons",
+ named: "answering a question by text names who answered on the question",
+ },
+} as const satisfies Record<string, { readonly cleared: HitlRule; readonly named: HitlRule }>;
+
+type AnsweredPrompt = keyof typeof answeredPromptRules;
/** Answered prompts in `groups` are never edited, so they keep their buttons and never say who answered. */
function staleAnsweredPrompts(
reason: string,
- groups: readonly (keyof typeof answeredPromptRules)[],
+ groups: readonly AnsweredPrompt[],
): Partial<Record<HitlRule, BrokenCell>> {
return Object.fromEntries(
groups
- .flatMap((group) => answeredPromptRules[group])
+ .flatMap((group) => Object.values(answeredPromptRules[group]))
.map((rule) => [
rule,
{
@@ -64,6 +66,19 @@ function staleAnsweredPrompts(
);
}
+/** Answered prompts in `groups` lose their buttons, but the edit doesn't say who answered. */
+function unnamedAnsweredPrompts(
+ reason: string,
+ groups: readonly AnsweredPrompt[],
+): Partial<Record<HitlRule, BrokenCell>> {
+ return Object.fromEntries(
+ groups.map((group) => [
+ answeredPromptRules[group].named,
+ { reason, symptom: /the answered prompt never names who answered/ },
+ ]),
+ );
+}
+
interface ConformanceChannel {
readonly driver: () => ChannelDriver | ClientDriver;
readonly broken?: Partial<Record<HitlRule, BrokenCell>>;
@@ -91,20 +106,18 @@ const hitlConformance = {
"chat-sdk": [
{
driver: chatSdkDriver,
- broken: staleAnsweredPrompts("the bridge never edits an answered prompt", [
- "approvalPress",
- "approvalText",
- "questionPress",
- "questionText",
- ]),
+ broken: unnamedAnsweredPrompts(
+ "a resolved prompt doesn't say who answered; input.resolved carries no responder",
+ ["approvalPress", "approvalText", "questionPress", "questionText"],
+ ),
},
{ driver: chatSdkTextDriver },
],
discord: [
{
driver: discordDriver,
- broken: staleAnsweredPrompts(
- "a press gets a deferred update and the message is never edited",
+ broken: unnamedAnsweredPrompts(
+ "a resolved prompt doesn't say who answered; input.resolved carries no responder",
["approvalPress", "questionPress"],
),
},
@@ -130,8 +143,8 @@ const hitlConformance = {
teams: [
{
driver: teamsDriver,
- broken: staleAnsweredPrompts(
- "only a pressed approval card is recorded for editing; questions and typed approvals are not",
+ broken: unnamedAnsweredPrompts(
+ "a resolved prompt doesn't say who answered; input.resolved carries no responder",
["approvalText", "questionPress", "questionText"],
),
},
@@ -139,8 +152,8 @@ const hitlConformance = {
telegram: [
{
driver: telegramDriver,
- broken: staleAnsweredPrompts(
- "nothing edits an answered prompt; a press only answers the callback query",
+ broken: unnamedAnsweredPrompts(
+ "a resolved prompt doesn't say who answered; input.resolved carries no responder",
["approvalPress", "approvalText", "questionPress", "questionText"],
),
},
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index 0f427daac..22f7c957d 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -9,7 +9,8 @@ import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+import type { InputResolution, UnstampedMessageStreamEvent } from "#protocol/message.js";
+import type { InputRequest } from "#shared/input.js";
import {
type InputResponse,
parseInputResponses,
@@ -73,9 +74,17 @@ export interface ChatSdkChannelState extends Record<string, unknown> {
pendingToolCallMessage?: string | null;
/** Authorization status messages, keyed by connection name. */
pendingAuthMessageIds?: Record<string, string>;
+ /** Posted input request cards, keyed by message id, until eve resolves every request on them. */
+ pendingInputCards?: Record<string, ChatSdkPendingInputCard>;
streamStepIndex?: number | null;
}
+/** One posted card's requests and the resolutions eve has reported for them so far. */
+export interface ChatSdkPendingInputCard {
+ readonly requests: readonly InputRequest[];
+ readonly resolved: Readonly<Record<string, InputResolution>>;
+}
+
/**
* Thread selector accepted by `chatSdkChannel().receive`. Pass a serialized
* Chat SDK thread when possible; `threadId` plus `adapterName` is supported for
@@ -397,7 +406,52 @@ function defaultEvents<TAdapters extends ChatSdkAdapters>(
},
async "input.requested"(event, channel, _ctx) {
if (!channel.thread || event.requests.length === 0) return;
- await channel.thread.post(renderInputRequests(event.requests, inputActionPrefix));
+ const posted = await channel.thread.post(
+ renderInputRequests(event.requests, inputActionPrefix),
+ );
+ if (!posted.id || channel.state.editSupported === false) return;
+ channel.state.pendingInputCards = {
+ ...channel.state.pendingInputCards,
+ [posted.id]: { requests: event.requests, resolved: {} },
+ };
+ },
+ // Covers every way a request ends: a press, a typed answer, or a withdrawal.
+ async "input.resolved"(event, channel, _ctx) {
+ const thread = channel.thread;
+ if (!thread) return;
+ for (const [messageId, card] of Object.entries(channel.state.pendingInputCards ?? {})) {
+ const resolutions = event.resolutions.filter((resolution) =>
+ card.requests.some((request) => request.requestId === resolution.requestId),
+ );
+ if (resolutions.length === 0) continue;
+ const resolved = {
+ ...card.resolved,
+ ...Object.fromEntries(
+ resolutions.map((resolution) => [resolution.requestId, resolution]),
+ ),
+ };
+ const { [messageId]: _, ...rest } = channel.state.pendingInputCards ?? {};
+ channel.state.pendingInputCards = card.requests.every(
+ (request) => resolved[request.requestId] !== undefined,
+ )
+ ? rest
+ : { ...rest, [messageId]: { requests: card.requests, resolved } };
+ try {
+ await thread.adapter.editMessage(
+ thread.id,
+ messageId,
+ renderInputRequests(card.requests, inputActionPrefix, resolved),
+ );
+ } catch (error) {
+ if (!isNotImplemented(error)) {
+ log.warn("answered input card edit failed", { error, messageId });
+ continue;
+ }
+ channel.state.editSupported = false;
+ channel.state.pendingInputCards = {};
+ return;
+ }
+ }
},
async "message.completed"(event, channel, _ctx) {
if (event.finishReason === "tool-calls") {
diff --git a/packages/eve/src/public/channels/chat-sdk/input-actions.ts b/packages/eve/src/public/channels/chat-sdk/input-actions.ts
index 0423ed9b1..545ccc610 100644
--- a/packages/eve/src/public/channels/chat-sdk/input-actions.ts
+++ b/packages/eve/src/public/channels/chat-sdk/input-actions.ts
@@ -1,3 +1,5 @@
+import { resolvedPromptLabel } from "#channel/resolved-prompt.js";
+import type { InputResolution } from "#protocol/message.js";
import type { InputRequest } from "#shared/input.js";
import type { CardChild } from "#compiled/chat/index.js";
import { Actions, Button, Card, CardText } from "#compiled/chat/index.js";
@@ -8,14 +10,35 @@ const FREEFORM_HINT = "Reply with your answer.";
/**
* Renders pending input requests as a Chat SDK card with one button per option,
- * plus fallback text for adapters without cards (such as Photon iMessage).
+ * plus fallback text for adapters without cards (such as Photon iMessage). A
+ * request in `resolved` shows its outcome in place of its buttons.
*/
-export function renderInputRequests(requests: readonly InputRequest[], inputActionPrefix: string) {
+export function renderInputRequests(
+ requests: readonly InputRequest[],
+ inputActionPrefix: string,
+ resolved: Readonly<Record<string, InputResolution>> = {},
+) {
+ const outcome = (request: InputRequest) => {
+ const resolution = resolved[request.requestId];
+ return resolution === undefined ? undefined : resolvedPromptLabel(resolution, request.options);
+ };
return {
card: Card({
- children: requests.flatMap((request) => renderInputRequest(request, inputActionPrefix)),
+ children: requests.flatMap((request) => {
+ const label = outcome(request);
+ return label === undefined
+ ? renderInputRequest(request, inputActionPrefix)
+ : [CardText(request.prompt), CardText(label)];
+ }),
}),
- fallbackText: requests.map(renderInputRequestText).join("\n\n"),
+ fallbackText: requests
+ .map((request) => {
+ const label = outcome(request);
+ return label === undefined
+ ? renderInputRequestText(request)
+ : `${request.prompt}\n\n${label}`;
+ })
+ .join("\n\n"),
};
}
diff --git a/packages/eve/src/public/channels/discord/defaults.ts b/packages/eve/src/public/channels/discord/defaults.ts
index 4d972d297..19c4d8a4f 100644
--- a/packages/eve/src/public/channels/discord/defaults.ts
+++ b/packages/eve/src/public/channels/discord/defaults.ts
@@ -1,7 +1,11 @@
import type { SessionAuthContext } from "#channel/types.js";
-import { extractErrorId, formatErrorHint } from "#internal/logging.js";
-import { splitDiscordMessageContent } from "#public/channels/discord/api.js";
+import { resolvedPromptLabel } from "#channel/resolved-prompt.js";
+import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
+import {
+ DISCORD_MESSAGE_CONTENT_MAX_LENGTH,
+ splitDiscordMessageContent,
+} from "#public/channels/discord/api.js";
import type { DiscordCommandInteraction } from "#public/channels/discord/inbound.js";
import { renderInputRequestComponents } from "#public/channels/discord/hitl.js";
import type {
@@ -10,6 +14,8 @@ import type {
DiscordContext,
} from "#public/channels/discord/discordChannel.js";
+const log = createLogger("discord.defaults");
+
/**
* Builds the default {@link SessionAuthContext} for a Discord command
* interaction: authenticator `discord-interaction`, guild-scoped
@@ -68,10 +74,45 @@ export const defaultEvents: DiscordChannelEvents = {
async "input.requested"(event, channel, _ctx) {
for (const request of event.requests) {
const content = splitDiscordMessageContent(request.prompt)[0] ?? request.prompt;
- await channel.discord.post({
- components: renderInputRequestComponents(request),
- content,
- });
+ const components = renderInputRequestComponents(request);
+ const posted = await channel.discord.post({ components, content });
+ if (components.length === 0 || !posted.id) continue;
+ channel.state.hitlPrompts = {
+ ...channel.state.hitlPrompts,
+ [request.requestId]: {
+ content,
+ messageId: posted.id,
+ options: (request.options ?? []).map(({ id, label }) => ({ id, label })),
+ },
+ };
+ }
+ },
+
+ // Covers every way a prompt ends: a press, a modal answer, or a withdrawal.
+ // The bot token outlives the interaction token the prompt may have been posted with.
+ async "input.resolved"(event, channel, _ctx) {
+ for (const resolution of event.resolutions) {
+ const prompt = channel.state.hitlPrompts?.[resolution.requestId];
+ if (prompt === undefined) continue;
+ const { [resolution.requestId]: _, ...rest } = channel.state.hitlPrompts ?? {};
+ channel.state.hitlPrompts = rest;
+ const label = resolvedPromptLabel(resolution, prompt.options);
+ const content = `${prompt.content}\n\n${label}`.slice(0, DISCORD_MESSAGE_CONTENT_MAX_LENGTH);
+ try {
+ const response = await channel.discord.request(
+ `/channels/${encodeURIComponent(channel.discord.channelId)}/messages/${encodeURIComponent(prompt.messageId)}`,
+ { components: [], content },
+ { botAuth: true, method: "PATCH" },
+ );
+ if (!response.ok) {
+ log.warn("Discord answered prompt edit failed", {
+ requestId: resolution.requestId,
+ status: response.status,
+ });
+ }
+ } catch (error) {
+ log.warn("Discord answered prompt edit failed", { error, requestId: resolution.requestId });
+ }
}
},
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index c8040559d..746e85dd5 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -50,7 +50,7 @@ import { verifyDiscordInbound } from "#public/channels/discord/verifyInbound.js"
import { readNonEmptyString } from "#shared/guards.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";
-import type { ValidatedInputResponse } from "#shared/input.js";
+import type { InputOption, ValidatedInputResponse } from "#shared/input.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
import { discordAudience, discordInstrumentationMetadata } from "./audience.js";
@@ -87,6 +87,15 @@ export interface DiscordChannelState {
initialResponseSent: boolean;
/** Whether `conversationId` is a real Discord message id. */
hasMessageAnchor: boolean;
+ /** Posted prompts with components, keyed by requestId, until eve resolves them. */
+ hitlPrompts?: Record<string, DiscordHitlPrompt>;
+}
+
+/** What a posted prompt needs so its message can be edited once eve resolves it. */
+export interface DiscordHitlPrompt {
+ readonly content: string;
+ readonly messageId: string;
+ readonly options: readonly Pick<InputOption, "id" | "label">[];
}
/** Discord channel credentials. */
@@ -140,6 +149,7 @@ export interface DiscordChannelEvents {
readonly "message.completed"?: DiscordEventHandler<"message.completed">;
readonly "message.appended"?: DiscordEventHandler<"message.appended">;
readonly "input.requested"?: DiscordEventHandler<"input.requested">;
+ readonly "input.resolved"?: DiscordEventHandler<"input.resolved">;
readonly "turn.failed"?: DiscordEventHandler<"turn.failed">;
readonly "turn.completed"?: DiscordEventHandler<"turn.completed">;
readonly "turn.cancelled"?: DiscordEventHandler<"turn.cancelled">;
diff --git a/packages/eve/src/public/channels/teams/defaults.test.ts b/packages/eve/src/public/channels/teams/defaults.test.ts
index 9052baf16..45469cab5 100644
--- a/packages/eve/src/public/channels/teams/defaults.test.ts
+++ b/packages/eve/src/public/channels/teams/defaults.test.ts
@@ -68,7 +68,7 @@ describe("defaultEvents approval lifecycle", () => {
);
expect(post).toHaveBeenCalledTimes(1);
- expect(channel.state.pendingApprovalCards).toEqual({
+ expect(channel.state.pendingPromptCards).toEqual({
approval_1: { activityId: "act1", prompt: "Approve deployment?" },
});
});
@@ -76,7 +76,7 @@ describe("defaultEvents approval lifecycle", () => {
it("replaces the settled approval card with the responder's identity", async () => {
const { channel, update } = buildChannelStub({
approvalResponderAccounts: { "teams:TENANT:USER": { id: "USER", name: "Ada" } },
- pendingApprovalCards: {
+ pendingPromptCards: {
approval_1: { activityId: "approval-card", prompt: "Approve deployment?" },
},
});
@@ -99,7 +99,7 @@ describe("defaultEvents approval lifecycle", () => {
expect.objectContaining({ attachments: expect.any(Array) }),
);
expect(JSON.stringify(update.mock.calls[0]?.[1])).toContain("Answered: Approved by Ada");
- expect(channel.state.pendingApprovalCards).toEqual({});
+ expect(channel.state.pendingPromptCards).toEqual({});
});
});
diff --git a/packages/eve/src/public/channels/teams/defaults.ts b/packages/eve/src/public/channels/teams/defaults.ts
index 2ef9ec713..d454de85b 100644
--- a/packages/eve/src/public/channels/teams/defaults.ts
+++ b/packages/eve/src/public/channels/teams/defaults.ts
@@ -1,5 +1,6 @@
import type { SessionAuthContext } from "#channel/types.js";
+import { resolvedPromptAnswer } from "#channel/resolved-prompt.js";
import { extractErrorId, formatErrorHint } from "#internal/logging.js";
import type { ConnectionAuthorizationOutcome } from "#protocol/message.js";
import { splitTeamsMessageText, type TeamsMention } from "#public/channels/teams/api.js";
@@ -76,17 +77,20 @@ export const defaultEvents: TeamsChannelEvents = {
replyToActivityId: channel.teams.replyToActivityId,
}),
);
- if (request.kind === "tool-approval" && posted.id) {
- channel.state.pendingApprovalCards = {
- ...channel.state.pendingApprovalCards,
- [request.requestId]: { activityId: posted.id, prompt: request.prompt },
- };
- }
+ if (!posted.id) continue;
+ const card = { activityId: posted.id, prompt: request.prompt };
+ channel.state.pendingPromptCards = {
+ ...channel.state.pendingPromptCards,
+ [request.requestId]:
+ request.kind === "question"
+ ? { ...card, options: (request.options ?? []).map(({ id, label }) => ({ id, label })) }
+ : card,
+ };
}
},
async "approval.settled"(event, channel, _ctx) {
- const cards = channel.state.pendingApprovalCards ?? {};
+ const cards = channel.state.pendingPromptCards ?? {};
const card = cards[event.requestId];
if (card === undefined) return;
const account = channel.state.approvalResponderAccounts?.[event.responderPrincipalId];
@@ -102,7 +106,28 @@ export const defaultEvents: TeamsChannelEvents = {
);
const next = { ...cards };
delete next[event.requestId];
- channel.state.pendingApprovalCards = next;
+ channel.state.pendingPromptCards = next;
+ },
+
+ // `approval.settled` runs first and retires pressed approvals with their
+ // responder. Cards that end any other way (a typed answer, any question, or a
+ // withdrawal) are retired here.
+ async "input.resolved"(event, channel, _ctx) {
+ for (const resolution of event.resolutions) {
+ const cards = channel.state.pendingPromptCards ?? {};
+ const card = cards[resolution.requestId];
+ if (card === undefined) continue;
+ await channel.thread.update(
+ card.activityId,
+ renderAnsweredInputRequestMessage({
+ includeText: false,
+ label: resolvedPromptAnswer(resolution, card.options),
+ prompt: card.prompt,
+ }),
+ );
+ const { [resolution.requestId]: _, ...rest } = cards;
+ channel.state.pendingPromptCards = rest;
+ }
},
async "message.completed"(event, channel, _ctx) {
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
index 21ad2e7e2..9025368f9 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
@@ -351,7 +351,7 @@ describe("teamsChannel", () => {
ctx,
);
- expect(ctx.state.pendingApprovalCards).toEqual({});
+ expect(ctx.state.pendingPromptCards).toEqual({});
const { send } = await firePost(channel, {
...baseActivity({ conversationType: "channel" }),
@@ -385,7 +385,7 @@ describe("teamsChannel", () => {
{ inputResponses: delivery.inputResponses, state: delivery.state },
ctx,
);
- expect(ctx.state.pendingApprovalCards).toEqual({
+ expect(ctx.state.pendingPromptCards).toEqual({
approval_1: { activityId: "approval-card", prompt: "Approve deployment?" },
});
@@ -545,12 +545,12 @@ describe("teamsChannel", () => {
const ctx = buildAdapterContext(teamsAdapter, stubAccessor());
const card = { activityId: "approval-card", prompt: "Approve deployment?" };
const responder = { id: "USER", name: "Ada" };
- ctx.state.pendingApprovalCards = { approval_1: card };
+ ctx.state.pendingPromptCards = { approval_1: card };
ctx.state.approvalResponderAccounts = { "teams:TENANT:USER": responder };
await teamsAdapter.deliver!({ message: "Begin", state: delivery.state }, ctx);
- expect(ctx.state.pendingApprovalCards).toEqual({ approval_1: card });
+ expect(ctx.state.pendingPromptCards).toEqual({ approval_1: card });
expect(ctx.state.approvalResponderAccounts).toEqual({ "teams:TENANT:USER": responder });
});
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.ts
index 2cc3e2058..ba345759a 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts
@@ -62,6 +62,7 @@ import { readNonEmptyString } from "#shared/guards.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { InputOption } from "#shared/input.js";
const log = createLogger("teams.channel");
@@ -89,12 +90,15 @@ interface TeamsChannelContext extends TeamsContext {
/** Event-handler Teams context, including continuation routing. */
export interface TeamsEventContext extends TeamsChannelContext, ChannelContinuationOps {}
-/** JSON-serializable Teams channel state. */
-export interface TeamsPendingApprovalCard {
+/** A posted question or approval card, kept until eve resolves its request. */
+export interface TeamsPendingPromptCard {
readonly activityId: string;
+ /** A question's options, so its card can show the chosen label. */
+ readonly options?: readonly Pick<InputOption, "id" | "label">[];
readonly prompt: string;
}
+/** JSON-serializable Teams channel state. */
export interface TeamsChannelState {
/** Bot account captured from the inbound activity recipient. */
bot: TeamsChannelAccount | null;
@@ -111,7 +115,7 @@ export interface TeamsChannelState {
triggeringUser: TeamsChannelAccount | null;
/** Activity id for the default connection-auth card, when posted. */
pendingAuthActivityId?: string | null;
- pendingApprovalCards?: Record<string, TeamsPendingApprovalCard>;
+ pendingPromptCards?: Record<string, TeamsPendingPromptCard>;
approvalResponderAccounts?: Record<string, TeamsChannelAccount>;
}
@@ -179,6 +183,7 @@ type TeamsSessionFailedHandler = (
export interface TeamsChannelEvents {
readonly "approval.candidate"?: TeamsEventHandler<"approval.candidate">;
readonly "approval.settled"?: TeamsEventHandler<"approval.settled">;
+ readonly "input.resolved"?: TeamsEventHandler<"input.resolved">;
readonly "turn.started"?: TeamsEventHandler<"turn.started">;
readonly "actions.requested"?: TeamsEventHandler<"actions.requested">;
readonly "action.partial"?: TeamsEventHandler<"action.partial">;
@@ -319,11 +324,11 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {
deliver(payload, channel) {
const state = payload.state as Partial<TeamsChannelState> | undefined;
- const cards = state?.pendingApprovalCards;
+ const cards = state?.pendingPromptCards;
if (cards !== undefined) {
- channel.state.pendingApprovalCards = {
+ channel.state.pendingPromptCards = {
...cards,
- ...channel.state.pendingApprovalCards,
+ ...channel.state.pendingPromptCards,
};
}
const responders = state?.approvalResponderAccounts;
@@ -769,7 +774,7 @@ function approvalResponseStatePatch(
}
return {
approvalResponderAccounts: { [auth.principalId]: activity.from },
- pendingApprovalCards: {
+ pendingPromptCards: {
[requestId]: {
activityId,
prompt: readTeamsToolApprovalPrompt(activity) ?? "Tool approval",
@@ -796,7 +801,7 @@ function initialTeamsState(): TeamsChannelState {
conversationId: null,
conversationType: null,
approvalResponderAccounts: {},
- pendingApprovalCards: {},
+ pendingPromptCards: {},
pendingAuthActivityId: null,
replyToActivityId: null,
serviceUrl: null,
diff --git a/packages/eve/src/public/channels/telegram/defaults.ts b/packages/eve/src/public/channels/telegram/defaults.ts
index 3c2d24034..90f16fc3e 100644
--- a/packages/eve/src/public/channels/telegram/defaults.ts
+++ b/packages/eve/src/public/channels/telegram/defaults.ts
@@ -9,7 +9,9 @@ import {
} from "#public/channels/telegram/authorization.js";
import {
registerTelegramFreeformPrompt,
+ registerTelegramHitlPrompt,
renderTelegramInputRequest,
+ takeTelegramResolvedPrompt,
} from "#public/channels/telegram/hitl.js";
import type { TelegramMessage } from "#public/channels/telegram/inbound.js";
import type {
@@ -164,11 +166,36 @@ export const defaultEvents: TelegramChannelEvents = {
reply_markup: rendered.replyMarkup,
text: rendered.text,
});
- if (rendered.freeformRequestId !== undefined && posted.id) {
+ if (!posted.id) continue;
+ if (rendered.freeformRequestId !== undefined) {
registerTelegramFreeformPrompt(channel.state, {
messageId: posted.id,
requestId: rendered.freeformRequestId,
});
+ } else {
+ registerTelegramHitlPrompt(channel.state, request, {
+ messageId: posted.id,
+ text: rendered.text,
+ });
+ }
+ }
+ },
+
+ // Covers every way a prompt ends: a press, a typed answer, or a withdrawal.
+ async "input.resolved"(event, channel, _ctx) {
+ for (const resolution of event.resolutions) {
+ const edit = takeTelegramResolvedPrompt(channel.state, resolution);
+ if (edit === undefined) continue;
+ try {
+ await channel.telegram.editMessageText({
+ ...edit,
+ replyMarkup: { inline_keyboard: [] },
+ });
+ } catch (error) {
+ log.warn("Telegram answered prompt edit failed", {
+ error,
+ requestId: resolution.requestId,
+ });
}
}
},
diff --git a/packages/eve/src/public/channels/telegram/hitl.ts b/packages/eve/src/public/channels/telegram/hitl.ts
index 28a6ca132..a0586919d 100644
--- a/packages/eve/src/public/channels/telegram/hitl.ts
+++ b/packages/eve/src/public/channels/telegram/hitl.ts
@@ -8,7 +8,10 @@
import type { UserContent } from "ai";
+import { resolvedPromptLabel } from "#channel/resolved-prompt.js";
+import type { InputResolution } from "#protocol/message.js";
import {
+ type InputOption,
type InputRequest,
type InputResponse,
parseInputResponse,
@@ -29,6 +32,8 @@ const TELEGRAM_BUTTON_LABEL_MAX_LENGTH = 64;
const TELEGRAM_INPUT_PLACEHOLDER_MAX_LENGTH = 64;
const TELEGRAM_PROMPT_MAX_LENGTH = 4000;
const TELEGRAM_INLINE_ROW_SIZE = 2;
+/** Keeps an edited prompt under Telegram's 4096-character message cap. */
+const TELEGRAM_RESOLVED_LABEL_MAX_LENGTH = 90;
/**
* Durable HITL state. `hitlCallbacks` maps compact callback ids to their stored
@@ -40,6 +45,15 @@ export interface TelegramHitlState {
hitlCallbacks?: Record<string, InputResponse>;
nextHitlCallbackId?: number;
pendingFreeformReplies?: Record<string, string>;
+ /** Posted prompts with inline keyboards, keyed by requestId, until eve resolves them. */
+ hitlPrompts?: Record<string, TelegramHitlPrompt>;
+}
+
+/** What a posted prompt needs so its message can be edited once eve resolves it. */
+export interface TelegramHitlPrompt {
+ readonly messageId: string;
+ readonly options: readonly Pick<InputOption, "id" | "label">[];
+ readonly text: string;
}
/**
@@ -98,6 +112,40 @@ export function registerTelegramFreeformPrompt(
};
}
+/** Records a posted inline-keyboard prompt so {@link takeTelegramResolvedPrompt} can edit it. */
+export function registerTelegramHitlPrompt(
+ state: TelegramHitlState,
+ request: InputRequest,
+ posted: { readonly messageId: string; readonly text: string },
+): void {
+ state.hitlPrompts = {
+ ...state.hitlPrompts,
+ [request.requestId]: {
+ ...posted,
+ options: (request.options ?? []).map(({ id, label }) => ({ id, label })),
+ },
+ };
+}
+
+/**
+ * Forgets a resolved prompt, returning the edit that
+ * replaces its keyboard with the outcome, or `undefined` when eve never posted it.
+ */
+export function takeTelegramResolvedPrompt(
+ state: TelegramHitlState,
+ resolution: InputResolution,
+): { readonly messageId: string; readonly text: string } | undefined {
+ const prompt = state.hitlPrompts?.[resolution.requestId];
+ if (prompt === undefined) return undefined;
+ const { [resolution.requestId]: _, ...rest } = state.hitlPrompts ?? {};
+ state.hitlPrompts = rest;
+ const label = truncate(
+ resolvedPromptLabel(resolution, prompt.options),
+ TELEGRAM_RESOLVED_LABEL_MAX_LENGTH,
+ );
+ return { messageId: prompt.messageId, text: `${prompt.text}\n\n${label}` };
+}
+
/**
* Wraps Telegram callback data as a synthetic `InputResponse` (requestId prefixed
* with `telegram_callback:`, optionId hardcoded to `"selected"`). It is a
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.ts
index e086f4f36..b4f0980e6 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts
@@ -158,6 +158,7 @@ export interface TelegramChannelEvents {
readonly "message.completed"?: TelegramEventHandler<"message.completed">;
readonly "message.appended"?: TelegramEventHandler<"message.appended">;
readonly "input.requested"?: TelegramEventHandler<"input.requested">;
+ readonly "input.resolved"?: TelegramEventHandler<"input.resolved">;
readonly "turn.failed"?: TelegramEventHandler<"turn.failed">;
readonly "turn.completed"?: TelegramEventHandler<"turn.completed">;
readonly "turn.cancelled"?: TelegramEventHandler<"turn.cancelled">;