Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): introduce approval lifecycle events, Slack adapter impl (#1371)

Ben Pankow755f12d74758
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v8.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v8.ts
new file mode 100644
index 000000000..02a61cf70
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v8.ts
@@ -0,0 +1,10 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineInstructions({
+ markdown: `Use session ${ctx.session.id} when correlating evidence.`,
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v8.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v8.ts
new file mode 100644
index 000000000..3c6e1498e
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v8.ts
@@ -0,0 +1,11 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineSkill({
+ description: `Review evidence for session ${ctx.session.id}.`,
+ markdown: "# Evidence review\n\nCheck every claim against its source.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v14.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v14.ts
new file mode 100644
index 000000000..76b54cd92
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v14.ts
@@ -0,0 +1,14 @@
+import { z as z3 } from "zod/v3";
+
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineTool({
+ description: "Return the active session identifier.",
+ inputSchema: z3.object({ prefix: z3.string() }),
+ execute: ({ prefix }) => ({ sessionId: `${prefix}:${ctx.session.id}` }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v10.ts b/packages/eve/extension-contracts/compatibility/hook/v10.ts
new file mode 100644
index 000000000..38ecc7e06
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v10.ts
@@ -0,0 +1,13 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "subagent.completed"(event, ctx) {
+ console.info("subagent completed", {
+ output: event.data.output,
+ sessionId: ctx.session.id,
+ subagentName: event.data.subagentName,
+ });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v9.ts b/packages/eve/extension-contracts/compatibility/hook/v9.ts
new file mode 100644
index 000000000..38ecc7e06
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v9.ts
@@ -0,0 +1,13 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "subagent.completed"(event, ctx) {
+ console.info("subagent completed", {
+ output: event.data.output,
+ sessionId: ctx.session.id,
+ subagentName: event.data.subagentName,
+ });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v9.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v9.json
new file mode 100644
index 000000000..0c0c994b1
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v9.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 9,
+ "sha256": "04853cbdfe992a845aa506dec793c91fec2b32efedd43c80044fdceb8bf7e83b",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v9.json b/packages/eve/extension-contracts/reports/dynamicSkill/v9.json
new file mode 100644
index 000000000..e6f1170e1
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v9.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 9,
+ "sha256": "04853cbdfe992a845aa506dec793c91fec2b32efedd43c80044fdceb8bf7e83b",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v15.json b/packages/eve/extension-contracts/reports/dynamicTool/v15.json
new file mode 100644
index 000000000..7f10997e4
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v15.json
@@ -0,0 +1,13 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 15,
+ "sha256": "0156eef2a51783d90364298ce1dc2e04fe7f8881dc0281f851b47c30c42d6ab8",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v11.json b/packages/eve/extension-contracts/reports/hook/v11.json
new file mode 100644
index 000000000..54470b30e
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v11.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 11,
+ "sha256": "5ff0b04e2fa257847e22a4e9886f9d8e1cc260aeb619a64cf3cb52557294b0d4",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index 304a73506..3423da280 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -36,6 +36,7 @@ export interface RouteHandlerArgs<TState = undefined> {
export interface SendPayload {
readonly message?: string | UserContent;
+ readonly [key: string]: unknown;
readonly inputResponses?: readonly InputResponse[];
/**
* Context strings contributed by the channel. eve appends each entry
diff --git a/packages/eve/src/cli/commands/registry-package.ts b/packages/eve/src/cli/commands/registry-package.ts
index f9b8845cf..137bf949f 100644
--- a/packages/eve/src/cli/commands/registry-package.ts
+++ b/packages/eve/src/cli/commands/registry-package.ts
@@ -76,7 +76,11 @@ async function selectComponents(
try {
return await asker.askMany(question);
} catch (error) {
- if (!options.nonInteractive || !(error instanceof Error) || error.name !== "InteractionRequired")
+ if (
+ !options.nonInteractive ||
+ !(error instanceof Error) ||
+ error.name !== "InteractionRequired"
+ )
throw error;
const question = (error as import("#setup/ask.js").InteractionRequired).question;
const { setupQuestionToWire } = await import("#setup/setup-question-wire.js");
@@ -139,7 +143,12 @@ export async function runRegistryPackage(input: {
});
let completion: RegistrySetupCompletion = { facts: [] };
if (options.skipSetup === true) return completion;
- if (!options.nonInteractive && options.yes !== true && options.prompter === undefined && !interactive) {
+ if (
+ !options.nonInteractive &&
+ options.yes !== true &&
+ options.prompter === undefined &&
+ !interactive
+ ) {
logger.log(operations.setupReminder(item));
return completion;
}
diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.ts
index 5a0683055..5582366b3 100644
--- a/packages/eve/src/client/message-reducer.test.ts
+++ b/packages/eve/src/client/message-reducer.test.ts
@@ -462,7 +462,7 @@ describe("defaultMessageReducer", () => {
kind: "tool-approval",
options: [
{ id: "approve", label: "Yes", style: "primary" },
- { id: "cancel", label: "No", style: "danger" },
+ { id: "deny", label: "No", style: "danger" },
],
prompt: "Approve tool call: bash",
requestId: "approval_1",
@@ -499,7 +499,7 @@ describe("defaultMessageReducer", () => {
kind: "tool-approval",
options: [
{ id: "approve", label: "Yes", style: "primary" },
- { id: "cancel", label: "No", style: "danger" },
+ { id: "deny", label: "No", style: "danger" },
],
prompt: "Approve tool call: bash",
requestId: "approval_1",
@@ -585,7 +585,7 @@ describe("defaultMessageReducer", () => {
kind: "tool-approval",
options: [
{ id: "approve", label: "Yes", style: "primary" },
- { id: "cancel", label: "No", style: "danger" },
+ { id: "deny", label: "No", style: "danger" },
],
prompt: "Approve tool call: bash",
requestId: "approval_1",
@@ -600,7 +600,7 @@ describe("defaultMessageReducer", () => {
data = reducer.reduce(data, {
data: {
createdAt: 1,
- responses: [{ optionId: "cancel", requestId: "approval_1" }],
+ responses: [{ optionId: "deny", requestId: "approval_1" }],
},
type: "client.input.responded",
});
@@ -630,12 +630,12 @@ describe("defaultMessageReducer", () => {
kind: "tool-approval",
options: [
{ id: "approve", label: "Yes", style: "primary" },
- { id: "cancel", label: "No", style: "danger" },
+ { id: "deny", label: "No", style: "danger" },
],
prompt: "Approve tool call: bash",
requestId: "approval_1",
},
- inputResponse: { optionId: "cancel", requestId: "approval_1" },
+ inputResponse: { optionId: "deny", requestId: "approval_1" },
kind: "tool-call",
name: "bash",
},
@@ -665,7 +665,7 @@ describe("defaultMessageReducer", () => {
kind: "tool-approval",
options: [
{ id: "approve", label: "Yes", style: "primary" },
- { id: "cancel", label: "No", style: "danger" },
+ { id: "deny", label: "No", style: "danger" },
],
prompt: "Approve tool call: bash",
requestId: "approval_1",
diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.ts
index abbd18971..bab12af49 100644
--- a/packages/eve/src/client/message-reducer.ts
+++ b/packages/eve/src/client/message-reducer.ts
@@ -168,6 +168,42 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E
return next;
}
+ case "approval.candidate":
+ // Candidate progress is responder-specific. Applications can consume the
+ // raw stream event for private UI without changing the shared tool part.
+ return data;
+
+ case "approval.settled": {
+ const existing = findToolPartByApprovalId(data, event.data.requestId);
+ if (existing === undefined) return data;
+ if (event.data.outcome === "approved") {
+ return updateToolPart(data, existing.toolCallId, {
+ approval: { approved: true, id: event.data.requestId, reason: undefined },
+ input: existing.input,
+ state: "approval-responded",
+ stepIndex: existing.stepIndex,
+ toolCallId: existing.toolCallId,
+ toolMetadata: existing.toolMetadata,
+ toolName: existing.toolName,
+ type: "dynamic-tool",
+ });
+ }
+ return updateToolPart(data, existing.toolCallId, {
+ approval: {
+ approved: false,
+ id: event.data.requestId,
+ reason: "Tool execution was cancelled.",
+ },
+ input: existing.input,
+ state: "output-denied",
+ stepIndex: existing.stepIndex,
+ toolCallId: existing.toolCallId,
+ toolMetadata: existing.toolMetadata,
+ toolName: existing.toolName,
+ type: "dynamic-tool",
+ });
+ }
+
case "action.result": {
const descriptor = normalizeActionResult(event.data.result);
const existing = findToolPart(data, event.data.result.callId);
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index a44ac0f89..63ced864a 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -23,14 +23,14 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: { current: 12, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dropped: {} },
dynamicTool: {
- current: 14,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
+ current: 15,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
dropped: {},
},
connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
hook: {
- current: 10,
- supported: [10],
+ current: 11,
+ supported: [10, 11],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
2: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -44,9 +44,9 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
skill: { current: 1, supported: [1], dropped: {} },
- dynamicSkill: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], dropped: {} },
+ dynamicSkill: { current: 9, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9], dropped: {} },
instructions: { current: 1, supported: [1], dropped: {} },
- dynamicInstructions: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], dropped: {} },
+ dynamicInstructions: { current: 9, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9], dropped: {} },
config: { current: 1, supported: [1], dropped: {} },
state: { current: 3, supported: [1, 2, 3], dropped: {} },
} as const satisfies Record<string, ExtensionCapabilityContract>;
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index bcda76f5f..95509d969 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -393,9 +393,13 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
schemaSession = setHarnessEmissionState(schemaSession, emissionState);
}
for (const { authorization, result } of completedAuths) {
+ const candidateId = pendingAuth?.challenges.find(
+ (challenge) => challenge.attemptId === result.attemptId,
+ )?.candidateId;
await handleEvent(
createAuthorizationCompletedEvent({
authorization,
+ candidateId,
name: result.name,
outcome: "authorized",
sequence: emissionState.sequence,
diff --git a/packages/eve/src/harness/approval-candidates.ts b/packages/eve/src/harness/approval-candidates.ts
index 2c641e2db..1b9ab5f80 100644
--- a/packages/eve/src/harness/approval-candidates.ts
+++ b/packages/eve/src/harness/approval-candidates.ts
@@ -20,6 +20,7 @@ export interface ApprovalCandidateAuditRecord {
readonly status: ApprovalCandidateStatus;
readonly createdAt: number;
readonly completedAt?: number;
+ readonly eventEmitted?: boolean;
readonly expiresAt?: number;
readonly reason?: string;
}
@@ -37,6 +38,7 @@ export interface ApprovalSettlementAuditRecord {
readonly requestId: string;
readonly settledAt: number;
readonly candidateId?: string;
+ readonly eventEmitted?: boolean;
}
export interface ActiveApprovalCandidate {
@@ -47,6 +49,7 @@ export interface ActiveApprovalCandidate {
readonly createdAt: number;
readonly expiresAt: number;
readonly authorizationChallenges?: readonly AuthorizationChallenge[];
+ readonly pendingEventEmitted?: boolean;
}
interface DurableApprovalState {
@@ -117,6 +120,59 @@ export function createApprovalCandidate(input: {
return { changed: true, state: writeApprovalState(expiredState, next) };
}
+/** Marks the pending candidate event as emitted. */
+export function markApprovalCandidatePendingEventEmitted(input: {
+ readonly candidateId: string;
+ readonly state: SessionStateMap | undefined;
+}): SessionStateMap | undefined {
+ const approvalState = readApprovalState(input.state);
+ const candidate = approvalState.activeCandidates[input.candidateId];
+ if (candidate === undefined || candidate.pendingEventEmitted === true) return input.state;
+ return writeApprovalState(input.state, {
+ ...approvalState,
+ activeCandidates: {
+ ...approvalState.activeCandidates,
+ [input.candidateId]: { ...candidate, pendingEventEmitted: true },
+ },
+ });
+}
+
+/** Marks a terminal candidate history event as emitted. */
+export function markApprovalCandidateHistoryEventEmitted(input: {
+ readonly candidateId: string;
+ readonly state: SessionStateMap | undefined;
+}): SessionStateMap | undefined {
+ const approvalState = readApprovalState(input.state);
+ let changed = false;
+ const candidateHistory = approvalState.candidateHistory.map((candidate) => {
+ if (candidate.candidateId !== input.candidateId || candidate.eventEmitted === true) {
+ return candidate;
+ }
+ changed = true;
+ return { ...candidate, eventEmitted: true };
+ });
+ return changed
+ ? writeApprovalState(input.state, { ...approvalState, candidateHistory })
+ : input.state;
+}
+
+/** Marks a terminal settlement event as emitted. */
+export function markApprovalSettlementEventEmitted(input: {
+ readonly requestId: string;
+ readonly state: SessionStateMap | undefined;
+}): SessionStateMap | undefined {
+ const approvalState = readApprovalState(input.state);
+ const settlement = approvalState.settlements[input.requestId];
+ if (settlement === undefined || settlement.eventEmitted === true) return input.state;
+ return writeApprovalState(input.state, {
+ ...approvalState,
+ settlements: {
+ ...approvalState.settlements,
+ [input.requestId]: { ...settlement, eventEmitted: true },
+ },
+ });
+}
+
/** Marks a candidate as waiting on a private authorization challenge. */
export function markApprovalCandidateAuthorizationRequired(input: {
readonly authorizationChallenges: readonly AuthorizationChallenge[];
diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.ts
index e6d019ead..07500b36a 100644
--- a/packages/eve/src/harness/authorization.test.ts
+++ b/packages/eve/src/harness/authorization.test.ts
@@ -45,6 +45,49 @@ describe("authorization callback results", () => {
});
});
+function candidateChallenge(name: string, candidateId: string) {
+ return {
+ candidateId,
+ challenge: { url: `https://idp.example/${candidateId}` },
+ hookUrl: `https://eve.example/${candidateId}`,
+ name,
+ };
+}
+
+describe("pending authorization state", () => {
+ it("merges concurrent candidate challenges by authorization name", () => {
+ const first = setPendingAuthorization(undefined, {
+ challenges: [candidateChallenge("candidate-1:github", "candidate-1")],
+ });
+ const second = setPendingAuthorization(first, {
+ challenges: [candidateChallenge("candidate-2:github", "candidate-2")],
+ });
+
+ expect(getPendingAuthorization(second)?.challenges).toEqual([
+ expect.objectContaining({ candidateId: "candidate-1", name: "candidate-1:github" }),
+ expect.objectContaining({ candidateId: "candidate-2", name: "candidate-2:github" }),
+ ]);
+ });
+
+ it("replaces a repeated challenge without duplicating it", () => {
+ const first = setPendingAuthorization(undefined, {
+ challenges: [candidateChallenge("candidate-1:github", "candidate-1")],
+ });
+ const second = setPendingAuthorization(first, {
+ challenges: [
+ {
+ ...candidateChallenge("candidate-1:github", "candidate-1"),
+ hookUrl: "https://eve.example/refreshed",
+ },
+ ],
+ });
+
+ expect(getPendingAuthorization(second)?.challenges).toEqual([
+ expect.objectContaining({ hookUrl: "https://eve.example/refreshed" }),
+ ]);
+ });
+});
+
describe("pending authorization attempts", () => {
const challenge = (
name: string,
diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.ts
index 61d0580d8..f2eeda658 100644
--- a/packages/eve/src/harness/authorization.ts
+++ b/packages/eve/src/harness/authorization.ts
@@ -50,6 +50,7 @@ const AUTHORIZATION_PENDING_BRAND = "__eveAuthorizationPending" as const;
export interface AuthorizationChallenge {
/** Opaque identity of this exact authorization attempt. */
readonly attemptId?: string;
+ readonly candidateId?: string;
readonly name: string;
readonly challenge: ConnectionAuthorizationChallenge;
readonly hookUrl: string;
@@ -113,6 +114,7 @@ export function redactSignalResume(signal: AuthorizationSignal): AuthorizationSi
return requestAuthorization(
signal.challenges.map((entry) => ({
attemptId: entry.attemptId,
+ candidateId: entry.candidateId,
name: entry.name,
challenge: entry.challenge,
hookUrl: entry.hookUrl,
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 12a60ce74..738548c49 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -50,6 +50,8 @@ import { PendingSkillAnnouncementKey } from "#context/dynamic-skill-lifecycle.js
import { toErrorMessage } from "#shared/errors.js";
import {
createActionResultEvent,
+ createApprovalCandidateEvent,
+ createApprovalSettledEvent,
createCompactionCompletedEvent,
createCompactionRequestedEvent,
createContextClearedEvent,
@@ -119,6 +121,16 @@ import {
} from "#harness/input-extraction.js";
import { createToolResultMessagePartFromToolError } from "#harness/action-result-helpers.js";
import { activeTurnId } from "#harness/active-turn-id.js";
+import {
+ getApprovalAuditState,
+ markApprovalCandidateHistoryEventEmitted,
+ markApprovalCandidatePendingEventEmitted,
+ markApprovalSettlementEventEmitted,
+} from "#harness/approval-candidates.js";
+import {
+ coordinateApprovalDelivery,
+ shouldPrepareApprovalPolicyTools,
+} from "#harness/approval-delivery-coordinator.js";
import { buildTelemetryRuntimeContext } from "#harness/instrumentation-runtime-context.js";
import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";
import { createInstrumentationHandleEvent } from "#harness/instrumentation-native-events.js";
@@ -136,10 +148,6 @@ import {
appendPendingInputBatch,
} from "#harness/input-requests.js";
import { queueDeferredStepInput } from "#harness/pending-input-batches.js";
-import {
- coordinateApprovalDelivery,
- shouldPrepareApprovalPolicyTools,
-} from "#harness/approval-delivery-coordinator.js";
import {
convertStaleResponsesToUserMessage,
dropStaleSessionLimitContinuationResponses,
@@ -772,7 +780,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}),
});
session = coordinated.session;
- if (emit !== undefined) {
+ if (emit) {
for (const message of coordinated.feedback) {
await emit(
createMessageCompletedEvent({
@@ -783,6 +791,74 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}),
);
}
+ const audit = getApprovalAuditState(session.state);
+ for (const candidate of audit.activeCandidates.filter(
+ (entry) => entry.pendingEventEmitted !== true,
+ )) {
+ await emit(
+ createApprovalCandidateEvent({
+ candidateId: candidate.candidateId,
+ outcome: "pending",
+ requestId: candidate.requestId,
+ responderPrincipalId: candidate.responder.principalId,
+ sequence: emissionState.sequence,
+ stepIndex: emissionState.stepIndex,
+ turnId: emissionState.turnId,
+ }),
+ );
+ session = {
+ ...session,
+ state: markApprovalCandidatePendingEventEmitted({
+ candidateId: candidate.candidateId,
+ state: session.state,
+ }),
+ };
+ }
+ for (const candidate of audit.candidateHistory.filter(
+ (entry) => entry.eventEmitted !== true && entry.status !== "allowed",
+ )) {
+ await emit(
+ createApprovalCandidateEvent({
+ candidateId: candidate.candidateId,
+ outcome: candidate.status as Exclude<
+ typeof candidate.status,
+ "allowed" | "authorization-required"
+ >,
+ requestId: candidate.requestId,
+ responderPrincipalId: candidate.responder.principalId,
+ reason: candidate.reason,
+ sequence: emissionState.sequence,
+ stepIndex: emissionState.stepIndex,
+ turnId: emissionState.turnId,
+ }),
+ );
+ session = {
+ ...session,
+ state: markApprovalCandidateHistoryEventEmitted({
+ candidateId: candidate.candidateId,
+ state: session.state,
+ }),
+ };
+ }
+ for (const settlement of audit.settlements.filter((entry) => entry.eventEmitted !== true)) {
+ await emit(
+ createApprovalSettledEvent({
+ outcome: settlement.outcome === "allowed" ? "approved" : "cancelled",
+ requestId: settlement.requestId,
+ responderPrincipalId: settlement.actor.principalId,
+ sequence: emissionState.sequence,
+ stepIndex: emissionState.stepIndex,
+ turnId: emissionState.turnId,
+ }),
+ );
+ session = {
+ ...session,
+ state: markApprovalSettlementEventEmitted({
+ requestId: settlement.requestId,
+ state: session.state,
+ }),
+ };
+ }
}
if (coordinated.kind === "park") return { next: null, session };
if (coordinated.kind === "continue-coordination") {
@@ -798,6 +874,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
await emit(
createAuthorizationRequiredEvent({
authorization: challenge.challenge,
+ candidateId: challenge.candidateId,
description:
challenge.challenge.instructions ?? `Authorization required for ${challenge.name}`,
name: challenge.name,
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index 92c47133a..424c9f044 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -214,6 +214,36 @@ export interface ActionsRequestedStreamEvent {
type: "actions.requested";
}
+export type ApprovalCandidateOutcome = "pending" | "rejected" | "failed" | "timed-out" | "stale";
+
+/** Safe lifecycle event for one responder-bound approval candidate. */
+export interface ApprovalCandidateStreamEvent {
+ data: {
+ candidateId: string;
+ outcome: ApprovalCandidateOutcome;
+ requestId: string;
+ responderPrincipalId: string;
+ reason?: string;
+ sequence: number;
+ stepIndex: number;
+ turnId: string;
+ };
+ type: "approval.candidate";
+}
+
+/** Terminal durable settlement for one approval request. */
+export interface ApprovalSettledStreamEvent {
+ data: {
+ outcome: "approved" | "cancelled";
+ requestId: string;
+ responderPrincipalId: string;
+ sequence: number;
+ stepIndex: number;
+ turnId: string;
+ };
+ type: "approval.settled";
+}
+
/**
* Stream event emitted when the harness needs human input before it can
* continue the run.
@@ -529,6 +559,7 @@ export interface CompactionCompletedStreamEvent {
export interface AuthorizationRequiredStreamEvent {
data: {
authorization?: ConnectionAuthorizationChallenge;
+ candidateId?: string;
description: string;
name: string;
sequence: number;
@@ -560,6 +591,7 @@ export type ConnectionAuthorizationOutcome = AuthorizationOutcome;
*/
export interface AuthorizationCompletedStreamEvent {
data: {
+ candidateId?: string;
/**
* The challenge from the matching `authorization.required` event,
* journaled across the park. Lets channels keep rendering the
@@ -616,6 +648,8 @@ export interface SessionCompletedStreamEvent {
* consumers receive {@link MessageStreamEvent}.
*/
export type UnstampedMessageStreamEvent =
+ | ApprovalCandidateStreamEvent
+ | ApprovalSettledStreamEvent
| ContextClearedStreamEvent
| CompactionCompletedStreamEvent
| CompactionRequestedStreamEvent
@@ -977,6 +1011,7 @@ export function createActionsRequestedEvent(input: {
*/
export function createAuthorizationRequiredEvent(input: {
readonly authorization?: ConnectionAuthorizationChallenge;
+ readonly candidateId?: string;
readonly description: string;
readonly name: string;
readonly sequence: number;
@@ -994,6 +1029,9 @@ export function createAuthorizationRequiredEvent(input: {
if (input.authorization !== undefined) {
data.authorization = input.authorization;
}
+ if (input.candidateId !== undefined) {
+ data.candidateId = input.candidateId;
+ }
if (input.webhookUrl !== undefined) {
data.webhookUrl = input.webhookUrl;
}
@@ -1010,6 +1048,7 @@ export function createAuthorizationRequiredEvent(input: {
*/
export function createAuthorizationCompletedEvent(input: {
readonly authorization?: ConnectionAuthorizationChallenge;
+ readonly candidateId?: string;
readonly name: string;
readonly outcome: AuthorizationOutcome;
readonly reason?: string;
@@ -1027,6 +1066,9 @@ export function createAuthorizationCompletedEvent(input: {
if (input.authorization !== undefined) {
data.authorization = input.authorization;
}
+ if (input.candidateId !== undefined) {
+ data.candidateId = input.candidateId;
+ }
if (input.reason !== undefined) {
data.reason = input.reason;
}
@@ -1036,6 +1078,20 @@ export function createAuthorizationCompletedEvent(input: {
};
}
+/** Creates a safe candidate lifecycle event. */
+export function createApprovalCandidateEvent(
+ input: ApprovalCandidateStreamEvent["data"],
+): ApprovalCandidateStreamEvent {
+ return { data: input, type: "approval.candidate" };
+}
+
+/** Creates a terminal approval settlement event. */
+export function createApprovalSettledEvent(
+ input: ApprovalSettledStreamEvent["data"],
+): ApprovalSettledStreamEvent {
+ return { data: input, type: "approval.settled" };
+}
+
/**
* Creates the `input.requested` event for one pending HITL batch.
*/
diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.ts
index 804814b09..5d82569ac 100644
--- a/packages/eve/src/public/channels/slack/defaults.test.ts
+++ b/packages/eve/src/public/channels/slack/defaults.test.ts
@@ -51,6 +51,177 @@ function authRequiredEvent(
};
}
+describe("defaultEvents approval lifecycle", () => {
+ it("sends candidate progress privately", async () => {
+ const { channel, postEphemeral } = buildChannelStub({
+ pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ });
+ const ctx = sessionContext({
+ attributes: { user_id: "U777" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T1:U777",
+ principalType: "user",
+ });
+
+ await defaultEvents["approval.candidate"]!(
+ {
+ candidateId: "candidate-1",
+ outcome: "pending",
+ requestId: "approval-1",
+ responderPrincipalId: "slack:T1:U777",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ ctx,
+ );
+
+ expect(postEphemeral).toHaveBeenCalledWith(
+ "U777",
+ "Checking whether you can approve this action…",
+ );
+ });
+
+ it("routes candidate progress from event identity instead of ambient auth", async () => {
+ const { channel, postEphemeral } = buildChannelStub({
+ pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ teamId: "T1",
+ });
+ const wrongAmbientUser = sessionContext({
+ attributes: { user_id: "U_WRONG" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T1:U_WRONG",
+ principalType: "user",
+ });
+
+ await defaultEvents["approval.candidate"]!(
+ {
+ candidateId: "candidate-1",
+ outcome: "pending",
+ requestId: "approval-1",
+ responderPrincipalId: "slack:T1:U777",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ wrongAmbientUser,
+ );
+
+ expect(postEphemeral).toHaveBeenCalledWith(
+ "U777",
+ "Checking whether you can approve this action…",
+ );
+ expect(channel.state.pendingApprovalCandidateUsers).toEqual({ "candidate-1": "U777" });
+ });
+
+ it("delivers an immediate rejection through the responder mapping", async () => {
+ const { channel, postEphemeral } = buildChannelStub({
+ pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ });
+ const ctx = sessionContext({
+ attributes: { user_id: "U777" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T1:U777",
+ principalType: "user",
+ });
+
+ await defaultEvents["approval.candidate"]!(
+ {
+ candidateId: "candidate-1",
+ outcome: "rejected",
+ requestId: "approval-1",
+ responderPrincipalId: "slack:T1:U777",
+ reason: "GitHub write access is required.",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ ctx,
+ );
+
+ expect(postEphemeral).toHaveBeenCalledWith("U777", "GitHub write access is required.");
+ });
+
+ it("updates the shared card only after settlement", async () => {
+ const { channel, request } = buildChannelStub({
+ pendingApprovalCards: {
+ "approval-1": {
+ messageBlocks: [
+ {
+ actions: [{ action_id: "eve_input:approval-1:button:1" }],
+ body: { text: "Approve?", type: "mrkdwn" },
+ type: "card",
+ },
+ ],
+ messageTs: "123.456",
+ userId: "U777",
+ },
+ },
+ });
+
+ await defaultEvents["approval.settled"]!(
+ {
+ outcome: "approved",
+ requestId: "approval-1",
+ responderPrincipalId: "slack:T1:U777",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ sessionCtx,
+ );
+
+ expect(request).toHaveBeenCalledWith(
+ "chat.update",
+ expect.objectContaining({ channel: "C123", text: "Answered: Approve", ts: "123.456" }),
+ );
+ expect(channel.state.pendingApprovalCards).toEqual({});
+ });
+
+ it("settles the request even when the stored click id differs from its sibling button", async () => {
+ const { channel, request } = buildChannelStub({
+ pendingApprovalCards: {
+ "approval-1": {
+ messageBlocks: [
+ {
+ actions: [
+ { action_id: "eve_input:approval-1:button:0" },
+ { action_id: "eve_input:approval-1:button:1" },
+ ],
+ body: { text: "Approve?", type: "mrkdwn" },
+ type: "card",
+ },
+ ],
+ messageTs: "123.456",
+ userId: "U777",
+ },
+ },
+ });
+
+ await defaultEvents["approval.settled"]!(
+ {
+ outcome: "approved",
+ requestId: "approval-1",
+ responderPrincipalId: "slack:T1:U777",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ sessionCtx,
+ );
+
+ const update = request.mock.calls.find(([method]) => method === "chat.update")?.[1] as {
+ blocks?: unknown[];
+ };
+ expect(JSON.stringify(update.blocks)).not.toContain("eve_input:approval-1");
+ });
+});
+
describe("defaultEvents authorization.required", () => {
it("posts a public status and delivers the challenge ephemerally to the triggering user", async () => {
const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
@@ -68,6 +239,58 @@ describe("defaultEvents authorization.required", () => {
expect(channel.state.pendingAuthMessageTs).toEqual({ notion: "ts1" });
});
+ it("does not post a public status for candidate-scoped authorization", async () => {
+ const { channel, post, postEphemeral } = buildChannelStub({
+ pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ triggeringUserId: "U_OTHER",
+ });
+
+ await defaultEvents["authorization.required"]!(
+ { ...authRequiredEvent(), candidateId: "candidate-1" },
+ channel,
+ sessionCtx,
+ );
+
+ expect(post).not.toHaveBeenCalled();
+ expect(postEphemeral).toHaveBeenCalledTimes(1);
+ });
+
+ it("uses only the candidate mapping for candidate-scoped challenges", async () => {
+ const { channel, postEphemeral } = buildChannelStub({
+ pendingApprovalCandidateUsers: { "candidate-1": "U_CANDIDATE" },
+ triggeringUserId: "U_STALE",
+ });
+ const wrongAmbientUser = sessionContext({
+ attributes: { user_id: "U_WRONG" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T01:U_WRONG",
+ principalType: "user",
+ });
+
+ await defaultEvents["authorization.required"]!(
+ { ...authRequiredEvent(), candidateId: "candidate-1" },
+ channel,
+ wrongAmbientUser,
+ );
+
+ expect(postEphemeral.mock.calls[0]?.[0]).toBe("U_CANDIDATE");
+ });
+
+ it("does not leak a candidate challenge when its mapping is missing", async () => {
+ const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U_STALE" });
+ await defaultEvents["authorization.required"]!(
+ { ...authRequiredEvent(), candidateId: "candidate-missing" },
+ channel,
+ sessionContext({
+ attributes: { user_id: "U_WRONG" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T01:U_WRONG",
+ principalType: "user",
+ }),
+ );
+ expect(postEphemeral).not.toHaveBeenCalled();
+ });
+
it("targets the current Slack caller instead of stale channel state", async () => {
const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U_FIRST" });
const currentCaller = sessionContext({
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index ab86ab0fd..d57197a5d 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -11,6 +11,7 @@ import {
type ConnectionAuthorizationOutcome,
} from "#public/channels/slack/connections.js";
import {
+ buildAnsweredBlocks,
renderInputRequestPostParts,
type SlackInputRequestPostPart,
} from "#public/channels/slack/hitl.js";
@@ -32,6 +33,21 @@ const log = createLogger("slack.defaults");
const REASONING_TYPING_REFRESH_INTERVAL_MS = 5_000;
const REASONING_TYPING_MIN_PROGRESS_CHARS = 4;
+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}`;
+ return [candidate.actions, candidate.elements].some(
+ (entries) =>
+ Array.isArray(entries) &&
+ entries.some((entry) => {
+ if (typeof entry !== "object" || entry === null) return false;
+ const actionId = (entry as { action_id?: unknown }).action_id;
+ return typeof actionId === "string" && actionId.startsWith(requestActionPrefix);
+ }),
+ );
+}
+
/**
* Workspace-scoped projection of the Slack actor that produced
* `message`, derived into a {@link SessionAuthContext}. Used by both
@@ -107,7 +123,18 @@ function firstNonEmptyLine(text: string): string | undefined {
export function defaultInputRequestedHandler(): NonNullable<SlackChannelEvents["input.requested"]> {
return async (data, channel, _ctx) => {
for (const post of buildInputRequestPosts(data.requests)) {
- await channel.thread.post(post);
+ 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,
+ };
+ }
+ }
+ channel.state.pendingApprovalCards = cards;
}
};
}
@@ -119,33 +146,35 @@ export function defaultInputRequestedHandler(): NonNullable<SlackChannelEvents["
*/
function buildInputRequestPosts(
requests: readonly InputRequest[],
-): Array<{ blocks: unknown[]; text: string }> {
- const details: SlackInputRequestPostPart[] = [];
- const controls: SlackInputRequestPostPart[] = [];
+): Array<{ blocks: unknown[]; requests: InputRequest[]; text: string }> {
+ const details: Array<SlackInputRequestPostPart & { readonly request: InputRequest }> = [];
+ const controls: Array<SlackInputRequestPostPart & { readonly request: InputRequest }> = [];
for (const request of requests) {
const parts = renderInputRequestPostParts(request);
- if (parts.details) details.push(parts.details);
- controls.push(parts.controls);
+ if (parts.details) details.push({ ...parts.details, request });
+ controls.push({ ...parts.controls, request });
}
return [...groupInputRequestPostParts(details), ...groupInputRequestPostParts(controls)];
}
function groupInputRequestPostParts(
- parts: readonly SlackInputRequestPostPart[],
-): Array<{ blocks: unknown[]; text: string }> {
- const groups: Array<{ blocks: unknown[]; fallbacks: string[] }> = [];
+ parts: readonly (SlackInputRequestPostPart & { readonly request: InputRequest })[],
+): Array<{ blocks: unknown[]; requests: InputRequest[]; text: string }> {
+ const groups: Array<{ blocks: unknown[]; fallbacks: string[]; requests: InputRequest[] }> = [];
for (const part of parts) {
const current = groups.at(-1);
if (current && current.blocks.length + part.blocks.length <= SLACK_MAX_BLOCKS_PER_MESSAGE) {
current.blocks.push(...part.blocks);
current.fallbacks.push(part.text);
+ current.requests.push(part.request);
} else {
- groups.push({ blocks: [...part.blocks], fallbacks: [part.text] });
+ groups.push({ blocks: [...part.blocks], fallbacks: [part.text], requests: [part.request] });
}
}
return groups.map((group) => ({
blocks: group.blocks,
+ requests: group.requests,
text: truncateMessageText(group.fallbacks.join("\n")),
}));
}
@@ -159,6 +188,51 @@ function groupInputRequestPostParts(
* which user overrides cannot express.
*/
export const defaultEvents: SlackChannelInternalEvents = {
+ async "approval.candidate"(event, channel, _ctx) {
+ const userId = channel.state.pendingApprovalCandidateUsers?.[event.candidateId];
+ if (event.outcome === "pending" && userId !== undefined) {
+ await channel.thread.postEphemeral(userId, "Checking whether you can approve this action…");
+ return;
+ }
+ if (userId === undefined) return;
+ if (event.outcome === "rejected" || event.outcome === "failed") {
+ await channel.thread.postEphemeral(
+ userId,
+ event.reason ?? "We couldn’t verify your approval. Please try again.",
+ );
+ }
+ },
+
+ async "approval.settled"(event, channel, _ctx) {
+ const cards = channel.state.pendingApprovalCards ?? {};
+ const card = cards[event.requestId];
+ if (card === undefined || channel.state.channelId === null) return;
+ const answerLabel = event.outcome === "approved" ? "Approve" : "Cancel";
+ const blocks = card.messageBlocks.flatMap((block) => {
+ if (!blockContainsRequestAction(block, event.requestId)) return [block];
+ if (typeof block !== "object" || block === null) return [];
+ const candidate = block as Record<string, unknown>;
+ if (candidate.type !== "card") {
+ return buildAnsweredBlocks({ answerLabel, promptBlocks: [], userId: card.userId });
+ }
+ const { actions: _actions, ...withoutActions } = candidate;
+ return buildAnsweredBlocks({
+ answerLabel,
+ promptBlocks: [withoutActions],
+ userId: card.userId,
+ });
+ });
+ await channel.slack.request("chat.update", {
+ blocks,
+ channel: channel.state.channelId,
+ text: `Answered: ${answerLabel}`,
+ ts: card.messageTs,
+ });
+ const next = { ...cards };
+ delete next[event.requestId];
+ channel.state.pendingApprovalCards = next;
+ },
+
async "turn.started"(_event, channel, _ctx) {
channel.state.pendingToolCallMessage = null;
channel.state.lastReasoningTypingAtMs = null;
@@ -243,16 +317,18 @@ export const defaultEvents: SlackChannelInternalEvents = {
async "authorization.required"(event, channel, ctx) {
const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);
const triggeringUserId =
- slackUserIdFromAuthContext(ctx.session.auth.current) ??
- channel.state.triggeringUserId ??
- null;
+ event.candidateId === undefined
+ ? (slackUserIdFromAuthContext(ctx.session.auth.current) ??
+ channel.state.triggeringUserId ??
+ null)
+ : (channel.state.pendingApprovalCandidateUsers?.[event.candidateId] ?? null);
const challengeUrl = event.authorization?.url;
// Post a public, link-free status so everyone in the thread can see
// the session is blocked and later see it complete. The challenge
// itself remains private.
const pending = channel.state.pendingAuthMessageTs ?? {};
- if (pending[event.name] === undefined) {
+ if (event.candidateId === undefined && pending[event.name] === undefined) {
const publicText = buildAuthRequiredPublicText({
displayName,
hasUser: triggeringUserId !== null,
@@ -302,7 +378,7 @@ export const defaultEvents: SlackChannelInternalEvents = {
async "authorization.completed"(event, channel, _ctx) {
const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);
- if (event.outcome === "authorized") {
+ if (event.outcome === "authorized" && event.candidateId === undefined) {
await channel.thread.startTyping(`Connected to ${displayName}. Resuming...`);
}
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index f4f341eb6..54d68fd9c 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -560,23 +560,20 @@ async function handleViewSubmission(
userName: user?.username ?? user?.name,
}),
})
+ .then(() =>
+ updateAnsweredFreeformCard({
+ channelId: metadata.channelId,
+ messageTs: metadata.messageTs,
+ answerLabel: text,
+ userId: triggeringUserId ?? undefined,
+ deps: _deps,
+ }),
+ )
.catch((error: unknown) => {
- log.error("freeform answer delivery failed", { error });
+ log.error("freeform answer delivery or answered-card update failed", { error });
}),
);
- ctx.waitUntil(
- updateAnsweredFreeformCard({
- channelId: metadata.channelId,
- messageTs: metadata.messageTs,
- answerLabel: text,
- userId: triggeringUserId ?? undefined,
- deps: _deps,
- }).catch((error: unknown) => {
- log.error("freeform answered-card update failed", { error });
- }),
- );
-
return ack;
}
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 2dbe619b8..898af189a 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -583,6 +583,12 @@ describe("slackChannel() default event handlers", () => {
value: "approve",
},
]);
+ expect(ctx.state.pendingApprovalCards).toEqual({
+ approval_abc123: {
+ messageBlocks: controlsBody.blocks,
+ messageTs: "1700000001.000001",
+ },
+ });
});
it("keeps a large tool input out of the Slack button callback", async () => {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 2682f4df8..ba9078b36 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -6,8 +6,9 @@ import type {
ChannelResolveSession,
ChannelSource,
} from "#channel/channel-operations.js";
+import { defaultDeliverResult } from "#channel/adapter.js";
import type { Session, SessionHandle } from "#channel/session.js";
-import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { SessionAuthContext } from "#channel/types.js";
import type { CardElement } from "#compiled/chat/index.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ChannelContinuationOps } from "#public/definitions/channel.js";
@@ -175,6 +176,12 @@ type SlackSessionFailedHandler = (
* step boundaries. Anything written here must round-trip through
* `JSON.stringify` / `JSON.parse`.
*/
+export interface SlackPendingApprovalCard {
+ readonly messageBlocks: readonly unknown[];
+ readonly messageTs: string;
+ readonly userId?: string;
+}
+
export interface SlackChannelState {
/** Slack channel id seeded by the inbound mention. */
channelId: string | null;
@@ -212,6 +219,9 @@ export interface SlackChannelState {
* resolution outcome.
*/
pendingAuthMessageTs?: Record<string, string>;
+ pendingApprovalCards?: Record<string, SlackPendingApprovalCard>;
+ pendingApprovalCandidateUsers?: Record<string, string>;
+ approvalResponderUsers?: Record<string, string>;
}
/**
@@ -437,6 +447,8 @@ export type SlackInboundResultOrPromise = SlackMentionResultOrPromise;
* context and exposes the ID as `data.sessionId`.
*/
export interface SlackChannelEvents {
+ readonly "approval.candidate"?: SlackEventHandler<"approval.candidate">;
+ readonly "approval.settled"?: SlackEventHandler<"approval.settled">;
readonly "turn.started"?: SlackEventHandler<"turn.started">;
readonly "actions.requested"?: SlackEventHandler<"actions.requested">;
readonly "action.partial"?: SlackEventHandler<"action.partial">;
@@ -483,8 +495,6 @@ export interface SlackChannelConfig {
/** Override the default webhook route path (`/eve/v1/slack`). */
readonly route?: string;
- /** Policy for accepted messages that arrive while a turn is active. */
- readonly turnPolicy?: TurnPolicy;
/**
* Inbound upload policy applied to file attachments before they reach
@@ -640,10 +650,27 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
const uploadPolicy = mergeUploadPolicy(config.uploadPolicy);
const slackFetchFile = createSlackFetchFile({ botToken: config.credentials?.botToken });
const authorizationRequiredOverride = config.events?.["authorization.required"];
+ const candidateHandler =
+ config.events?.["approval.candidate"] ?? defaultEvents["approval.candidate"]!;
const turnStartedHandler = config.events?.["turn.started"] ?? defaultEvents["turn.started"]!;
const mergedEvents: SlackChannelInternalEvents = {
...defaultEvents,
...config.events,
+ async "approval.candidate"(data, channel, ctx) {
+ const responderUserId = channel.state.approvalResponderUsers?.[data.responderPrincipalId];
+ if (data.outcome === "pending" && responderUserId !== undefined) {
+ channel.state.pendingApprovalCandidateUsers = {
+ ...channel.state.pendingApprovalCandidateUsers,
+ [data.candidateId]: responderUserId,
+ };
+ }
+ await candidateHandler(data, channel, ctx);
+ if (data.outcome !== "pending") {
+ const users = { ...channel.state.pendingApprovalCandidateUsers };
+ delete users[data.candidateId];
+ channel.state.pendingApprovalCandidateUsers = users;
+ }
+ },
async "turn.started"(data, channel, ctx) {
const triggeringUserId = slackUserIdFromAuthContext(ctx.session.auth.current);
if (triggeringUserId !== undefined) {
@@ -669,7 +696,6 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
SlackInstrumentationMetadata
>({
kindHint: "slack",
- turnPolicy: config.turnPolicy,
state: {
channelId: null as string | null,
threadTs: null as string | null,
@@ -679,6 +705,9 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
lastReasoningTypingAtMs: null,
lastReasoningTypingStatus: null,
pendingAuthMessageTs: {},
+ pendingApprovalCards: {},
+ pendingApprovalCandidateUsers: {},
+ approvalResponderUsers: {},
},
fetchFile: slackFetchFile,
metadata(state): SlackInstrumentationMetadata {
@@ -694,6 +723,21 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
return rebuildSlackContext(state, session, config.credentials);
},
+ deliver(payload, channel) {
+ const cards = payload.pendingApprovalCards;
+ if (typeof cards === "object" && cards !== null) {
+ channel.state.pendingApprovalCards = { ...channel.state.pendingApprovalCards, ...cards };
+ }
+ const responders = payload.approvalResponderUsers;
+ if (typeof responders === "object" && responders !== null) {
+ channel.state.approvalResponderUsers = {
+ ...channel.state.approvalResponderUsers,
+ ...responders,
+ };
+ }
+ return defaultDeliverResult(payload);
+ },
+
routes: [
POST<SlackChannelState>(config.route ?? SLACK_CHANNEL_DEFAULT_ROUTE, async (req, args) => {
const { waitUntil } = args;
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 2e125798b..ca7c998ad 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -17,7 +17,7 @@ import type {
} from "#channel/channel-operations.js";
import type { RouteDefinition } from "#channel/routes.js";
import type { Session, SessionHandle } from "#channel/session.js";
-import type { DeliverPayload, TurnPolicy } from "#channel/types.js";
+import type { DeliverPayload } from "#channel/types.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
@@ -182,6 +182,8 @@ type ChannelSessionFailedHandler<TCtx> = (
* and the channel context, with no `ctx`; its data includes `sessionId`.
*/
export interface ChannelEvents<TCtx = void> {
+ readonly "approval.candidate"?: ChannelEventHandler<"approval.candidate", TCtx>;
+ readonly "approval.settled"?: ChannelEventHandler<"approval.settled", TCtx>;
readonly "context.cleared"?: ChannelEventHandler<"context.cleared", TCtx>;
readonly "compaction.requested"?: ChannelEventHandler<"compaction.requested", TCtx>;
readonly "compaction.completed"?: ChannelEventHandler<"compaction.completed", TCtx>;
@@ -248,7 +250,6 @@ export interface Channel<
input: ReceiveInput<TReceiveTarget>,
ctx: ChannelReceiveContext<TState>,
) => Promise<Session>;
- readonly turnPolicy?: TurnPolicy;
}
/**
@@ -281,7 +282,6 @@ export function defineChannel<
adapter,
cors,
receive: definition.receive,
- turnPolicy: definition.turnPolicy,
};
return compiled;
@@ -290,6 +290,8 @@ export function defineChannel<
// The Record type fails to compile if this map drifts from the ChannelEvents
// keys in either direction.
const channelEventTypes: Record<keyof ChannelEvents, null> = {
+ "approval.candidate": null,
+ "approval.settled": null,
"context.cleared": null,
"compaction.requested": null,
"compaction.completed": null,
@@ -390,8 +392,9 @@ function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<str
};
},
- deliver(payload: DeliverPayload) {
- return defaultDeliverResult(payload);
+ deliver(payload: DeliverPayload, adapterCtx) {
+ if (definition.deliver === undefined) return defaultDeliverResult(payload);
+ return definition.deliver(payload, adapterCtx as TCtx);
},
...eventHandlers,
diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.ts
index 525a92756..b41693ba6 100644
--- a/packages/eve/src/public/definitions/hook.ts
+++ b/packages/eve/src/public/definitions/hook.ts
@@ -1,10 +1,9 @@
-import type { MessageStreamEvent } from "../../protocol/message.js";
+import type { HandleMessageStreamEvent } from "../../protocol/message.js";
import type { SessionContext } from "./callback-context.js";
import type { ExactDefinition } from "./exact.js";
-// Stamped, so a hook can read `event.meta` unguarded.
-type ProtocolEvent<TType extends MessageStreamEvent["type"]> = Extract<
- MessageStreamEvent,
+type ProtocolEvent<TType extends HandleMessageStreamEvent["type"]> = Extract<
+ HandleMessageStreamEvent,
{ type: TType }
>;
@@ -18,6 +17,8 @@ type ProtocolEvent<TType extends MessageStreamEvent["type"]> = Extract<
export interface HookEventMap {
readonly "action.partial": ProtocolEvent<"action.partial">;
readonly "action.result": ProtocolEvent<"action.result">;
+ readonly "approval.candidate": ProtocolEvent<"approval.candidate">;
+ readonly "approval.settled": ProtocolEvent<"approval.settled">;
readonly "actions.requested": ProtocolEvent<"actions.requested">;
readonly "authorization.completed": ProtocolEvent<"authorization.completed">;
readonly "authorization.required": ProtocolEvent<"authorization.required">;
diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.ts
index bb7e0448f..d94b98788 100644
--- a/packages/eve/src/shared/channel-definition.ts
+++ b/packages/eve/src/shared/channel-definition.ts
@@ -3,7 +3,8 @@ import type { UserContent } from "ai";
import type { ChannelReceiveContext } from "#channel/channel-operations.js";
import type { RouteDefinition } from "#channel/routes.js";
import type { Session, SessionHandle } from "#channel/session.js";
-import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { StepInput } from "#harness/types.js";
/**
* Enriched return shape from a channel's {@link ChannelAdapter.fetchFile}
@@ -52,6 +53,7 @@ export interface GenericChannelDefinition<
> {
/** Policy used by message sends that do not provide an explicit override. */
readonly turnPolicy?: TurnPolicy;
+ deliver?(payload: DeliverPayload, ctx: TCtx): StepInput | void | Promise<StepInput | void>;
readonly state?: TState;
/**
* CORS policy for this channel's HTTP routes. `true` enables H3/Nitro's