Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): enforce exact channel input responses (#2340)

Ruia43e14f340e7
diff --git a/.changeset/tame-horses-listen.md b/.changeset/tame-horses-listen.md
new file mode 100644
index 000000000..9f49bed3f
--- /dev/null
+++ b/.changeset/tame-horses-listen.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Prevent channel HITL responses from carrying channel-local metadata into strict session-inbox payloads. Channel and session `respond()` calls now accept exact response literals or values proven by `parseInputResponses()`, rejecting imprecise `InputResponse[]` values that could have erased extra keys.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index a0b025c9b..3ce52c272 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -111,6 +111,18 @@ await session.reset({ reason: "Retire this session" });
await session.getEventStream({ startIndex: 12 });
```
+`respond()` accepts exact response literals directly. If responses have already
+been widened to `InputResponse[]`—for example, after decoding a platform
+payload—validate them with eve's strict schema before delivery. The validated
+type preserves that proof across channel wrappers:
+
+```ts
+import { parseInputResponses } from "eve/client";
+
+const inputResponses = parseInputResponses(decodedResponses);
+await source.respond(inputResponses, { auth });
+```
+
Message sends use the channel's `turnPolicy`, which defaults to `"steer"`. An accepted message arriving during an active turn is durably buffered before eve cancels that turn and starts the message as a replacement turn. Configure `turnPolicy: "queue"` on `defineChannel(...)` when active turns should finish in order, or override one send:
```ts
diff --git a/packages/eve/extension-contracts/compatibility/channel/v4.ts b/packages/eve/extension-contracts/compatibility/channel/v4.ts
new file mode 100644
index 000000000..3ea081a11
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v4.ts
@@ -0,0 +1,12 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+export default defineChannel({
+ routes: [
+ POST("/input", async (_request, { attachSession, from }) => {
+ const inputResponses = [{ optionId: "approve", requestId: "approval-1" }];
+ await from("thread-1").respond(inputResponses, { auth: null });
+ await attachSession("session-1").respond(inputResponses, { auth: null });
+ return new Response("ok");
+ }),
+ ],
+});
diff --git a/packages/eve/extension-contracts/compatibility/schedule/v2.ts b/packages/eve/extension-contracts/compatibility/schedule/v2.ts
new file mode 100644
index 000000000..0d30c387a
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/schedule/v2.ts
@@ -0,0 +1,18 @@
+import channel from "../channel/v2.js";
+import { defineSchedule } from "#public/schedules/index.js";
+
+export default defineSchedule({
+ cron: "0 0 * * *",
+ async run({ appAuth, to, waitUntil }) {
+ waitUntil(
+ (async () => {
+ const session = await to(channel, { sessionRef: "daily" }).send("Start review", {
+ auth: appAuth,
+ });
+ await session.respond([{ optionId: "approve", requestId: "approval-1" }], {
+ auth: appAuth,
+ });
+ })(),
+ );
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v5.json b/packages/eve/extension-contracts/reports/channel/v5.json
new file mode 100644
index 000000000..bd92b9db3
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v5.json
@@ -0,0 +1,17 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 5,
+ "sha256": "760ea4e2840b45e41b8304476125961cf727ad61e90b9433a63c681a00d48a77",
+ "exports": [
+ "DELETE",
+ "GET",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "isChannel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v3.json b/packages/eve/extension-contracts/reports/schedule/v3.json
new file mode 100644
index 000000000..46d76b54e
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v3.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 3,
+ "sha256": "c7828af3a7864655e45b9797428d76db54bef76542553262bbc91e24cf548988",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule"
+ ]
+}
diff --git a/packages/eve/src/channel/channel-operations.test.ts b/packages/eve/src/channel/channel-operations.test.ts
index adb446be1..6befd4505 100644
--- a/packages/eve/src/channel/channel-operations.test.ts
+++ b/packages/eve/src/channel/channel-operations.test.ts
@@ -1,7 +1,33 @@
import { describe, expect, it, vi } from "vitest";
-import { createChannelOperations } from "#channel/channel-operations.js";
+import { createChannelOperations, type ChannelSource } from "#channel/channel-operations.js";
import type { Runtime } from "#channel/types.js";
+import { type InputResponse, parseInputResponses } from "#runtime/input/types.js";
+
+function authoredChannelRespondTypeChecks(source: ChannelSource): void {
+ const responseWithMetadata = {
+ kind: "tool-approval",
+ optionId: "approve",
+ requestId: "approval-1",
+ } as const;
+ const responsesWithMetadata = [responseWithMetadata] as const;
+
+ // @ts-expect-error channel-local metadata is not part of the input-response contract.
+ void source.respond([responseWithMetadata], { auth: null });
+ // @ts-expect-error exactness must survive a preassembled response array.
+ void source.respond(responsesWithMetadata, { auth: null });
+
+ const widenedResponses: readonly InputResponse[] = responsesWithMetadata;
+ // @ts-expect-error widened responses must be schema-validated before delivery.
+ void source.respond(widenedResponses, { auth: null });
+
+ const validatedResponses = parseInputResponses([
+ { optionId: "approve", requestId: "approval-1" },
+ ]);
+ void source.respond(validatedResponses, { auth: null });
+}
+
+void authoredChannelRespondTypeChecks;
function createRuntime(): Runtime {
return {
diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.ts
index 5e7bc1bdf..774b8e59e 100644
--- a/packages/eve/src/channel/channel-operations.ts
+++ b/packages/eve/src/channel/channel-operations.ts
@@ -18,7 +18,11 @@ import type {
SessionCallback,
TurnPolicy,
} from "#channel/types.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import {
+ type InputResponse,
+ parseInputResponses,
+ type StrictInputResponses,
+} from "#runtime/input/types.js";
import type { JsonObject } from "#shared/json.js";
import type { RunMode } from "#shared/run-mode.js";
@@ -53,8 +57,8 @@ export interface ChannelSource<TState = undefined> {
/** Starts or resumes a turn with a user message. May create a session. */
send(message: string | UserContent, options: ChannelSendOptions<TState>): Promise<Session>;
/** Answers pending input requests. Never creates a session. */
- respond(
- inputResponses: readonly InputResponse[],
+ respond<const TResponses extends readonly InputResponse[]>(
+ inputResponses: StrictInputResponses<TResponses>,
options: ChannelRespondOptions<TState>,
): Promise<Session>;
/** Cooperatively cancels the active turn without creating a session. */
@@ -117,10 +121,11 @@ export function createChannelOperations<TState = undefined>(input: {
if (inputResponses.length === 0) {
throw new Error("respond() requires at least one input response.");
}
+ const validatedInputResponses = parseInputResponses(inputResponses);
return await bound.deliver(
{
context: options.context,
- inputResponses,
+ inputResponses: validatedInputResponses,
outputSchema: options.outputSchema,
state: options.state,
},
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index d0933d84c..9da4cf610 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -1,9 +1,35 @@
import { describe, expect, it, vi } from "vitest";
-import { buildSessionHandle, createAttachSessionFn, createSession } from "#channel/session.js";
+import {
+ buildSessionHandle,
+ createAttachSessionFn,
+ createSession,
+ type Session,
+} from "#channel/session.js";
import type { Runtime } from "#channel/types.js";
import { ContextContainer } from "#context/container.js";
import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";
+import { type InputResponse, parseInputResponses } from "#runtime/input/types.js";
+
+function fixedSessionRespondTypeChecks(session: Session): void {
+ const responsesWithMetadata = [
+ { kind: "tool-approval", optionId: "approve", requestId: "approval-1" },
+ ] as const;
+
+ // @ts-expect-error fixed sessions enforce the same exact input-response contract.
+ void session.respond(responsesWithMetadata, { auth: null });
+
+ const widenedResponses: readonly InputResponse[] = responsesWithMetadata;
+ // @ts-expect-error widened responses must be schema-validated before delivery.
+ void session.respond(widenedResponses, { auth: null });
+
+ const validatedResponses = parseInputResponses([
+ { optionId: "approve", requestId: "approval-1" },
+ ]);
+ void session.respond(validatedResponses, { auth: null });
+}
+
+void fixedSessionRespondTypeChecks;
function createRuntime(): Runtime {
return {
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 9ba1a996c..babfb31b7 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -21,7 +21,11 @@ import { DEFAULT_TURN_POLICY } from "#channel/types.js";
import { serializeUrlFilePartsInMessage } from "#channel/send-input.js";
import type { SessionAuth } from "#context/keys.js";
import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import {
+ type InputResponse,
+ parseInputResponses,
+ type StrictInputResponses,
+} from "#runtime/input/types.js";
import type { JsonObject } from "#shared/json.js";
import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";
@@ -34,8 +38,8 @@ export interface Session {
options: SessionSendOptions,
): Promise<SessionSendCommandResult>;
/** Answers pending input requests on this exact session ID. */
- respond(
- inputResponses: readonly InputResponse[],
+ respond<const TResponses extends readonly InputResponse[]>(
+ inputResponses: StrictInputResponses<TResponses>,
options: SessionRespondOptions,
): Promise<SessionSendCommandResult>;
/** Requests cancellation of this exact session's active turn or one owned task. */
@@ -114,13 +118,14 @@ export function createSession(
if (inputResponses.length === 0) {
throw new Error("respond() requires at least one input response.");
}
+ const validatedInputResponses = parseInputResponses(inputResponses);
const caller = sessionCallbackToTurnCaller(options.callback);
const delivery = createDelivery(metadata);
const payload: {
context?: readonly string[];
inputResponses: readonly InputResponse[];
outputSchema?: JsonObject;
- } = { inputResponses };
+ } = { inputResponses: validatedInputResponses };
if (options.context !== undefined) payload.context = options.context;
if (options.outputSchema !== undefined) payload.outputSchema = options.outputSchema;
const commandWithoutCaller = {
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index 4dbc3fb4f..505c46807 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -150,6 +150,8 @@ export {
inputResponseSchema,
isInputRequest,
isInputResponse,
+ parseInputResponse,
+ parseInputResponses,
} from "#runtime/input/types.js";
export { resolveTextToResponse, resolveTextToResponses } from "#channel/resolve-text.js";
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index ca8a86ccd..1f449c2aa 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -27,8 +27,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
dropped: {},
},
- channel: { current: 4, supported: [1, 2, 3, 4], dropped: {} },
- schedule: { current: 2, supported: [1, 2], dropped: {} },
+ channel: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
+ schedule: { current: 3, supported: [1, 2, 3], dropped: {} },
subagent: { current: 2, supported: [1, 2], dropped: {} },
connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
hook: {
diff --git a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
index fe366e430..7b9d7e45b 100644
--- a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
@@ -7,7 +7,7 @@ import type {
InternalChannelSource,
} from "#channel/channel-operations.js";
import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import { type InputResponse, inputResponseSchema } from "#runtime/input/types.js";
export type ObservedChannelDelivery<TState> =
| (ChannelSendOptions<TState> & { readonly message: string | UserContent })
@@ -31,7 +31,7 @@ export function mockChannelContext<TState = undefined>(
async respond(inputResponses, options) {
return (await observeDelivery(continuationToken, {
...options,
- inputResponses,
+ inputResponses: inputResponseSchema.array().parse(inputResponses),
})) as never;
},
async cancel() {
@@ -47,9 +47,16 @@ export function mockChannelContext<TState = undefined>(
return { status: "no_active_session" } as never;
},
async [INTERNAL_CHANNEL_DELIVER](payload, options) {
+ const validatedPayload =
+ payload.inputResponses === undefined
+ ? payload
+ : {
+ ...payload,
+ inputResponses: inputResponseSchema.array().parse(payload.inputResponses),
+ };
return (await observeDelivery(continuationToken, {
...options,
- ...payload,
+ ...validatedPayload,
} as ObservedChannelDelivery<TState>)) as never;
},
};
diff --git a/packages/eve/src/internal/testing/mocks/mocks.test.ts b/packages/eve/src/internal/testing/mocks/mocks.test.ts
index fadd641cb..f488fb35c 100644
--- a/packages/eve/src/internal/testing/mocks/mocks.test.ts
+++ b/packages/eve/src/internal/testing/mocks/mocks.test.ts
@@ -1,8 +1,24 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";
import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
import { mockTool } from "#internal/testing/mocks/mock-tool.js";
+describe("mockChannelContext", () => {
+ it("rejects producer metadata outside the input response contract", async () => {
+ const observeDelivery = vi.fn();
+ const source = mockChannelContext(observeDelivery).from("thread-1");
+
+ await expect(
+ source.respond(
+ [{ kind: "tool-approval", optionId: "approve", requestId: "approval-1" }] as never,
+ { auth: null },
+ ),
+ ).rejects.toThrow(/unrecognized_keys/);
+ expect(observeDelivery).not.toHaveBeenCalled();
+ });
+});
+
describe("mockTool", () => {
it("assigns deterministic defaults from the tool name", () => {
const tool = mockTool({ name: "get_weather", execute: () => 42 });
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index 75ccb7029..de276b6f8 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -51,6 +51,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 "#runtime/input/types.js";
const log = createLogger("discord.channel");
@@ -615,7 +616,7 @@ async function dispatchCommand(input: {
async function dispatchInputResponses(input: {
readonly conversationId: string;
- readonly inputResponses: readonly { requestId: string; optionId?: string; text?: string }[];
+ readonly inputResponses: readonly ValidatedInputResponse[];
readonly interaction: DiscordComponentInteraction | DiscordModalSubmitInteraction;
readonly from: ChannelFrom<DiscordChannelState>;
}): Promise<void> {
diff --git a/packages/eve/src/public/channels/discord/hitl.ts b/packages/eve/src/public/channels/discord/hitl.ts
index 2458f2166..63285c44a 100644
--- a/packages/eve/src/public/channels/discord/hitl.ts
+++ b/packages/eve/src/public/channels/discord/hitl.ts
@@ -10,7 +10,12 @@ import {
type DiscordComponentInteraction,
type DiscordModalSubmitInteraction,
} from "#public/channels/discord/inbound.js";
-import type { InputOption, InputRequest, InputResponse } from "#runtime/input/types.js";
+import {
+ type InputOption,
+ type InputRequest,
+ parseInputResponse,
+ type ValidatedInputResponse,
+} from "#runtime/input/types.js";
/** Maps Discord component kinds (ACTION_ROW, BUTTON, STRING_SELECT, TEXT_INPUT) to their wire `type` integers used in component payloads. */
export const DISCORD_COMPONENT_TYPE = {
@@ -171,17 +176,17 @@ export function isDiscordFreeformComponent(customId: string): boolean {
*/
export function deriveComponentInputResponses(
interaction: DiscordComponentInteraction,
-): readonly InputResponse[] {
+): readonly ValidatedInputResponse[] {
const payload = decodeHitlCustomId(interaction.customId, DISCORD_HITL_CUSTOM_ID_PREFIX);
if (!payload) return [];
if (payload.optionId !== undefined) {
- return [{ optionId: payload.optionId, requestId: payload.requestId }];
+ return [parseInputResponse({ optionId: payload.optionId, requestId: payload.requestId })];
}
const selected = interaction.values[0];
if (selected !== undefined) {
- return [{ optionId: selected, requestId: payload.requestId }];
+ return [parseInputResponse({ optionId: selected, requestId: payload.requestId })];
}
return [];
@@ -194,11 +199,11 @@ export function deriveComponentInputResponses(
*/
export function deriveModalInputResponses(
interaction: DiscordModalSubmitInteraction,
-): readonly InputResponse[] {
+): readonly ValidatedInputResponse[] {
const payload = decodeHitlCustomId(interaction.customId, DISCORD_HITL_FREEFORM_CUSTOM_ID_PREFIX);
const text = interaction.textInputs[DISCORD_HITL_FREEFORM_TEXT_INPUT_ID];
if (!payload || text === undefined) return [];
- return [{ requestId: payload.requestId, text }];
+ return [parseInputResponse({ requestId: payload.requestId, text })];
}
function encodeHitlCustomId(prefix: string, payload: HitlCustomIdPayload): string {
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 8c5de0df7..1d39ac680 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -46,7 +46,7 @@ import {
createEveSessionStreamRoutePath,
createEveSubagentStreamRoutePath,
} from "#protocol/routes.js";
-import { type InputResponse, isInputResponse } from "#runtime/input/types.js";
+import { isInputResponse, type ValidatedInputResponse } from "#runtime/input/types.js";
import { type AuthFn, routeAuth } from "#public/channels/auth.js";
import {
collectUploadPolicyViolations,
@@ -898,7 +898,7 @@ function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | R
interface ParsedSessionMessageBody {
callback?: SessionCallback;
message?: string | UserContent;
- inputResponses?: readonly InputResponse[];
+ inputResponses?: readonly ValidatedInputResponse[];
context?: readonly string[];
outputSchema?: JsonObject;
turnPolicy?: TurnPolicy;
@@ -1255,7 +1255,9 @@ function checkUploadPolicy(
);
}
-function parseInputResponses(value: unknown): readonly InputResponse[] | Response | undefined {
+function parseInputResponses(
+ value: unknown,
+): readonly ValidatedInputResponse[] | Response | undefined {
if (value === undefined) return undefined;
if (!Array.isArray(value) || value.length === 0) {
return Response.json(
diff --git a/packages/eve/src/public/channels/slack/hitl.test.ts b/packages/eve/src/public/channels/slack/hitl.test.ts
index ab199689e..c3b135d43 100644
--- a/packages/eve/src/public/channels/slack/hitl.test.ts
+++ b/packages/eve/src/public/channels/slack/hitl.test.ts
@@ -32,6 +32,20 @@ function makeRequest(overrides: Partial<InputRequest>): InputRequest {
}
describe("deriveHitlResponse", () => {
+ it("keeps Slack classification outside the durable input response type", () => {
+ const derived: NonNullable<ReturnType<typeof deriveHitlResponse>> = {
+ kind: "tool-approval",
+ response: {
+ // @ts-expect-error Slack classification is not part of InputResponse.
+ kind: "tool-approval",
+ optionId: "approve",
+ requestId: "approval_abc123",
+ },
+ };
+
+ expect(derived.kind).toBe("tool-approval");
+ });
+
it("decodes a button click with a requestId that contains underscores", () => {
// `requestId` is the AI SDK `action.callId`, which always starts
// with `call_…` and contains underscores. The old encoding
@@ -42,7 +56,9 @@ describe("deriveHitlResponse", () => {
value: "approve",
});
- expect(response).toEqual({ requestId: "call_abc123", optionId: "approve" });
+ expect(response).toEqual({
+ response: { requestId: "call_abc123", optionId: "approve" },
+ });
});
it("decodes a radio / select click from selectedOptionValue", () => {
@@ -51,7 +67,7 @@ describe("deriveHitlResponse", () => {
selectedOptionValue: "weekly",
});
- expect(response).toEqual({ requestId: "call_xyz", optionId: "weekly" });
+ expect(response).toEqual({ response: { requestId: "call_xyz", optionId: "weekly" } });
});
it("preserves tool-approval metadata from a button action id", () => {
@@ -62,8 +78,10 @@ describe("deriveHitlResponse", () => {
expect(response).toEqual({
kind: "tool-approval",
- optionId: "approve",
- requestId: "approval_abc123",
+ response: {
+ optionId: "approve",
+ requestId: "approval_abc123",
+ },
});
});
@@ -335,8 +353,10 @@ describe("renderInputRequestBlocks", () => {
const response = deriveHitlResponse({ actionId: button.action_id, value: button.value });
expect(response).toEqual({
- requestId: "call_with_many_underscores_99",
- optionId: "yes_please",
+ response: {
+ requestId: "call_with_many_underscores_99",
+ optionId: "yes_please",
+ },
});
});
@@ -378,8 +398,10 @@ describe("renderInputRequestBlocks", () => {
selectedOptionValue: widget.options[0]!.value,
});
expect(response).toEqual({
- requestId: "call_with_many_underscores_99",
- optionId: "weekly_report",
+ response: {
+ requestId: "call_with_many_underscores_99",
+ optionId: "weekly_report",
+ },
});
});
});
diff --git a/packages/eve/src/public/channels/slack/hitl.ts b/packages/eve/src/public/channels/slack/hitl.ts
index 063fb332a..f1dd580cb 100644
--- a/packages/eve/src/public/channels/slack/hitl.ts
+++ b/packages/eve/src/public/channels/slack/hitl.ts
@@ -19,7 +19,11 @@ import {
truncatePlainText,
truncateSectionText,
} from "#public/channels/slack/limits.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import {
+ type InputRequest,
+ parseInputResponse,
+ type ValidatedInputResponse,
+} from "#runtime/input/types.js";
/**
* Wire-format prefix every framework HITL widget mints onto its
@@ -84,13 +88,12 @@ interface SlackHitlAction {
/**
* Resolved HITL response derived from one Slack interactivity action.
- * Matches the `InputResponse` contract minus `text` — freeform answers
- * come back through a different interaction path.
+ * Slack-local classification stays beside the typed eve input response so
+ * presentation metadata cannot cross the durable session-inbox boundary.
*/
interface DerivedHitlResponse {
- readonly requestId: string;
- readonly optionId: string;
readonly kind?: "tool-approval";
+ readonly response: ValidatedInputResponse;
}
/**
@@ -107,8 +110,13 @@ export function deriveHitlResponse(action: SlackHitlAction): DerivedHitlResponse
const { kind, requestId } = splitEncodedRequest(encodedRequest);
if (!requestId) return null;
return kind === "tool-approval"
- ? { kind, optionId: action.selectedOptionValue, requestId }
- : { optionId: action.selectedOptionValue, requestId };
+ ? {
+ kind,
+ response: parseInputResponse({ optionId: action.selectedOptionValue, requestId }),
+ }
+ : {
+ response: parseInputResponse({ optionId: action.selectedOptionValue, requestId }),
+ };
}
if (action.value !== undefined) {
@@ -116,8 +124,11 @@ export function deriveHitlResponse(action: SlackHitlAction): DerivedHitlResponse
const requestId = match?.groups?.requestId;
if (!requestId) return null;
return match.groups?.kind === "tool-approval"
- ? { kind: "tool-approval", optionId: action.value, requestId }
- : { optionId: action.value, requestId };
+ ? {
+ kind: "tool-approval",
+ response: parseInputResponse({ optionId: action.value, requestId }),
+ }
+ : { response: parseInputResponse({ optionId: action.value, requestId }) };
}
return null;
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 8c9faaf64..0713b16a0 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -47,6 +47,7 @@ import type {
} from "#public/channels/slack/slackChannel.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import { bindSlackSessionOperations } from "#public/channels/slack/session-operations.js";
+import { parseInputResponse } from "#runtime/input/types.js";
const log = createLogger("slack.interactions");
@@ -362,8 +363,8 @@ export async function handleInteractionPost(
const continuationToken = slackContinuationToken(interaction.channelId, interaction.threadTs);
const hitlActions = interaction.actions.flatMap((action) => {
- const response = deriveHitlResponse(action);
- return response === null ? [] : [{ action, response }];
+ const derived = deriveHitlResponse(action);
+ return derived === null ? [] : [{ action, derived }];
});
if (hitlActions.length > 0) {
@@ -376,7 +377,7 @@ export async function handleInteractionPost(
submission: {
type: "block_actions",
actions: hitlActions.map(({ action }) => action),
- inputResponses: hitlActions.map(({ response }) => response),
+ inputResponses: hitlActions.map(({ derived }) => derived.response),
messageTs: hitlActions[0]!.action.messageTs,
user,
},
@@ -569,7 +570,7 @@ async function handleViewSubmission(
const teamId = user?.teamId ?? payload.teamId ?? null;
const submission: SlackInputResponseSubmission = {
type: "view_submission",
- inputResponses: [{ requestId: metadata.requestId, text }],
+ inputResponses: [parseInputResponse({ requestId: metadata.requestId, text })],
messageTs: metadata.messageTs,
user: {
id: triggeringUserId,
diff --git a/packages/eve/src/public/channels/slack/session-operations.ts b/packages/eve/src/public/channels/slack/session-operations.ts
index d30ee3c9b..7ca017337 100644
--- a/packages/eve/src/public/channels/slack/session-operations.ts
+++ b/packages/eve/src/public/channels/slack/session-operations.ts
@@ -6,7 +6,7 @@ import type {
ChannelSource,
} from "#channel/channel-operations.js";
import type { SessionAuthContext } from "#channel/types.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse, StrictInputResponses } from "#runtime/input/types.js";
import type { UserContent } from "ai";
import type { SlackChannelState } from "#public/channels/slack/slackChannel.js";
@@ -25,8 +25,8 @@ export type SlackRespondOptions = Omit<ChannelRespondOptions<SlackChannelState>,
/** Current-owner operations already bound to one Slack thread. */
export interface SlackSessionOperations {
send(message: string | UserContent, options?: SlackSendOptions): ReturnType<SlackSource["send"]>;
- respond(
- inputResponses: readonly InputResponse[],
+ respond<const TResponses extends readonly InputResponse[]>(
+ inputResponses: StrictInputResponses<TResponses>,
options?: SlackRespondOptions,
): ReturnType<SlackSource["respond"]>;
cancel(options?: { readonly turnId?: string }): ReturnType<SlackSource["cancel"]>;
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index cf9c23a5d..f2de478e1 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -9,6 +9,7 @@ import type { ChannelFrom, ChannelSource } from "#channel/channel-operations.js"
import { isHttpRouteDefinition } from "#channel/routes.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { SessionKey } from "#context/keys.js";
+import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
import {
mockChannelContext,
type ObservedChannelDelivery,
@@ -32,12 +33,34 @@ import {
constrainAuthorizationRequired,
slackChannel,
type SlackAuthorizationEventContext,
+ type SlackInboundEventContext,
type SlackInputResponseContext,
type SlackInputResponseSubmission,
+ type SlackInteractionContext,
type SlackChannelState,
type SlackEventContext,
} from "#public/channels/slack/slackChannel.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
+import { type InputResponse, parseInputResponses } from "#runtime/input/types.js";
+
+function slackRespondTypeChecks(
+ interaction: SlackInteractionContext,
+ event: SlackInboundEventContext,
+): void {
+ const widened: readonly InputResponse[] = [{ optionId: "approve", requestId: "approval-1" }];
+ const validated = parseInputResponses(widened);
+
+ // @ts-expect-error Slack thread wrappers reject input-response shapes that erased extra keys.
+ void interaction.respond(widened);
+ void interaction.respond(validated);
+
+ const options = { auth: null, target: { channelId: "C1", threadTs: "T1" } } as const;
+ // @ts-expect-error generic Slack event wrappers enforce the same schema proof.
+ void event.respond(widened, options);
+ void event.respond(validated, options);
+}
+
+void slackRespondTypeChecks;
function getAdapter(channel: unknown): ChannelAdapter<any> {
if (!isCompiledChannel(channel)) {
@@ -2557,6 +2580,16 @@ describe("slackChannel() HITL interaction pipeline", () => {
approvalResponderUsers: { "slack:T01:U_APPROVER": "U_APPROVER" },
},
});
+ expect(
+ sessionInboxWire.encode(
+ { kind: "send", payload: { inputResponses: input.inputResponses } },
+ { version: 1 },
+ ),
+ ).toMatchObject({
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval_abc123" }] }],
+ version: 1,
+ });
});
it("authorizes HITL button answers before resuming with the returned auth", async () => {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index e90d15338..27d7b8996 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -15,7 +15,11 @@ 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 } from "#runtime/input/types.js";
+import type {
+ InputResponse,
+ StrictInputResponses,
+ ValidatedInputResponse,
+} from "#runtime/input/types.js";
import {
buildSlackBinding,
buildSlackWorkspaceHandle,
@@ -314,8 +318,8 @@ export type SlackEventSendFn = (
) => Promise<Session>;
/** Answers pending input requests on one Slack thread. */
-export type SlackEventRespondFn = (
- inputResponses: Parameters<SlackSessionOperations["respond"]>[0],
+export type SlackEventRespondFn = <const TResponses extends readonly InputResponse[]>(
+ inputResponses: StrictInputResponses<TResponses>,
options: SlackEventRespondOptions,
) => ReturnType<SlackSessionOperations["respond"]>;
@@ -435,14 +439,14 @@ export interface SlackInteractionUser {
export type SlackInputResponseSubmission =
| {
readonly type: "block_actions";
- readonly inputResponses: readonly InputResponse[];
+ readonly inputResponses: readonly ValidatedInputResponse[];
readonly actions: readonly SlackInteractionAction[];
readonly messageTs?: string;
readonly user: SlackInteractionUser;
}
| {
readonly type: "view_submission";
- readonly inputResponses: readonly InputResponse[];
+ readonly inputResponses: readonly ValidatedInputResponse[];
readonly messageTs: string;
readonly user: SlackInteractionUser;
};
diff --git a/packages/eve/src/public/channels/teams/hitl.ts b/packages/eve/src/public/channels/teams/hitl.ts
index 793679fdf..28e27fcce 100644
--- a/packages/eve/src/public/channels/teams/hitl.ts
+++ b/packages/eve/src/public/channels/teams/hitl.ts
@@ -2,7 +2,11 @@
* Teams Adaptive Card rendering and decode helpers for eve HITL prompts.
*/
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import {
+ type InputRequest,
+ parseInputResponse,
+ type ValidatedInputResponse,
+} from "#runtime/input/types.js";
import type {
TeamsActivity,
TeamsInvokeActivity,
@@ -153,7 +157,9 @@ export function readTeamsToolApprovalPrompt(activity: TeamsActivity): string | u
* acknowledgement), or an empty array when the activity has no recognizable
* HITL payload or requestId.
*/
-export function deriveTeamsInputResponses(activity: TeamsActivity): readonly InputResponse[] {
+export function deriveTeamsInputResponses(
+ activity: TeamsActivity,
+): readonly ValidatedInputResponse[] {
const value = readActivityValue(activity);
if (!value) return [];
const payload = readHitlPayload(value);
@@ -173,9 +179,9 @@ export function deriveTeamsInputResponses(activity: TeamsActivity): readonly Inp
? value[TEAMS_HITL_FREEFORM_INPUT_ID]
: undefined;
- if (optionId !== undefined) return [{ optionId, requestId }];
- if (text !== undefined) return [{ requestId, text }];
- return [{ requestId }];
+ if (optionId !== undefined) return [parseInputResponse({ optionId, requestId })];
+ if (text !== undefined) return [parseInputResponse({ requestId, text })];
+ return [parseInputResponse({ requestId })];
}
/**
diff --git a/packages/eve/src/public/channels/telegram/hitl.ts b/packages/eve/src/public/channels/telegram/hitl.ts
index a2eb37154..901e5d60e 100644
--- a/packages/eve/src/public/channels/telegram/hitl.ts
+++ b/packages/eve/src/public/channels/telegram/hitl.ts
@@ -6,7 +6,13 @@
* them back to full input responses inside the channel deliver hook.
*/
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import {
+ type InputRequest,
+ type InputResponse,
+ parseInputResponse,
+ parseInputResponses,
+ type ValidatedInputResponse,
+} from "#runtime/input/types.js";
/** Prefix used in Telegram callback_data values generated by eve. */
export const TELEGRAM_HITL_CALLBACK_PREFIX = "eve:";
@@ -96,22 +102,22 @@ export function registerTelegramFreeformPrompt(
* placeholder; {@link resolveTelegramInputResponses} resolves it back to the real
* stored response.
*/
-export function telegramCallbackInputResponse(callbackData: string): InputResponse {
- return {
+export function telegramCallbackInputResponse(callbackData: string): ValidatedInputResponse {
+ return parseInputResponse({
optionId: "selected",
requestId: `${TELEGRAM_CALLBACK_RESPONSE_PREFIX}${callbackData}`,
- };
+ });
}
/** Wraps a reply-to-message id in an `InputResponse` shape for delivery. */
export function telegramReplyInputResponse(input: {
readonly messageId: string;
readonly text: string;
-}): InputResponse {
- return {
+}): ValidatedInputResponse {
+ return parseInputResponse({
requestId: `${TELEGRAM_REPLY_RESPONSE_PREFIX}${input.messageId}`,
text: input.text,
- };
+ });
}
/** True when an input response needs Telegram-specific durable-state remapping. */
@@ -126,7 +132,7 @@ export function isTelegramSyntheticResponse(response: InputResponse): boolean {
export function resolveTelegramInputResponses(
state: TelegramHitlState,
responses: readonly InputResponse[],
-): InputResponse[] {
+): ValidatedInputResponse[] {
const resolved: InputResponse[] = [];
for (const response of responses) {
@@ -153,7 +159,7 @@ export function resolveTelegramInputResponses(
resolved.push(response);
}
- return resolved;
+ return [...parseInputResponses(resolved)];
}
function registerTelegramCallback(state: TelegramHitlState, response: InputResponse): string {
diff --git a/packages/eve/src/runtime/input/types.test.ts b/packages/eve/src/runtime/input/types.test.ts
index dc1487602..a35006034 100644
--- a/packages/eve/src/runtime/input/types.test.ts
+++ b/packages/eve/src/runtime/input/types.test.ts
@@ -152,4 +152,15 @@ describe("inputResponseSchema", () => {
expect(inputResponseSchema.parse(value)).toEqual(value);
expect(isInputResponse(value)).toBe(true);
});
+
+ it("rejects channel-local metadata", () => {
+ const value = {
+ kind: "tool-approval",
+ optionId: "approve",
+ requestId: "req-4",
+ };
+
+ expect(() => inputResponseSchema.parse(value)).toThrow();
+ expect(isInputResponse(value)).toBe(false);
+ });
});
diff --git a/packages/eve/src/runtime/input/types.ts b/packages/eve/src/runtime/input/types.ts
index dacf6a3de..c1d90e0ba 100644
--- a/packages/eve/src/runtime/input/types.ts
+++ b/packages/eve/src/runtime/input/types.ts
@@ -72,6 +72,13 @@ export const inputRequestSchema = z
*/
export type InputResponse = z.infer<typeof inputResponseSchema>;
+declare const validatedInputResponseBrand: unique symbol;
+
+/** Input response proven to match the strict durable wire schema. */
+export type ValidatedInputResponse = InputResponse & {
+ readonly [validatedInputResponseBrand]: true;
+};
+
/**
* Zod schema for one input response.
*/
@@ -83,6 +90,43 @@ export const inputResponseSchema = z
})
.strict();
+/** Parses one response and preserves schema validation in its static type. */
+export function parseInputResponse(value: unknown): ValidatedInputResponse {
+ return inputResponseSchema.parse(value) as ValidatedInputResponse;
+}
+
+/** Parses response arrays whose element types were widened before delivery. */
+export function parseInputResponses(value: unknown): readonly ValidatedInputResponse[] {
+ return inputResponseSchema
+ .array()
+ .parse(value)
+ .map((response) => response as ValidatedInputResponse);
+}
+
+type IsWidenedInputResponse<TResponse extends InputResponse> =
+ keyof TResponse extends keyof InputResponse
+ ? keyof InputResponse extends keyof TResponse
+ ? InputResponse extends TResponse
+ ? true
+ : false
+ : false
+ : false;
+
+type StrictInputResponse<TResponse extends InputResponse> = TResponse extends ValidatedInputResponse
+ ? TResponse
+ : IsWidenedInputResponse<TResponse> extends true
+ ? never
+ : TResponse & {
+ readonly [TKey in Exclude<keyof TResponse, keyof InputResponse>]: never;
+ };
+
+/** Rejects extra response keys and imprecise arrays not proven by the strict schema. */
+export type StrictInputResponses<TResponses extends readonly InputResponse[]> = TResponses & {
+ readonly [TIndex in keyof TResponses]: TResponses[TIndex] extends InputResponse
+ ? StrictInputResponse<TResponses[TIndex]>
+ : TResponses[TIndex];
+};
+
/**
* Returns true when a value matches the input request contract.
*/
@@ -93,6 +137,6 @@ export function isInputRequest(value: unknown): value is InputRequest {
/**
* Returns true when a value matches the input response contract.
*/
-export function isInputResponse(value: unknown): value is InputResponse {
+export function isInputResponse(value: unknown): value is ValidatedInputResponse {
return inputResponseSchema.safeParse(value).success;
}
diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
index 1fe940260..d7f4f8ad5 100644
--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {
);
expect(
JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),
- ).toMatchObject({ requires: { channel: 4, schedule: 2, subagent: 2 } });
+ ).toMatchObject({ requires: { channel: 5, schedule: 3, subagent: 2 } });
const app = await scenarioApp({
name: "mounted-extension-installed",
installDependencies: true,