Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[1/3] feat(slack): add private input delivery (#3061)

Ben Pankow4652b5d38967
diff --git a/.changeset/private-slack-approvals.md b/.changeset/private-slack-approvals.md
new file mode 100644
index 000000000..6581828aa
--- /dev/null
+++ b/.changeset/private-slack-approvals.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Slack channels can route each input request, including tool approvals and `ctx.ask()` questions, to the shared thread or the triggering user's direct messages with the `approvalChannel` callback. Direct-message requests include a preview of the Slack message that triggered the turn, while the original thread names the reviewer without exposing the request.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 3215ede64..b088d4b5a 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -438,6 +438,21 @@ export default slackChannel({
HITL renders as Slack buttons and selects. Fixed-choice actions and freeform modal submissions pass through `onInputResponse` before the parked session resumes. The initial **Type your answer** action only opens eve's modal; the hook runs when the user submits an answer.
+Set `approvalChannel` to choose where each input request appears, including tool approvals and questions from `ctx.ask()`. Return `"direct-message"` when the request must be visible only to the Slack user who triggered the turn, or `"thread"` for the normal shared thread.
+
+```ts title="agent/channels/slack.ts"
+import { slackChannel } from "eve/channels/slack";
+
+export default slackChannel({
+ approvalChannel: (request) =>
+ request.kind === "question" || request.action.toolName === "review_answer"
+ ? "direct-message"
+ : "thread",
+});
+```
+
+The callback receives the `InputRequest` and current `SessionContext`, so it can switch on `kind`, `action`, or presentation properties. Omit it to keep every request in the thread, or return `"direct-message"` unconditionally to make every request private. If eve cannot resolve the triggering Slack user for a direct message, it logs the undelivered request and posts no fallback, so private delivery fails closed. The existing `onInputResponse` or tool approval response policy still decides whether the person who clicks may respond.
+
Authorization prompts split public status from private credentials. A sign-in challenge (OAuth URL, device code) is a credential. Anyone who completes it binds their identity to the session's connection. The default `authorization.required` handler posts a public, link-free status in the thread, delivers the actual challenge ephemerally to the triggering user, device code included, and then updates that public status when `authorization.completed` fires. The handler receives a private-delivery context with `postEphemeral`, `postDirectMessage` (needs the `im:write` scope), and `state`. There is, intentionally, no public `post` and no raw API access.
```ts
diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.ts
index 8275c2d2e..a3e489db9 100644
--- a/packages/eve/src/public/channels/slack/defaults.test.ts
+++ b/packages/eve/src/public/channels/slack/defaults.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import { defaultEvents } from "#public/channels/slack/defaults.js";
+import { defaultEvents, defaultInputRequestedHandler } from "#public/channels/slack/defaults.js";
import type { SlackChannelState, SlackEventContext } from "#public/channels/slack/slackChannel.js";
function sessionContext(
@@ -20,14 +20,75 @@ function sessionContext(
const sessionCtx = sessionContext();
+function approvalRequest(requestId = "approval-1") {
+ return {
+ action: {
+ callId: "call-1",
+ input: { answer: "private draft" },
+ kind: "tool-call" as const,
+ toolName: "review_answer",
+ },
+ allowFreeform: false,
+ display: "confirmation" as const,
+ kind: "tool-approval" as const,
+ options: [
+ { id: "approve", label: "Approve", style: "primary" as const },
+ { id: "cancel", label: "Cancel", style: "danger" as const },
+ ],
+ prompt: "Approve review_answer?",
+ requestId,
+ };
+}
+
+function questionRequest(requestId = "question-1") {
+ return {
+ action: {
+ callId: "call-1",
+ input: { prompt: "Share the result?" },
+ kind: "tool-call" as const,
+ toolName: "ask_question",
+ },
+ allowFreeform: false,
+ display: "confirmation" as const,
+ kind: "question" as const,
+ options: [
+ { id: "yes", label: "Yes", style: "primary" as const },
+ { id: "no", label: "No", style: "danger" as const },
+ ],
+ prompt: "Share the result?",
+ requestId,
+ };
+}
+
function buildChannelStub(state: Partial<SlackChannelState> = {}) {
- const postEphemeral = vi.fn().mockResolvedValue({ id: "eph1" });
- const post = vi.fn().mockResolvedValue({ id: "ts1" });
+ const postEphemeral = vi.fn().mockResolvedValue({ id: "eph1", raw: { ok: true } });
+ const postDirectMessage = vi
+ .fn()
+ .mockResolvedValue({ id: "dm1", raw: { channel: "D123", ok: true } });
+ const post = vi.fn().mockResolvedValue({ id: "ts1", raw: { ok: true } });
const startTyping = vi.fn().mockResolvedValue(undefined);
- const request = vi.fn().mockResolvedValue({ ok: true });
+ let postedMessages = 0;
+ const request = vi.fn(async (operation: string, _body: unknown) => {
+ if (operation === "conversations.open") return { channel: { id: "D123" }, ok: true };
+ if (operation === "chat.getPermalink") {
+ return {
+ ok: true,
+ permalink: "https://example.slack.com/archives/C123/p111333?thread_ts=111.222&cid=C123",
+ };
+ }
+ if (operation === "chat.postMessage") {
+ postedMessages += 1;
+ return { ok: true, ts: `dm${postedMessages}` };
+ }
+ return { ok: true };
+ });
const channel = {
- thread: { postEphemeral, post, startTyping } as Partial<SlackEventContext["thread"]>,
- slack: { channelId: "C123", request } as Partial<SlackEventContext["slack"]>,
+ thread: { postDirectMessage, postEphemeral, post, startTyping } as Partial<
+ SlackEventContext["thread"]
+ >,
+ slack: { channelId: "C123", request, threadTs: "111.222" } as Partial<
+ SlackEventContext["slack"]
+ >,
state: {
channelId: "C123",
threadTs: "111.222",
@@ -35,7 +96,7 @@ function buildChannelStub(state: Partial<SlackChannelState> = {}) {
...state,
},
} as SlackEventContext;
- return { channel, post, postEphemeral, request, startTyping };
+ return { channel, post, postDirectMessage, postEphemeral, request, startTyping };
}
function authRequiredEvent(
@@ -51,6 +112,176 @@ function authRequiredEvent(
};
}
+describe("defaultInputRequestedHandler private input requests", () => {
+ it("uses the authored destination for a tool approval", async () => {
+ const { channel, post, postDirectMessage } = buildChannelStub();
+ const approvalChannel = vi.fn(() => "thread" as const);
+
+ await defaultInputRequestedHandler(approvalChannel)(
+ { requests: [approvalRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ channel,
+ sessionCtx,
+ );
+
+ expect(approvalChannel).toHaveBeenCalledWith(
+ expect.objectContaining({ requestId: "approval-1" }),
+ sessionCtx,
+ );
+ expect(post).toHaveBeenCalled();
+ expect(postDirectMessage).not.toHaveBeenCalled();
+ });
+
+ it("routes a ctx.ask question through the same destination resolver", async () => {
+ const { channel, post, request } = buildChannelStub({ triggeringUserId: "U_REVIEWER" });
+ const approvalChannel = vi.fn(() => "direct-message" as const);
+
+ await defaultInputRequestedHandler(approvalChannel)(
+ { requests: [questionRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ channel,
+ sessionCtx,
+ );
+
+ expect(approvalChannel).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: "question", requestId: "question-1" }),
+ sessionCtx,
+ );
+ expect(post).toHaveBeenCalledWith("Waiting on a response from <@U_REVIEWER>…");
+ expect(JSON.stringify(request.mock.calls)).toContain("eve_input:route:C123:111.222:question-1");
+ expect(channel.state.pendingApprovalCards).toEqual({});
+ });
+
+ it("fails closed when no direct-message reviewer can be resolved", async () => {
+ const { channel, post, postDirectMessage, postEphemeral } = buildChannelStub();
+
+ await defaultInputRequestedHandler(() => "direct-message")(
+ { requests: [approvalRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ channel,
+ sessionCtx,
+ );
+
+ expect(post).not.toHaveBeenCalled();
+ expect(postDirectMessage).not.toHaveBeenCalled();
+ expect(postEphemeral).not.toHaveBeenCalled();
+ });
+
+ it("rolls back partial DM delivery without announcing an unusable approval", async () => {
+ const { channel, post, request } = buildChannelStub({
+ triggeringMessageTs: "111.333",
+ triggeringUserId: "U_REVIEWER",
+ });
+ let postedMessages = 0;
+ request.mockImplementation(async (operation: string) => {
+ if (operation === "conversations.open") return { channel: { id: "D123" }, ok: true };
+ if (operation === "chat.getPermalink") {
+ return { ok: true, permalink: "https://example.slack.com/archives/C123/p111333" };
+ }
+ if (operation === "chat.postMessage") {
+ postedMessages += 1;
+ return postedMessages < 3
+ ? { ok: true, ts: `dm${postedMessages}` }
+ : { error: "message_failed", ok: false };
+ }
+ return { ok: true };
+ });
+
+ await expect(
+ defaultInputRequestedHandler(() => "direct-message")(
+ { requests: [approvalRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ channel,
+ sessionCtx,
+ ),
+ ).rejects.toThrow("Slack chat.postMessage failed: message_failed");
+
+ expect(post).not.toHaveBeenCalled();
+ expect(request).toHaveBeenCalledWith("chat.delete", { channel: "D123", ts: "dm1" });
+ expect(request).toHaveBeenCalledWith("chat.delete", { channel: "D123", ts: "dm2" });
+ expect(channel.state.pendingApprovalCards).toBeUndefined();
+ });
+
+ it("keeps the actionable DM committed when its thread announcement fails", async () => {
+ const { channel, post, request } = buildChannelStub({
+ triggeringMessageTs: "111.333",
+ triggeringUserId: "U_REVIEWER",
+ });
+ post.mockRejectedValueOnce(new Error("thread unavailable"));
+
+ await expect(
+ defaultInputRequestedHandler(() => "direct-message")(
+ { requests: [approvalRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ channel,
+ sessionCtx,
+ ),
+ ).resolves.toBeUndefined();
+
+ expect(
+ request.mock.calls.filter(([operation]) => operation === "chat.postMessage"),
+ ).toHaveLength(3);
+ expect(channel.state.pendingApprovalCards?.["approval-1"]).toMatchObject({
+ messageChannelId: "D123",
+ messageTs: "dm3",
+ });
+ });
+
+ it("previews the triggering message and updates the routed DM card after settlement", async () => {
+ const { channel, post, postDirectMessage, request } = buildChannelStub({
+ triggeringMessageTs: "111.333",
+ triggeringUserId: "U_REVIEWER",
+ });
+
+ await defaultInputRequestedHandler(() => "direct-message")(
+ { requests: [approvalRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ channel,
+ sessionCtx,
+ );
+
+ expect(post).toHaveBeenCalledWith("Waiting on approval from <@U_REVIEWER>…");
+ expect(postDirectMessage).not.toHaveBeenCalled();
+ expect(
+ request.mock.calls.filter(([operation]) => operation === "conversations.open"),
+ ).toHaveLength(1);
+ const directMessages = request.mock.calls.filter(
+ ([operation]) => operation === "chat.postMessage",
+ );
+ expect(directMessages).toHaveLength(3);
+ expect(directMessages[0]?.[1]).toMatchObject({
+ channel: "D123",
+ markdown_text: "https://example.slack.com/archives/C123/p111333?thread_ts=111.222&cid=C123",
+ unfurl_links: true,
+ });
+ expect(JSON.stringify(directMessages[1]?.[1])).toContain("private draft");
+ expect(JSON.stringify(directMessages[2]?.[1])).toContain(
+ "eve_input:route:C123:111.222:tool-approval:approval-1",
+ );
+ expect(request).toHaveBeenCalledWith("chat.getPermalink", {
+ channel: "C123",
+ message_ts: "111.333",
+ });
+ expect(channel.state.pendingApprovalCards?.["approval-1"]?.messageChannelId).toBe("D123");
+
+ await defaultEvents["approval.settled"]!(
+ {
+ outcome: "approved",
+ requestId: "approval-1",
+ responderPrincipalId: "slack:T1:U_REVIEWER",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ sessionCtx,
+ );
+
+ expect(request).toHaveBeenCalledWith(
+ "chat.update",
+ expect.objectContaining({ channel: "D123", text: "Answered: Approve", ts: "dm3" }),
+ );
+ const update = request.mock.calls.find(([method]) => method === "chat.update")?.[1] as {
+ blocks?: unknown[];
+ };
+ expect(JSON.stringify(update.blocks)).not.toContain("eve_input:route:");
+ });
+});
+
describe("defaultEvents approval lifecycle", () => {
it("sends candidate progress privately", async () => {
const { channel, postEphemeral } = buildChannelStub({
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index 34ddb77b0..697ac787c 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -1,6 +1,6 @@
import type { SessionAuthContext } from "#channel/types.js";
-import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
+import { createLogger, extractErrorId, formatErrorHint, logError } from "#internal/logging.js";
import { describeActionRequests } from "#public/channels/slack/action-status.js";
import { buildSlackAuthContext, slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";
import {
@@ -12,10 +12,12 @@ import {
} from "#public/channels/slack/connections.js";
import {
buildAnsweredBlocks,
+ decodeHitlActionId,
renderInputRequestPostParts,
type SlackInputRequestPostPart,
} from "#public/channels/slack/hitl.js";
import type { SlackMessage } from "#public/channels/slack/inbound.js";
+import { deliverPrivateInputRequest } from "#public/channels/slack/private-approval-delivery.js";
import {
SLACK_MARKDOWN_TEXT_MAX_LENGTH,
SLACK_MAX_BLOCKS_PER_MESSAGE,
@@ -23,6 +25,7 @@ import {
truncateTypingStatus,
} from "#public/channels/slack/limits.js";
import type {
+ SlackApprovalChannelResolver,
SlackChannelEvents,
SlackChannelInternalEvents,
SlackChannelState,
@@ -120,8 +123,6 @@ function formatSemanticErrorReply(input: {
function blockContainsRequestAction(block: unknown, requestId: string): boolean {
if (typeof block !== "object" || block === null) return false;
const candidate = block as { actions?: unknown; elements?: unknown };
- const requestActionPrefix = `eve_input:${requestId}`;
- const approvalActionPrefix = `eve_input:tool-approval:${requestId}`;
return [candidate.actions, candidate.elements].some(
(entries) =>
Array.isArray(entries) &&
@@ -129,8 +130,7 @@ function blockContainsRequestAction(block: unknown, requestId: string): boolean
if (typeof entry !== "object" || entry === null) return false;
const actionId = (entry as { action_id?: unknown }).action_id;
return (
- typeof actionId === "string" &&
- (actionId.startsWith(requestActionPrefix) || actionId.startsWith(approvalActionPrefix))
+ typeof actionId === "string" && decodeHitlActionId(actionId)?.requestId === requestId
);
}),
);
@@ -208,25 +208,76 @@ function firstNonEmptyLine(text: string): string | undefined {
* Slack's 50-block message cap. Override by declaring
* `events["input.requested"]`.
*/
-export function defaultInputRequestedHandler(): NonNullable<SlackChannelEvents["input.requested"]> {
- return async (data, channel, _ctx) => {
- for (const post of buildInputRequestPosts(data.requests)) {
- const message = await channel.thread.post({ blocks: post.blocks, text: post.text });
- if (!message.id) continue;
- const cards = { ...channel.state.pendingApprovalCards };
- for (const request of post.requests) {
- if (request.kind === "tool-approval") {
- cards[request.requestId] = {
- messageBlocks: post.blocks,
- messageTs: message.id,
- };
- }
+export function defaultInputRequestedHandler(
+ approvalChannel?: SlackApprovalChannelResolver,
+): NonNullable<SlackChannelEvents["input.requested"]> {
+ return async (data, channel, ctx) => {
+ const directMessageRequests: InputRequest[] = [];
+ const threadRequests: InputRequest[] = [];
+ for (const request of data.requests) {
+ const destination =
+ approvalChannel === undefined ? "thread" : await approvalChannel(request, ctx);
+ (destination === "direct-message" ? directMessageRequests : threadRequests).push(request);
+ }
+
+ await postPublicInputRequests(threadRequests, channel);
+ for (const request of directMessageRequests) {
+ const reviewer =
+ slackUserIdFromAuthContext(ctx.session.auth.current) ?? channel.state.triggeringUserId;
+ if (!reviewer) {
+ log.warn("direct-message input request not delivered because no reviewer was resolved", {
+ requestId: request.requestId,
+ sessionId: ctx.session.id,
+ });
+ continue;
+ }
+ const card = await deliverPrivateInputRequest({
+ previewMessageTs: channel.state.triggeringMessageTs ?? channel.slack.threadTs,
+ request,
+ reviewer,
+ slack: channel.slack,
+ });
+ recordApprovalCards(channel.state, [request], card);
+ try {
+ await channel.thread.post(
+ `Waiting on ${request.kind === "tool-approval" ? "approval" : "a response"} from <@${reviewer}>…`,
+ );
+ } catch (error) {
+ logError(log, "failed to announce private input request", error, {
+ requestId: request.requestId,
+ sessionId: ctx.session.id,
+ });
}
- channel.state.pendingApprovalCards = cards;
}
};
}
+async function postPublicInputRequests(
+ requests: readonly InputRequest[],
+ channel: Parameters<NonNullable<SlackChannelEvents["input.requested"]>>[1],
+): Promise<void> {
+ for (const post of buildInputRequestPosts(requests)) {
+ const message = await channel.thread.post({ blocks: post.blocks, text: post.text });
+ recordApprovalCards(channel.state, post.requests, {
+ messageBlocks: post.blocks,
+ messageTs: message.id,
+ });
+ }
+}
+
+function recordApprovalCards(
+ state: SlackChannelState,
+ requests: readonly InputRequest[],
+ card: NonNullable<SlackChannelState["pendingApprovalCards"]>[string],
+): void {
+ if (!card.messageTs) return;
+ const cards = { ...state.pendingApprovalCards };
+ for (const request of requests) {
+ if (request.kind === "tool-approval") cards[request.requestId] = card;
+ }
+ state.pendingApprovalCards = cards;
+}
+
/**
* Groups HITL requests into `chat.postMessage` payloads that stay under
* Slack's block-count cap. Tool input details are posted before interactive
@@ -328,7 +379,9 @@ export const defaultEvents: SlackChannelInternalEvents = {
async "approval.settled"(event, channel, _ctx) {
const cards = channel.state.pendingApprovalCards ?? {};
const card = cards[event.requestId];
- if (card === undefined || channel.state.channelId === null) return;
+ if (card === undefined) return;
+ const messageChannelId = card.messageChannelId ?? channel.state.channelId;
+ if (messageChannelId === null) return;
const answerLabel = event.outcome === "approved" ? "Approve" : "Cancel";
const userId = channel.state.approvalResponderUsers?.[event.responderPrincipalId];
const blocks = card.messageBlocks.flatMap((block) => {
@@ -347,7 +400,7 @@ export const defaultEvents: SlackChannelInternalEvents = {
});
await channel.slack.request("chat.update", {
blocks,
- channel: channel.state.channelId,
+ channel: messageChannelId,
text: `Answered: ${answerLabel}`,
ts: card.messageTs,
});
diff --git a/packages/eve/src/public/channels/slack/hitl.test.ts b/packages/eve/src/public/channels/slack/hitl.test.ts
index 919c83431..0ed66d408 100644
--- a/packages/eve/src/public/channels/slack/hitl.test.ts
+++ b/packages/eve/src/public/channels/slack/hitl.test.ts
@@ -4,6 +4,7 @@ import type { InputRequest } from "#shared/input.js";
import {
buildAnsweredBlocks,
buildFreeformModalView,
+ decodeHitlActionId,
deriveHitlResponse,
formatInputRequestFallbackText,
freeformRequestIdFromActionId,
@@ -31,6 +32,35 @@ function makeRequest(overrides: Partial<InputRequest>): InputRequest {
};
}
+describe("private HITL routes", () => {
+ it("renders and decodes one typed return route", () => {
+ const blocks = renderInputRequestBlocks(
+ makeRequest({
+ kind: "tool-approval",
+ options: [
+ { id: "approve", label: "Approve" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ requestId: "approval_abc123",
+ }),
+ { channelId: "C123", threadTs: "111.222" },
+ );
+ const actionId = (blocks[0] as { actions: Array<{ action_id: string }> }).actions[0]!.action_id;
+
+ expect(decodeHitlActionId(actionId)).toEqual({
+ button: true,
+ kind: "tool-approval",
+ requestId: "approval_abc123",
+ route: { channelId: "C123", threadTs: "111.222" },
+ });
+ expect(deriveHitlResponse({ actionId, value: "approve" })).toMatchObject({
+ kind: "tool-approval",
+ response: { optionId: "approve", requestId: "approval_abc123" },
+ route: { channelId: "C123", threadTs: "111.222" },
+ });
+ });
+});
+
describe("deriveHitlResponse", () => {
it("keeps Slack classification outside the durable input response type", () => {
const derived: NonNullable<ReturnType<typeof deriveHitlResponse>> = {
@@ -373,6 +403,18 @@ describe("renderInputRequestBlocks", () => {
expect(freeformRequestIdFromActionId(HITL_FREEFORM_ACTION_PREFIX)).toBeUndefined();
});
+ it("preserves the return route on a freeform question", () => {
+ const blocks = renderInputRequestBlocks(
+ makeRequest({ requestId: "question_freeform", options: undefined }),
+ { channelId: "C777", threadTs: "7.7" },
+ );
+ const actionId = (blocks[1] as { elements: Array<{ action_id: string }> }).elements[0]!
+ .action_id;
+
+ expect(actionId).toBe("eve_input_freeform:route:C777:7.7:question_freeform");
+ expect(freeformRequestIdFromActionId(actionId)).toBe("question_freeform");
+ });
+
it("truncates section-block prompts past the Slack 3000-char cap", () => {
const longPrompt = "x".repeat(SLACK_SECTION_TEXT_MAX_LENGTH + 500);
const blocks = renderInputRequestBlocks(makeRequest({ prompt: longPrompt }));
diff --git a/packages/eve/src/public/channels/slack/hitl.ts b/packages/eve/src/public/channels/slack/hitl.ts
index 3c377942f..db31a35b0 100644
--- a/packages/eve/src/public/channels/slack/hitl.ts
+++ b/packages/eve/src/public/channels/slack/hitl.ts
@@ -58,6 +58,13 @@ export const HITL_FREEFORM_MODAL_BLOCK_ID = "eve_freeform_block";
*/
export const HITL_FREEFORM_MODAL_ACTION_ID = "eve_freeform_text";
+const HITL_ROUTE_PREFIX = `${HITL_ACTION_PREFIX}route:`;
+
+export interface SlackHitlRoute {
+ readonly channelId: string;
+ readonly threadTs: string;
+}
+
/**
* Maximum radio-button option count before the renderer falls back to
* a `static_select` dropdown. Matches Slack's UX guidance (radio
@@ -92,8 +99,16 @@ interface SlackHitlAction {
* presentation metadata cannot cross the durable session-inbox boundary.
*/
interface DerivedHitlResponse {
- readonly kind?: "tool-approval";
- readonly response: ValidatedInputResponse;
+ kind?: "tool-approval";
+ response: ValidatedInputResponse;
+ route?: SlackHitlRoute;
+}
+
+interface DecodedHitlActionId {
+ button: boolean;
+ kind?: "tool-approval";
+ requestId: string;
+ route?: SlackHitlRoute;
}
/**
@@ -104,34 +119,16 @@ interface DerivedHitlResponse {
export function deriveHitlResponse(action: SlackHitlAction): DerivedHitlResponse | null {
if (!action.actionId.startsWith(HITL_ACTION_PREFIX)) return null;
- const encodedRequest = action.actionId.slice(HITL_ACTION_PREFIX.length);
-
- if (action.selectedOptionValue !== undefined) {
- const { kind, requestId } = splitEncodedRequest(encodedRequest);
- if (!requestId) return null;
- return kind === "tool-approval"
- ? {
- kind,
- response: parseInputResponse({ optionId: action.selectedOptionValue, requestId }),
- }
- : {
- response: parseInputResponse({ optionId: action.selectedOptionValue, requestId }),
- };
- }
-
- if (action.value !== undefined) {
- const match = BUTTON_ACTION_ID_RE.exec(encodedRequest);
- const requestId = match?.groups?.requestId;
- if (!requestId) return null;
- return match.groups?.kind === "tool-approval"
- ? {
- kind: "tool-approval",
- response: parseInputResponse({ optionId: action.value, requestId }),
- }
- : { response: parseInputResponse({ optionId: action.value, requestId }) };
- }
-
- return null;
+ const decoded = decodeHitlActionId(action.actionId);
+ if (decoded === null) return null;
+ const optionId = action.selectedOptionValue ?? action.value;
+ if (optionId === undefined || (action.value !== undefined && !decoded.button)) return null;
+ const derived: DerivedHitlResponse = {
+ response: parseInputResponse({ optionId, requestId: decoded.requestId }),
+ };
+ if (decoded.kind !== undefined) derived.kind = decoded.kind;
+ if (decoded.route !== undefined) derived.route = decoded.route;
+ return derived;
}
function splitEncodedRequest(value: string): {
@@ -153,6 +150,39 @@ export function isHitlAction(actionId: string): boolean {
return actionId.startsWith(HITL_ACTION_PREFIX);
}
+/** Decodes the framework-owned identity and optional return route from one action id. */
+export function decodeHitlActionId(actionId: string): DecodedHitlActionId | null {
+ if (!actionId.startsWith(HITL_ACTION_PREFIX)) return null;
+ let encoded = actionId.slice(HITL_ACTION_PREFIX.length);
+ let route: SlackHitlRoute | undefined;
+ if (encoded.startsWith("route:")) {
+ encoded = encoded.slice("route:".length);
+ const first = encoded.indexOf(":");
+ const second = encoded.indexOf(":", first + 1);
+ if (first <= 0 || second <= first + 1) return null;
+ route = { channelId: encoded.slice(0, first), threadTs: encoded.slice(first + 1, second) };
+ encoded = encoded.slice(second + 1);
+ }
+ const button = BUTTON_ACTION_ID_RE.exec(encoded);
+ const request = splitEncodedRequest(button?.groups?.requestId ?? encoded);
+ if (!request.requestId) return null;
+ const kind = button?.groups?.kind === "tool-approval" ? "tool-approval" : request.kind;
+ const decoded: DecodedHitlActionId = {
+ button: button !== null,
+ requestId: request.requestId,
+ };
+ if (kind !== undefined) decoded.kind = kind;
+ if (route !== undefined) decoded.route = route;
+ return decoded;
+}
+
+function encodeHitlActionId(request: InputRequest, route?: SlackHitlRoute): string {
+ const requestIdentity = `${request.kind === "tool-approval" ? "tool-approval:" : ""}${request.requestId}`;
+ return route === undefined
+ ? `${HITL_ACTION_PREFIX}${requestIdentity}`
+ : `${HITL_ROUTE_PREFIX}${route.channelId}:${route.threadTs}:${requestIdentity}`;
+}
+
/**
* Renders one `InputRequest` as Block Kit blocks:
*
@@ -171,15 +201,13 @@ export function isHitlAction(actionId: string): boolean {
*
* Always emits at least the prompt section.
*/
-export function renderInputRequestBlocks(request: InputRequest): unknown[] {
+export function renderInputRequestBlocks(request: InputRequest, route?: SlackHitlRoute): unknown[] {
const prompt = {
text: { text: truncateSectionText(request.prompt), type: "mrkdwn" },
type: "section",
};
const details = renderInputRequestDetailBlocks(request);
- const actionId = `${HITL_ACTION_PREFIX}${
- request.kind === "tool-approval" ? "tool-approval:" : ""
- }${request.requestId}`;
+ const actionId = encodeHitlActionId(request, route);
const options = request.options;
const acceptsFreeform = request.allowFreeform === true || !options || options.length === 0;
@@ -204,6 +232,7 @@ export function renderInputRequestBlocks(request: InputRequest): unknown[] {
}
if (acceptsFreeform) {
+ const freeformActionId = actionId.replace(HITL_ACTION_PREFIX, HITL_FREEFORM_ACTION_PREFIX);
return [
prompt,
...details,
@@ -212,7 +241,7 @@ export function renderInputRequestBlocks(request: InputRequest): unknown[] {
elements: [
{
type: "button",
- action_id: `${HITL_FREEFORM_ACTION_PREFIX}${request.requestId}`,
+ action_id: freeformActionId,
text: { type: "plain_text", text: "Type your answer" },
style: "primary",
value: request.requestId,
@@ -235,11 +264,14 @@ export interface SlackInputRequestPostPart {
* originating message in `block_actions`, so putting large tool input beside
* the buttons makes the callback body grow with model-authored input.
*/
-export function renderInputRequestPostParts(request: InputRequest): {
+export function renderInputRequestPostParts(
+ request: InputRequest,
+ route?: SlackHitlRoute,
+): {
readonly controls: SlackInputRequestPostPart;
readonly details?: SlackInputRequestPostPart;
} {
- const blocks = renderInputRequestBlocks(request);
+ const blocks = renderInputRequestBlocks(request, route);
const firstBlock = blocks[0];
if (!isApprovalRequest(request) || !isBlockType(firstBlock, "card") || blocks.length === 1) {
return {
@@ -278,6 +310,8 @@ export interface HitlFreeformModalMetadata {
/** Workspace whose app installation supplies credentials for modal follow-up API calls. */
readonly installationTeamId?: string;
readonly threadTs: string;
+ /** Slack conversation containing the interactive card. */
+ readonly messageChannelId?: string;
readonly messageTs: string;
readonly requestId: string;
}
@@ -333,9 +367,14 @@ export function isFreeformAction(actionId: string): boolean {
* Extracts the requestId from a freeform-answer button's `action_id`.
*/
export function freeformRequestIdFromActionId(actionId: string): string | undefined {
- if (!isFreeformAction(actionId)) return undefined;
- const slice = actionId.slice(HITL_FREEFORM_ACTION_PREFIX.length);
- return slice.length > 0 ? slice : undefined;
+ return decodeFreeformHitlActionId(actionId)?.requestId;
+}
+
+export function decodeFreeformHitlActionId(actionId: string): DecodedHitlActionId | null {
+ if (!isFreeformAction(actionId)) return null;
+ return decodeHitlActionId(
+ `${HITL_ACTION_PREFIX}${actionId.slice(HITL_FREEFORM_ACTION_PREFIX.length)}`,
+ );
}
function buildCardButton(
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 1eb15a36d..e54741638 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -20,8 +20,8 @@ import {
import { buildSlackAuthContext } from "#public/channels/slack/auth.js";
import {
buildFreeformModalView,
+ decodeFreeformHitlActionId,
deriveHitlResponse,
- freeformRequestIdFromActionId,
HITL_FREEFORM_MODAL_ACTION_ID,
HITL_FREEFORM_MODAL_BLOCK_ID,
HITL_FREEFORM_MODAL_CALLBACK_ID,
@@ -299,7 +299,6 @@ export async function handleInteractionPost(
return ack;
}
- const continuationToken = slackContinuationToken(interaction.channelId, interaction.threadTs);
const hitlActions = interaction.actions.flatMap((action) => {
const derived = deriveHitlResponse(action);
return derived === null ? [] : [{ action, derived }];
@@ -307,11 +306,13 @@ export async function handleInteractionPost(
if (hitlActions.length > 0) {
const user = hitlActions[0]!.action.user;
+ const route = hitlActions[0]!.derived.route;
ctx.waitUntil(
dispatchBlockInputResponses({
ctx,
deps,
interaction,
+ route,
submission: {
type: "block_actions",
actions: hitlActions.map(({ action }) => action),
@@ -337,7 +338,7 @@ export async function handleInteractionPost(
});
const slackCtx: SlackInteractionContext = {
...bindSlackSessionOperations({
- address: continuationToken,
+ address: slackContinuationToken(interaction.channelId, interaction.threadTs),
defaultAuth: buildSlackAuthContext({
channelId: interaction.channelId,
teamId: interaction.teamId,
@@ -482,21 +483,24 @@ async function dispatchBlockInputResponses(input: {
};
readonly deps: InteractionHandlerDeps;
readonly interaction: ParsedBlockActionsPayload;
+ readonly route?: { readonly channelId: string; readonly threadTs: string };
readonly submission: Extract<SlackInputResponseSubmission, { type: "block_actions" }>;
}): Promise<void> {
+ const channelId = input.route?.channelId ?? input.interaction.channelId;
+ const threadTs = input.route?.threadTs ?? input.interaction.threadTs;
const result = await authorizeInputResponse({
- channelId: input.interaction.channelId,
+ channelId,
deps: input.deps,
installationTeamId: input.interaction.installationTeamId,
submission: input.submission,
teamId: input.interaction.teamId,
- threadTs: input.interaction.threadTs,
+ threadTs,
});
if (result === null) return;
try {
await input.ctx
- .from(slackContinuationToken(input.interaction.channelId, input.interaction.threadTs))
+ .from(slackContinuationToken(channelId, threadTs))
.respond(input.submission.inputResponses, {
auth: result.auth,
state: approvalResponderStatePatch(input.submission, result.auth),
@@ -531,8 +535,12 @@ async function openFreeformModal(input: {
return;
}
- const requestId =
- freeformRequestIdFromActionId(input.freeformAction.actionId) ?? input.freeformAction.value;
+ const decoded = decodeFreeformHitlActionId(input.freeformAction.actionId);
+ if (decoded === null) {
+ log.warn("freeform button click carries invalid metadata");
+ return;
+ }
+ const requestId = decoded.requestId;
if (!requestId) {
log.warn("freeform button click missing requestId");
return;
@@ -544,14 +552,14 @@ async function openFreeformModal(input: {
return;
}
+ const channelId = decoded?.route?.channelId ?? input.interaction.channelId;
+ const threadTs = decoded?.route?.threadTs ?? input.interaction.threadTs;
const metadata: HitlFreeformModalMetadata = {
- continuationToken: slackContinuationToken(
- input.interaction.channelId,
- input.interaction.threadTs,
- ),
- channelId: input.interaction.channelId,
+ continuationToken: slackContinuationToken(channelId, threadTs),
+ channelId,
installationTeamId: input.interaction.installationTeamId,
- threadTs: input.interaction.threadTs,
+ messageChannelId: input.interaction.channelId,
+ threadTs,
messageTs,
requestId,
};
@@ -676,7 +684,7 @@ async function dispatchViewInputResponse(input: {
try {
await updateAnsweredFreeformCard({
- channelId: input.metadata.channelId,
+ channelId: input.metadata.messageChannelId ?? input.metadata.channelId,
messageTs: input.metadata.messageTs,
answerLabel: input.text,
userId: input.submission.user.id,
diff --git a/packages/eve/src/public/channels/slack/private-approval-delivery.ts b/packages/eve/src/public/channels/slack/private-approval-delivery.ts
new file mode 100644
index 000000000..bf89a1700
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/private-approval-delivery.ts
@@ -0,0 +1,102 @@
+import { createLogger, logError } from "#internal/logging.js";
+import type { SlackHandle } from "#public/channels/slack/api.js";
+import { renderInputRequestPostParts, type SlackHitlRoute } from "#public/channels/slack/hitl.js";
+import type { SlackPendingApprovalCard } from "#public/channels/slack/slackChannel.js";
+import type { InputRequest } from "#shared/input.js";
+
+const log = createLogger("slack.private-approval-delivery");
+type PrivateApprovalSlack = Pick<SlackHandle, "channelId" | "request" | "threadTs">;
+
+export async function deliverPrivateInputRequest(input: {
+ readonly previewMessageTs: string;
+ readonly request: InputRequest;
+ readonly reviewer: string;
+ readonly slack: PrivateApprovalSlack;
+}): Promise<SlackPendingApprovalCard> {
+ const open = await input.slack.request("conversations.open", { users: input.reviewer });
+ const messageChannelId =
+ open.ok === true ? (open.channel as { id?: unknown } | undefined)?.id : undefined;
+ if (typeof messageChannelId !== "string" || messageChannelId.length === 0) {
+ throw new Error(`Slack conversations.open failed: ${open.error ?? "unknown_error"}`);
+ }
+
+ const route: SlackHitlRoute = {
+ channelId: input.slack.channelId,
+ threadTs: input.slack.threadTs,
+ };
+ const parts = renderInputRequestPostParts(input.request, route);
+ const postedMessageIds: string[] = [];
+
+ try {
+ const permalink = await resolveMessagePermalink(input.slack, input.previewMessageTs);
+ if (permalink !== undefined) {
+ postedMessageIds.push(
+ await postMessage(input.slack, {
+ channel: messageChannelId,
+ markdown_text: permalink,
+ unfurl_links: true,
+ unfurl_media: false,
+ }),
+ );
+ }
+ if (parts.details !== undefined) {
+ postedMessageIds.push(
+ await postMessage(input.slack, {
+ blocks: parts.details.blocks,
+ channel: messageChannelId,
+ text: parts.details.text,
+ unfurl_links: false,
+ unfurl_media: false,
+ }),
+ );
+ }
+ const messageTs = await postMessage(input.slack, {
+ blocks: parts.controls.blocks,
+ channel: messageChannelId,
+ text: parts.controls.text,
+ unfurl_links: false,
+ unfurl_media: false,
+ });
+ postedMessageIds.push(messageTs);
+ return { messageBlocks: parts.controls.blocks, messageChannelId, messageTs };
+ } catch (error) {
+ await Promise.allSettled(
+ postedMessageIds.map(async (ts) => {
+ try {
+ await input.slack.request("chat.delete", { channel: messageChannelId, ts });
+ } catch (cleanupError) {
+ logError(log, "failed to roll back partial private approval delivery", cleanupError, {
+ channelId: messageChannelId,
+ messageTs: ts,
+ });
+ }
+ }),
+ );
+ throw error;
+ }
+}
+
+async function resolveMessagePermalink(
+ slack: Pick<SlackHandle, "channelId" | "request">,
+ messageTs: string,
+): Promise<string | undefined> {
+ if (!slack.channelId || !messageTs) return undefined;
+ const response = await slack.request("chat.getPermalink", {
+ channel: slack.channelId,
+ message_ts: messageTs,
+ });
+ return response.ok === true && typeof response.permalink === "string"
+ ? response.permalink
+ : undefined;
+}
+
+async function postMessage(
+ slack: Pick<SlackHandle, "request">,
+ body: Record<string, unknown>,
+): Promise<string> {
+ const response = await slack.request("chat.postMessage", body);
+ if (response.ok !== true || typeof response.ts !== "string" || response.ts.length === 0) {
+ throw new Error(`Slack chat.postMessage failed: ${response.error ?? "unknown_error"}`);
+ }
+ return response.ts;
+}
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 25ac1f57a..bf450aa28 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -1894,6 +1894,7 @@ describe("slackChannel() inbound mention pipeline", () => {
installationTeamId: null,
teamId: "T01",
threadTs: "1700000000.000300",
+ triggeringMessageTs: "1700000000.000005",
triggeringUserId: "U01",
},
});
@@ -3382,7 +3383,7 @@ describe("slackChannel() HITL interaction pipeline", () => {
});
});
- it("opens freeform modals with installation-scoped credentials and metadata", async () => {
+ it("opens routed freeform modals with installation-scoped credentials and metadata", async () => {
const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");
const channel = slackChannel({ credentials: { botToken } });
@@ -3401,7 +3402,7 @@ describe("slackChannel() HITL interaction pipeline", () => {
},
actions: [
{
- action_id: `${HITL_FREEFORM_ACTION_PREFIX}call_abc123`,
+ action_id: `${HITL_FREEFORM_ACTION_PREFIX}route:C_ORIGINAL:1700000000.000001:call_abc123`,
text: { type: "plain_text", text: "Type your answer" },
value: "call_abc123",
},
@@ -3418,7 +3419,12 @@ describe("slackChannel() HITL interaction pipeline", () => {
view: { private_metadata: string };
};
expect(JSON.parse(body.view.private_metadata)).toMatchObject({
+ channelId: "C_ORIGINAL",
+ continuationToken: "C_ORIGINAL:1700000000.000001",
installationTeamId: "T_INSTALLATION",
+ messageChannelId: "C01",
+ requestId: "call_abc123",
+ threadTs: "1700000000.000001",
});
});
@@ -3835,8 +3841,9 @@ describe("slackChannel() HITL interaction pipeline", () => {
app_installed_team_id: "T_INSTALLATION",
callback_id: HITL_FREEFORM_MODAL_CALLBACK_ID,
private_metadata: JSON.stringify({
- channelId: "C01",
- continuationToken: "C01:1700000000.000001",
+ channelId: "C_ORIGINAL",
+ continuationToken: "C_ORIGINAL:1700000000.000001",
+ messageChannelId: "D_REVIEW",
messageTs: "1700000000.000010",
requestId: "call_abc123",
threadTs: "1700000000.000001",
@@ -3854,12 +3861,12 @@ describe("slackChannel() HITL interaction pipeline", () => {
expect(send).toHaveBeenCalledTimes(1);
const [continuationToken, input] = send.mock.calls[0]!;
- expect(continuationToken).toBe("C01:1700000000.000001");
+ expect(continuationToken).toBe("C_ORIGINAL:1700000000.000001");
expect(input).toMatchObject({
auth: {
attributes: {
author_type: "user",
- channel_id: "C01",
+ channel_id: "C_ORIGINAL",
team_id: "T_ACTOR",
thread_ts: "1700000000.000001",
user_id: "U_SUBMITTER",
@@ -3873,6 +3880,10 @@ describe("slackChannel() HITL interaction pipeline", () => {
inputResponses: [{ requestId: "call_abc123", text: "approved with context" }],
});
expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://slack.com/api/chat.update",
+ expect.objectContaining({ body: expect.stringContaining('"channel":"D_REVIEW"') }),
+ );
});
it("authorizes freeform modal answers before resuming", async () => {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index c9c8562f6..61282c2b1 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -16,7 +16,12 @@ import type { ChannelContinuationOps } from "#public/definitions/channel.js";
import { createLogger, logError } from "#internal/logging.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import type { InputResponse, StrictInputResponses, ValidatedInputResponse } from "#shared/input.js";
+import type {
+ InputRequest,
+ InputResponse,
+ StrictInputResponses,
+ ValidatedInputResponse,
+} from "#shared/input.js";
import {
buildSlackBinding,
buildSlackWorkspaceHandle,
@@ -190,6 +195,8 @@ type SlackSessionFailedHandler = (
* `JSON.stringify` / `JSON.parse`.
*/
export interface SlackPendingApprovalCard {
+ /** Channel containing the approval card; differs from the session channel for DM delivery. */
+ readonly messageChannelId?: string;
readonly messageBlocks: readonly unknown[];
readonly messageTs: string;
}
@@ -203,6 +210,8 @@ export interface SlackChannelState {
threadTs: string | null;
/** Slack team id, when the inbound event carried one. */
teamId: string | null;
+ /** Slack message ts that triggered the active turn. */
+ triggeringMessageTs?: string | null;
/** Slack workspace whose app installation supplies this session's credentials. */
installationTeamId?: string | null;
/**
@@ -604,10 +613,28 @@ export interface SlackChannelInternalEvents extends Omit<
readonly "authorization.required"?: SlackEventHandler<"authorization.required">;
}
+export type SlackApprovalChannel = "direct-message" | "thread";
+
+/** Input request passed to a {@link SlackApprovalChannelResolver}. */
+export type SlackApprovalRequest = InputRequest;
+
+/** Chooses the Slack destination for one input request. */
+export type SlackApprovalChannelResolver = (
+ request: SlackApprovalRequest,
+ ctx: SessionContext,
+) => SlackApprovalChannel | Promise<SlackApprovalChannel>;
+
export interface SlackChannelConfig {
readonly credentials?: SlackChannelCredentials;
readonly botName?: string;
+ /**
+ * Chooses where each input request is delivered. Direct-message requests go to the
+ * Slack user who triggered the active turn; the session thread names that reviewer
+ * without exposing the request. Defaults to `"thread"` when omitted.
+ */
+ readonly approvalChannel?: SlackApprovalChannelResolver;
+
/** Optional presentation-only activity rendered without starting parent turns. */
readonly activity?: {
readonly renderers: readonly SlackActivityRenderer[];
@@ -877,7 +904,8 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
"reasoning.appended": reasoningHandler,
"actions.requested": actionsHandler,
"message.completed": messageCompletedHandler,
- "input.requested": config.events?.["input.requested"] ?? defaultInputRequestedHandler(),
+ "input.requested":
+ config.events?.["input.requested"] ?? defaultInputRequestedHandler(config.approvalChannel),
"authorization.required":
authorizationRequiredOverride === undefined
? defaultEvents["authorization.required"]
@@ -903,6 +931,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
teamId: null as string | null,
installationTeamId: null as string | null,
triggeringUserId: null,
+ triggeringMessageTs: null,
pendingToolCallMessage: null,
lastReasoningTypingAtMs: null,
lastReasoningTypingStatus: null,
@@ -1316,6 +1345,7 @@ async function dispatchSlackMessage(input: {
installationTeamId: input.installationTeamId ?? null,
teamId: input.message.teamId ?? null,
threadTs: input.message.threadTs,
+ triggeringMessageTs: input.message.ts,
triggeringUserId: author?.userId ?? null,
};
const sessionOperations = bindSlackSessionOperations({