Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[2/6] fix(slack): resolve typed HITL answers against the typed text (#4150)

Ben Pankowef1a6b9ef6fd
diff --git a/.changeset/slack-typed-hitl-answers.md b/.changeset/slack-typed-hitl-answers.md
new file mode 100644
index 000000000..f840a6926
--- /dev/null
+++ b/.changeset/slack-typed-hitl-answers.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Slack thread replies now answer pending tool approvals and `ctx.ask()` questions by what the person typed, such as `approve` or an option label. Before, eve matched the attributed `<slack_message>` envelope instead, so typed answers never resolved a choice and free-text answers included the envelope.
diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.ts
index bdaa9af4a..34266b9b3 100644
--- a/packages/eve/src/channel/adapter.ts
+++ b/packages/eve/src/channel/adapter.ts
@@ -1,6 +1,7 @@
import type { ContextAccessor } from "#context/key.js";
import type { StepInput } from "#harness/types.js";
import { attachClientContext, readClientContext } from "#internal/client-context.js";
+import { attachInputText, readInputText } from "#internal/input-text.js";
import { createLogger } from "#internal/logging.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { SessionHandle } from "#channel/session.js";
@@ -197,12 +198,15 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
export function defaultDeliverResult(payload: DeliverPayload): StepInput | undefined {
if (payload.message !== undefined) {
return attachClientContext(
- {
- inputResponses: payload.inputResponses,
- message: payload.message,
- context: payload.context,
- outputSchema: payload.outputSchema,
- },
+ attachInputText(
+ {
+ inputResponses: payload.inputResponses,
+ message: payload.message,
+ context: payload.context,
+ outputSchema: payload.outputSchema,
+ },
+ readInputText(payload),
+ ),
readClientContext(payload),
);
}
diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.ts
index f893585ac..2e375f844 100644
--- a/packages/eve/src/channel/channel-operations.ts
+++ b/packages/eve/src/channel/channel-operations.ts
@@ -20,6 +20,7 @@ import {
type StrictInputResponses,
} from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
+import { attachInputText, readInputText } from "#internal/input-text.js";
interface BaseChannelSendOptions {
readonly auth: SessionAuthContext | null;
@@ -95,12 +96,15 @@ export function createChannelOperations<TState = undefined>(input: {
// Deliver hooks read per-delivery state (such as the message author)
// from the payload, as they do for `respond()`.
return await bound.deliver(
- {
- context: options.context,
- message,
- outputSchema: options.outputSchema,
- state: (options as { readonly state?: TState }).state,
- },
+ attachInputText(
+ {
+ context: options.context,
+ message,
+ outputSchema: options.outputSchema,
+ state: (options as { readonly state?: TState }).state,
+ },
+ readInputText(options),
+ ),
options,
);
},
diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.ts
index b312d0d63..b206cdc7b 100644
--- a/packages/eve/src/harness/input-requests.test.ts
+++ b/packages/eve/src/harness/input-requests.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import { SessionKey } from "#context/keys.js";
+import { attachInputText } from "#internal/input-text.js";
import { once } from "#tools/approval/policies.js";
import type { InputRequest } from "#shared/input.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
@@ -248,7 +249,13 @@ describe("resolvePendingInput", () => {
expect(getDeferredStepInput(deferred.session)).toBeUndefined();
});
- it("resolves approval when follow-up text matches an option", () => {
+ it.each([
+ ["a plain message", { message: "approve" }],
+ [
+ "typed text inside a channel envelope",
+ attachInputText({ message: "<slack_message>\n<content>\napprove\n</content>" }, "approve"),
+ ],
+ ])("resolves approval when follow-up text matches an option: %s", (_, stepInput) => {
const session = appendPendingInputBatch({
requests: [
{
@@ -290,10 +297,7 @@ describe("resolvePendingInput", () => {
session: createHarnessSession(),
});
- const result = resolvePendingInput({
- stepInput: { message: "approve" },
- session,
- });
+ const result = resolvePendingInput({ stepInput, session });
expect(result.outcome).toBe("resolved");
expect(result.deferredMessage).toBeUndefined();
diff --git a/packages/eve/src/harness/input-requests.ts b/packages/eve/src/harness/input-requests.ts
index 1838752dc..b41f98b8a 100644
--- a/packages/eve/src/harness/input-requests.ts
+++ b/packages/eve/src/harness/input-requests.ts
@@ -28,6 +28,7 @@ import {
} from "#harness/hitl/session-limit-input-requests.js";
import type { HarnessSession, StepInput } from "#harness/types.js";
import { readClientContext } from "#internal/client-context.js";
+import { readAnswerText } from "#internal/input-text.js";
export { getApprovedTools, clearPendingSessionLimitPrompt };
export type { RejectedActionBatch };
@@ -194,7 +195,8 @@ function resolveTextMessageInput(
pendingBatch: PendingInputBatch,
stepInput: StepInput | undefined,
): ResolvedStepInput | undefined {
- if (typeof stepInput?.message !== "string") return stepInput;
+ const text = readAnswerText(stepInput);
+ if (stepInput === undefined || text === undefined) return stepInput;
const batchRequestIds = new Set(pendingBatch.requests.map((request) => request.requestId));
if (stepInput.inputResponses?.some((response) => batchRequestIds.has(response.requestId))) {
@@ -205,7 +207,7 @@ function resolveTextMessageInput(
const textRequests = pendingBatch.requests.filter(
(request) => !responseAuthRequired.has(request.requestId),
);
- const responses = resolveTextToResponses(stepInput.message, textRequests);
+ const responses = resolveTextToResponses(text, textRequests);
if (responses.length === 0) return stepInput;
return compactStepInput({
diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.ts
index cf7f8de3e..3b30ee400 100644
--- a/packages/eve/src/harness/messages.ts
+++ b/packages/eve/src/harness/messages.ts
@@ -9,6 +9,7 @@ import type {
import type { InputResponse } from "#shared/input.js";
import type { StepInput } from "#harness/types.js";
import { attachClientContext, readClientContext } from "#internal/client-context.js";
+import { attachInputText, readInputText } from "#internal/input-text.js";
/** Reason a framework-authored user-role message was added to model history. */
export type FrameworkMessageKind =
@@ -182,10 +183,20 @@ export function coalesceTurnInputs(a: StepInput, b: StepInput): StepInput {
result.outputSchema = outputSchema;
}
+ // Typed text describes one message, so it survives only when the other input has none.
+ const inputText =
+ normalizeUserContent(a.message) === undefined
+ ? readInputText(b)
+ : normalizeUserContent(b.message) === undefined
+ ? readInputText(a)
+ : undefined;
return attachClientContext(
- frameworkMessageKind === undefined
- ? result
- : markFrameworkStepInput(result, frameworkMessageKind),
+ attachInputText(
+ frameworkMessageKind === undefined
+ ? result
+ : markFrameworkStepInput(result, frameworkMessageKind),
+ inputText,
+ ),
ephemeralContext,
);
}
diff --git a/packages/eve/src/internal/input-text.ts b/packages/eve/src/internal/input-text.ts
new file mode 100644
index 000000000..3c062309e
--- /dev/null
+++ b/packages/eve/src/internal/input-text.ts
@@ -0,0 +1,29 @@
+export const inputTextKey = "__eveInputText";
+
+type InputTextCarrier = {
+ [inputTextKey]?: string;
+};
+
+/**
+ * Attaches the text a person typed, for channels whose model-visible message
+ * wraps it in an envelope. Pending input requests resolve against this text, so
+ * a typed `approve` or option label still answers them.
+ */
+export function attachInputText<T extends object>(target: T, text: string | undefined): T {
+ if (text !== undefined) {
+ (target as T & InputTextCarrier)[inputTextKey] = text;
+ }
+ return target;
+}
+
+export function readInputText(target: object | undefined): string | undefined {
+ return (target as InputTextCarrier | undefined)?.[inputTextKey];
+}
+
+/** The text pending input resolves against: the typed text, else a plain string message. */
+export function readAnswerText(
+ target: (object & { readonly message?: unknown }) | undefined,
+): string | undefined {
+ if (typeof target?.message !== "string") return undefined;
+ return readInputText(target) ?? target.message;
+}
diff --git a/packages/eve/src/public/channels/hitl-conformance.integration.test.ts b/packages/eve/src/public/channels/hitl-conformance.integration.test.ts
index 74596ba6e..38a6a7b8d 100644
--- a/packages/eve/src/public/channels/hitl-conformance.integration.test.ts
+++ b/packages/eve/src/public/channels/hitl-conformance.integration.test.ts
@@ -29,15 +29,7 @@ const channels: readonly {
readonly broken?: Partial<Record<HitlRule, BrokenCell>>;
}[] = [
{ driver: chatSdkDriver },
- {
- driver: slackDriver,
- broken: {
- "a text reply matching an option answers the only pending question": {
- reason: "the answer is the whole <slack_message> envelope",
- symptom: /ask_question returned \{"answer":"<slack_message>/,
- },
- },
- },
+ { driver: slackDriver },
{
driver: telegramDriver,
broken: {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index b9de190a9..e1fa1f55c 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -14,6 +14,7 @@ import type { SessionAuthContext } from "#channel/types.js";
import { isHttpRouteDefinition } from "#channel/routes.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { AuthKey, SessionKey } from "#context/keys.js";
+import { readInputText } from "#internal/input-text.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
import {
mockChannelContext,
@@ -2969,6 +2970,34 @@ describe("slackChannel() inbound mention pipeline", () => {
);
});
+ it.each([
+ ["default HITL config", {}, "approve"],
+ ["a custom input response hook", { onInputResponse: () => null }, undefined],
+ ["an approval channel", { approvalChannel: () => "thread" as const }, undefined],
+ ])("carries the typed text for pending input with %s", async (_, config, expected) => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ onAppMention: () => ({ auth: null }),
+ ...config,
+ });
+ const body = buildEventBody(
+ {
+ channel: "C01",
+ event_ts: "1700000000.000001",
+ text: "<@U_BOT> approve",
+ ts: "1700000000.000001",
+ type: "app_mention",
+ user: "U_REQUESTER",
+ },
+ { authorizations: [{ user_id: "U_BOT" }] },
+ );
+
+ const { send } = await firePost(channel, buildSignedRequest({ body }));
+
+ const [, input] = send.mock.calls[0]!;
+ expect(readInputText(input)).toBe(expected);
+ });
+
it("marks an accepted unmentioned direct message as not mentioned", async () => {
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 01166d1e3..6bc565e81 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -16,6 +16,7 @@ import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ChannelContinuationOps } from "#public/definitions/channel.js";
import { createLogger, logError } from "#internal/logging.js";
+import { attachInputText } from "#internal/input-text.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import type {
InputRequest,
@@ -1115,6 +1116,10 @@ async function handleEventPost(input: {
kind,
message,
received: input.received,
+ // A typed reply would bypass a custom `onInputResponse` and could answer
+ // a request `approvalChannel` sent privately, so either one disables it.
+ resolvesTypedInput:
+ config.onInputResponse === undefined && config.approvalChannel === undefined,
threadContext: config.threadContext,
uploadPolicy: input.uploadPolicy,
});
@@ -1205,6 +1210,7 @@ async function dispatchSlackMessage(input: {
readonly kind: "app_mention" | "channel_message" | "direct_message";
readonly message: SlackMessage;
readonly received: SlackRenderChain["received"];
+ readonly resolvesTypedInput: boolean;
readonly threadContext: LoadThreadContextMessagesOptions | undefined;
readonly uploadPolicy: UploadPolicy;
}): Promise<void> {
@@ -1300,6 +1306,7 @@ async function dispatchSlackMessage(input: {
isPrivateConversation,
isMentioned: isBotMentioned,
message: input.message,
+ resolvesTypedInput: input.resolvesTypedInput,
result,
sessionOperations,
thread,
@@ -1424,6 +1431,7 @@ async function deliverSlackMessage(input: {
readonly isMentioned: boolean;
readonly kind: string;
readonly message: SlackMessage;
+ readonly resolvesTypedInput: boolean;
readonly result: Exclude<SlackInboundResult, null>;
readonly thread: SlackThread;
readonly threadContext: LoadThreadContextMessagesOptions | undefined;
@@ -1463,10 +1471,15 @@ async function deliverSlackMessage(input: {
const title = input.isPrivateConversation
? PRIVATE_SLACK_RUN_TITLE
: (input.result.title ?? message.markdown);
- const sendOptions: SlackSendOptions =
+ const sendOptions: SlackSendOptions = attachInputText(
channelContext.length === 0
? { auth: input.result.auth, title }
- : { auth: input.result.auth, context: channelContext, title };
+ : { auth: input.result.auth, context: channelContext, title },
+ // The envelope stays model-visible; pending input matches what the person typed.
+ input.resolvesTypedInput && fileParts.length === 0
+ ? slackTypedText(message.text, input.botUserId)
+ : undefined,
+ );
await input.sessionOperations.send(turnMessage, sendOptions);
} catch (error) {
@@ -1474,6 +1487,11 @@ async function deliverSlackMessage(input: {
}
}
+function slackTypedText(text: string, botUserId: string | undefined): string {
+ if (botUserId === undefined) return text;
+ return text.replace(new RegExp(`<@${botUserId}(?:\\|[^>]*)?>`, "gu"), "").trim();
+}
+
/**
* Records the Slack user behind a delivery's principal. Slack-authenticated
* callers carry their user id; custom auth relies on the message author or
diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.ts
index 86e37412e..9ecd61775 100644
--- a/packages/eve/src/subagents/hitl-proxy.ts
+++ b/packages/eve/src/subagents/hitl-proxy.ts
@@ -21,6 +21,7 @@ import {
} from "#protocol/message.js";
import type { InputResponse } from "#shared/input.js";
import { resolveTextToResponse } from "#channel/resolve-text.js";
+import { inputTextKey, readAnswerText } from "#internal/input-text.js";
import { SESSION_LIMIT_STOP_OPTION_ID } from "#harness/session-limit-continuation.js";
// ---------------------------------------------------------------------------
@@ -261,7 +262,7 @@ export function routeDeliverPayload(input: {
if (key === "inputResponses" || value === undefined) {
continue;
}
- if (key === "message" && message.consumed) continue;
+ if ((key === "message" || key === inputTextKey) && message.consumed) continue;
remainder[key] = value;
}
@@ -326,9 +327,10 @@ function resolveMessageAgainstQuestions(input: {
if (questions.length === 0) return none;
const [only] = questions;
+ const text = readAnswerText(input.payload);
const answer =
- pending.length === 1 && only !== undefined && typeof input.payload.message === "string"
- ? resolveTextToResponse(input.payload.message, only)
+ pending.length === 1 && only !== undefined && text !== undefined
+ ? resolveTextToResponse(text, only)
: undefined;
if (answer !== undefined) return { consumed: true, responses: [answer] };
return none;