Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): UX for Teams approval authz flow (#2251)

Ben Pankowc47350f9104c
diff --git a/.changeset/refresh-cold-dynamic-approvals.md b/.changeset/refresh-cold-dynamic-approvals.md
new file mode 100644
index 000000000..0e38d37ce
--- /dev/null
+++ b/.changeset/refresh-cold-dynamic-approvals.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Rebuild untransformed session-scoped dynamic tool executors and approval policies on durable continuations so dependency-created tools remain available after replay.
diff --git a/.changeset/teams-approval-settlement.md b/.changeset/teams-approval-settlement.md
new file mode 100644
index 000000000..af332586f
--- /dev/null
+++ b/.changeset/teams-approval-settlement.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Update Teams tool-approval cards only after approval settlement, with the outcome and the Teams responder who acted.
diff --git a/docs/channels/teams.mdx b/docs/channels/teams.mdx
index f2662b6d6..633a20ed2 100644
--- a/docs/channels/teams.mdx
+++ b/docs/channels/teams.mdx
@@ -56,6 +56,8 @@ A human-in-the-loop (HITL) `input.requested` event renders as an Adaptive Card.
By default, submissions use the Teams identity of the user who clicked the card. If you customize `onMessage` for an allowlist, configure the same policy in `onInputResponse`; eve otherwise rejects HITL submissions rather than bypassing the message gate.
+When a tool approval settles, eve replaces its Adaptive Card with the outcome and responder name. A response rejected by an approval policy leaves the shared card unchanged.
+
For invokes that aren't HITL, handle them in `onInvoke(ctx, activity)`.
### Proactive sessions
diff --git a/packages/eve/src/public/channels/teams/api.test.ts b/packages/eve/src/public/channels/teams/api.test.ts
index d29f07d17..dcf0034a3 100644
--- a/packages/eve/src/public/channels/teams/api.test.ts
+++ b/packages/eve/src/public/channels/teams/api.test.ts
@@ -103,6 +103,28 @@ describe("Teams Connector API wrapper", () => {
expect(requests[3]!.body).toEqual({ type: "typing" });
});
+ it("reports Connector update failures with the response body and target", async () => {
+ const apiFetch = vi.fn(async () =>
+ Response.json(
+ { error: { code: "BadArgument", message: "Activity cannot be updated." } },
+ { status: 400 },
+ ),
+ );
+
+ await expect(
+ updateTeamsActivity({
+ activityId: "ACTIVITY_1",
+ body: { text: "updated", type: "message" },
+ conversationId: "CONV",
+ credentials: { tokenProvider: () => "connector-token" },
+ fetch: apiFetch,
+ serviceUrl: "https://smba.example.test/teams",
+ }),
+ ).rejects.toThrow(
+ 'Teams update activity failed with HTTP 400 for conversation "CONV" activity "ACTIVITY_1": {"error":{"code":"BadArgument","message":"Activity cannot be updated."}}',
+ );
+ });
+
it("exposes a raw Connector request helper", async () => {
const apiFetch = vi.fn(async () => Response.json({ ok: true }));
await callTeamsConnectorApi({
diff --git a/packages/eve/src/public/channels/teams/api.ts b/packages/eve/src/public/channels/teams/api.ts
index d1176f0a1..b77d6bf20 100644
--- a/packages/eve/src/public/channels/teams/api.ts
+++ b/packages/eve/src/public/channels/teams/api.ts
@@ -324,7 +324,9 @@ export async function updateTeamsActivity(
)}`,
});
if (!response.ok) {
- throw new Error(`Teams update activity failed with HTTP ${response.status}.`);
+ throw new Error(
+ `Teams update activity failed with HTTP ${response.status} for conversation "${input.conversationId}" activity "${input.activityId}": ${formatConnectorErrorBody(response.body)}`,
+ );
}
return toPostedActivity(response.body);
}
@@ -397,6 +399,12 @@ function toPostedActivity(body: unknown): TeamsPostedActivity {
};
}
+function formatConnectorErrorBody(body: unknown): string {
+ const value = typeof body === "string" ? body : JSON.stringify(body);
+ if (value === undefined || value.length === 0) return "empty response body";
+ return value.length <= 1_000 ? value : `${value.slice(0, 997)}...`;
+}
+
function trimTrailingSlash(value: string): string {
return value.replace(/\/+$/, "");
}
diff --git a/packages/eve/src/public/channels/teams/defaults.test.ts b/packages/eve/src/public/channels/teams/defaults.test.ts
index 0770855b8..9052baf16 100644
--- a/packages/eve/src/public/channels/teams/defaults.test.ts
+++ b/packages/eve/src/public/channels/teams/defaults.test.ts
@@ -12,6 +12,7 @@ function buildChannelStub(state: Partial<TeamsChannelState> = {}) {
const update = vi.fn().mockResolvedValue(undefined);
const channel = {
adaptiveCardVersion: "1.5",
+ teams: { replyToActivityId: undefined } as Partial<TeamsEventContext["teams"]>,
thread: { post, startTyping, update } as Partial<TeamsEventContext["thread"]>,
state: {
bot: null,
@@ -40,6 +41,68 @@ function authRequiredEvent(overrides: { displayName?: string } = {}) {
};
}
+describe("defaultEvents approval lifecycle", () => {
+ it("records a posted tool approval card for settlement", async () => {
+ const { channel, post } = buildChannelStub();
+
+ await defaultEvents["input.requested"]!(
+ {
+ requests: [
+ {
+ action: { callId: "call-1", input: {}, kind: "tool-call", toolName: "deploy" },
+ kind: "tool-approval",
+ options: [
+ { id: "approve", label: "Approve" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ prompt: "Approve deployment?",
+ requestId: "approval_1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ sessionCtx,
+ );
+
+ expect(post).toHaveBeenCalledTimes(1);
+ expect(channel.state.pendingApprovalCards).toEqual({
+ approval_1: { activityId: "act1", prompt: "Approve deployment?" },
+ });
+ });
+
+ it("replaces the settled approval card with the responder's identity", async () => {
+ const { channel, update } = buildChannelStub({
+ approvalResponderAccounts: { "teams:TENANT:USER": { id: "USER", name: "Ada" } },
+ pendingApprovalCards: {
+ approval_1: { activityId: "approval-card", prompt: "Approve deployment?" },
+ },
+ });
+
+ await defaultEvents["approval.settled"]!(
+ {
+ outcome: "approved",
+ requestId: "approval_1",
+ responderPrincipalId: "teams:TENANT:USER",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ channel,
+ sessionCtx,
+ );
+
+ expect(update).toHaveBeenCalledWith(
+ "approval-card",
+ expect.objectContaining({ attachments: expect.any(Array) }),
+ );
+ expect(JSON.stringify(update.mock.calls[0]?.[1])).toContain("Answered: Approved by Ada");
+ expect(channel.state.pendingApprovalCards).toEqual({});
+ });
+});
+
describe("defaultEvents authorization.required", () => {
it("renders the title-cased connection name when the challenge has no displayName", async () => {
const { channel, post } = buildChannelStub();
diff --git a/packages/eve/src/public/channels/teams/defaults.ts b/packages/eve/src/public/channels/teams/defaults.ts
index 46e6eb391..d0e9638d6 100644
--- a/packages/eve/src/public/channels/teams/defaults.ts
+++ b/packages/eve/src/public/channels/teams/defaults.ts
@@ -69,15 +69,41 @@ export const defaultEvents: TeamsChannelEvents = {
async "input.requested"(event, channel, _ctx) {
for (const request of event.requests) {
- await channel.thread.post(
+ const posted = await channel.thread.post(
renderInputRequestMessage(request, {
adaptiveCardVersion: channel.adaptiveCardVersion,
replyToActivityId: channel.teams.replyToActivityId,
}),
);
+ if (request.kind === "tool-approval" && posted.id) {
+ channel.state.pendingApprovalCards = {
+ ...channel.state.pendingApprovalCards,
+ [request.requestId]: { activityId: posted.id, prompt: request.prompt },
+ };
+ }
}
},
+ async "approval.settled"(event, channel, _ctx) {
+ const cards = channel.state.pendingApprovalCards ?? {};
+ const card = cards[event.requestId];
+ if (card === undefined) return;
+ const account = channel.state.approvalResponderAccounts?.[event.responderPrincipalId];
+ const label = event.outcome === "approved" ? "Approved" : "Cancelled";
+ const actor = account?.name ?? account?.id;
+ await channel.thread.update(
+ card.activityId,
+ renderAnsweredInputRequestMessage({
+ includeText: false,
+ label: actor === undefined ? label : `${label} by ${actor}`,
+ prompt: card.prompt,
+ }),
+ );
+ const next = { ...cards };
+ delete next[event.requestId];
+ channel.state.pendingApprovalCards = next;
+ },
+
async "message.completed"(event, channel, _ctx) {
if (event.finishReason === "tool-calls" || !event.message) return;
for (const chunk of splitTeamsMessageText(event.message)) {
diff --git a/packages/eve/src/public/channels/teams/hitl.test.ts b/packages/eve/src/public/channels/teams/hitl.test.ts
index 5144e8875..1e4f57922 100644
--- a/packages/eve/src/public/channels/teams/hitl.test.ts
+++ b/packages/eve/src/public/channels/teams/hitl.test.ts
@@ -2,11 +2,14 @@ import { describe, expect, it } from "vitest";
import {
deriveTeamsInputResponses,
+ isTeamsToolApprovalResponseActivity,
readTeamsInputReplyToActivityId,
renderInputRequestMessage,
TEAMS_HITL_CHOICE_INPUT_ID,
TEAMS_HITL_DATA_KEY,
TEAMS_HITL_FREEFORM_INPUT_ID,
+ TEAMS_HITL_PROMPT_KEY,
+ TEAMS_HITL_REQUEST_KIND_KEY,
} from "#public/channels/teams/hitl.js";
import { parseTeamsActivity } from "#public/channels/teams/inbound.js";
import type { InputRequest } from "#runtime/input/types.js";
@@ -37,7 +40,11 @@ describe("Teams HITL helpers", () => {
};
expect(card.actions?.[0]?.data).toMatchObject({
- [TEAMS_HITL_DATA_KEY]: { replyToActivityId: "ROOT" },
+ [TEAMS_HITL_DATA_KEY]: {
+ [TEAMS_HITL_PROMPT_KEY]: "Approve deploy?",
+ [TEAMS_HITL_REQUEST_KIND_KEY]: "tool-approval",
+ replyToActivityId: "ROOT",
+ },
});
});
@@ -78,6 +85,21 @@ describe("Teams HITL helpers", () => {
expect(invoke ? deriveTeamsInputResponses(invoke) : []).toEqual([
{ requestId: "REQ", text: "freeform" },
]);
+ expect(invoke ? isTeamsToolApprovalResponseActivity(invoke) : false).toBe(false);
+ });
+
+ it("identifies tool approval submissions", () => {
+ const activity = parseTeamsActivity(
+ activityWithValue({
+ [TEAMS_HITL_DATA_KEY]: {
+ [TEAMS_HITL_REQUEST_KIND_KEY]: "tool-approval",
+ optionId: "approve",
+ requestId: "REQ",
+ },
+ }),
+ );
+
+ expect(activity ? isTeamsToolApprovalResponseActivity(activity) : false).toBe(true);
});
});
diff --git a/packages/eve/src/public/channels/teams/hitl.ts b/packages/eve/src/public/channels/teams/hitl.ts
index 9da9f2594..793679fdf 100644
--- a/packages/eve/src/public/channels/teams/hitl.ts
+++ b/packages/eve/src/public/channels/teams/hitl.ts
@@ -30,6 +30,12 @@ export const TEAMS_HITL_CHOICE_INPUT_ID = "eve_option";
/** Text input id used for freeform HITL requests. */
export const TEAMS_HITL_FREEFORM_INPUT_ID = "eve_freeform_text";
+/** Request kind carried on approval actions so lifecycle handling can distinguish them from questions. */
+export const TEAMS_HITL_REQUEST_KIND_KEY = "kind";
+
+/** Prompt carried on approval actions so a response can recover its card record. */
+export const TEAMS_HITL_PROMPT_KEY = "prompt";
+
/** Renders one input request as a Teams message body containing an Adaptive Card. */
export function renderInputRequestMessage(
request: InputRequest,
@@ -92,10 +98,12 @@ export function renderInputRequestAttachment(
/** Renders an answered Teams card that replaces a pending HITL prompt. */
export function renderAnsweredInputRequestMessage(input: {
+ readonly includeText?: boolean;
readonly label?: string;
readonly prompt: string;
}): TeamsMessageBody {
- return {
+ const text = input.label ? `Answered: ${input.label}` : "Answered";
+ const result: TeamsMessageBody = {
attachments: [
{
content: parseJsonObject({
@@ -106,12 +114,7 @@ export function renderAnsweredInputRequestMessage(input: {
type: "TextBlock",
wrap: true,
},
- {
- color: "good",
- text: input.label ? `Answered: ${input.label}` : "Answered",
- type: "TextBlock",
- wrap: true,
- },
+ { color: "good", text, type: "TextBlock", wrap: true },
],
type: "AdaptiveCard",
version: "1.5",
@@ -119,8 +122,9 @@ export function renderAnsweredInputRequestMessage(input: {
contentType: TEAMS_ADAPTIVE_CARD_CONTENT_TYPE,
},
],
- text: input.label ? `Answered: ${input.label}` : "Answered",
};
+ if (input.includeText !== false) return { ...result, text };
+ return result;
}
/** Returns true when a Teams activity carries an eve HITL submit payload. */
@@ -128,6 +132,21 @@ export function isTeamsInputResponseActivity(activity: TeamsActivity): boolean {
return deriveTeamsInputResponses(activity).length > 0;
}
+/** Returns whether an eve HITL activity answers a tool approval. */
+export function isTeamsToolApprovalResponseActivity(activity: TeamsActivity): boolean {
+ const value = readActivityValue(activity);
+ const payload = value && readHitlPayload(value);
+ return payload?.[TEAMS_HITL_REQUEST_KIND_KEY] === "tool-approval";
+}
+
+/** Reads the original prompt from a tool-approval submit activity. */
+export function readTeamsToolApprovalPrompt(activity: TeamsActivity): string | undefined {
+ const value = readActivityValue(activity);
+ const payload = value && readHitlPayload(value);
+ const prompt = payload?.[TEAMS_HITL_PROMPT_KEY];
+ return typeof prompt === "string" && prompt.length > 0 ? prompt : undefined;
+}
+
/**
* Decodes the eve HITL submit payload from a Teams activity. Returns a single
* `InputResponse` (option selection, freeform text, or a bare requestId
@@ -223,6 +242,10 @@ function renderActions(
): readonly Record<string, unknown>[] {
const payload = (optionId?: string): Record<string, unknown> => {
const value: Record<string, unknown> = { requestId: request.requestId };
+ if (request.kind === "tool-approval") {
+ value[TEAMS_HITL_REQUEST_KIND_KEY] = "tool-approval";
+ value[TEAMS_HITL_PROMPT_KEY] = request.prompt;
+ }
if (replyToActivityId !== undefined) value.replyToActivityId = replyToActivityId;
if (optionId !== undefined) value.optionId = optionId;
return value;
diff --git a/packages/eve/src/public/channels/teams/index.ts b/packages/eve/src/public/channels/teams/index.ts
index 00aa05b15..89c15aa23 100644
--- a/packages/eve/src/public/channels/teams/index.ts
+++ b/packages/eve/src/public/channels/teams/index.ts
@@ -82,6 +82,8 @@ export {
export {
deriveTeamsInputResponses,
isTeamsInputResponseActivity,
+ isTeamsToolApprovalResponseActivity,
+ readTeamsToolApprovalPrompt,
renderAnsweredInputRequestMessage,
renderInputRequestAttachment,
renderInputRequestMessage,
@@ -90,6 +92,8 @@ export {
TEAMS_HITL_CHOICE_INPUT_ID,
TEAMS_HITL_DATA_KEY,
TEAMS_HITL_FREEFORM_INPUT_ID,
+ TEAMS_HITL_REQUEST_KIND_KEY,
+ TEAMS_HITL_PROMPT_KEY,
} from "#public/channels/teams/hitl.js";
export {
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
index 77e84c781..30164e97f 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
@@ -1,10 +1,53 @@
import { describe, expect, it, vi } from "vitest";
+import { callAdapterEventHandler } from "#channel/adapter.js";
+import { buildAdapterContext } from "#channel/adapter-context.js";
import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey } from "#context/keys.js";
import { isHttpRouteDefinition } from "#channel/routes.js";
-import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";
+import {
+ mockChannelContext,
+ type ObservedChannelDelivery,
+} from "#internal/testing/mocks/mock-channel-operations.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { teamsChannel, type TeamsChannelState } from "#public/channels/teams/index.js";
+function adapter(channel: unknown) {
+ return asCompiled<TeamsChannelState>(channel).adapter;
+}
+
+function makeEvent<T extends UnstampedMessageStreamEvent["type"]>(
+ type: T,
+ data: unknown,
+): UnstampedMessageStreamEvent {
+ return { type, data } as UnstampedMessageStreamEvent;
+}
+
+function stubAccessor() {
+ return { get: () => undefined, set: () => {} } as any;
+}
+
+const stubAlsContext = (() => {
+ const ctx = new ContextContainer();
+ ctx.setVirtualContext(SessionKey, {
+ sessionId: "test-session",
+ auth: { current: null, initiator: null },
+ turn: { id: "test-turn", sequence: 0 },
+ });
+ return ctx;
+})();
+
+function callEvent(
+ teamsAdapter: ReturnType<typeof adapter>,
+ event: UnstampedMessageStreamEvent,
+ ctx: ReturnType<typeof buildAdapterContext>,
+) {
+ return contextStorage.run(stubAlsContext, () =>
+ callAdapterEventHandler(teamsAdapter, event, ctx),
+ );
+}
+
function asCompiled<T = unknown>(channel: unknown): CompiledChannel<T> {
if (!isCompiledChannel(channel)) {
throw new Error("Expected compiled channel.");
@@ -191,7 +234,7 @@ describe("teamsChannel", () => {
expect(send).not.toHaveBeenCalled();
});
- it("resumes invoke HITL responses with the clicker's auth and recorded thread", async () => {
+ it("resumes tool approvals with the clicker's auth and durable Teams identity", async () => {
const channel = teamsChannel({ credentials: { webhookVerifier: () => true } });
const { response, send } = await firePost(channel, {
...baseActivity({ conversationType: "channel" }),
@@ -203,6 +246,7 @@ describe("teamsChannel", () => {
data: {
eve_input: {
replyToActivityId: "THREAD_ROOT",
+ kind: "tool-approval",
requestId: "REQ",
optionId: "approve",
},
@@ -217,8 +261,130 @@ describe("teamsChannel", () => {
expect.objectContaining({
auth: expect.objectContaining({ subject: "AAD_USER" }),
inputResponses: [{ optionId: "approve", requestId: "REQ" }],
+ state: {
+ approvalResponderAccounts: {
+ "teams:TENANT:USER": expect.objectContaining({ id: "USER", name: "Ada" }),
+ },
+ },
+ }),
+ );
+ });
+
+ it("updates a posted approval card after a durable cancel settlement", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(new Response(null, { status: 200 }))
+ .mockResolvedValue(new Response(JSON.stringify({ id: "updated-card" })));
+ const channel = teamsChannel({
+ api: { fetch: fetchMock },
+ credentials: { tokenProvider: () => "test-token", webhookVerifier: () => true },
+ });
+ const teamsAdapter = adapter(channel);
+ const ctx = buildAdapterContext(teamsAdapter, stubAccessor());
+
+ ctx.state.bot = { id: "BOT" };
+ ctx.state.conversationId = "19:[email protected];messageid=THREAD_ROOT";
+ ctx.state.conversationType = "channel";
+ ctx.state.replyToActivityId = "THREAD_ROOT";
+ ctx.state.serviceUrl = "https://smba.example.test/teams";
+ ctx.state.tenantId = "TENANT";
+
+ await callEvent(
+ teamsAdapter,
+ makeEvent("input.requested", {
+ requests: [
+ {
+ action: { callId: "call-1", input: {}, kind: "tool-call", toolName: "deploy" },
+ kind: "tool-approval",
+ options: [
+ { id: "approve", label: "Approve" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ prompt: "Approve deployment?",
+ requestId: "approval_1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ expect(ctx.state.pendingApprovalCards).toEqual({});
+
+ const { send } = await firePost(channel, {
+ ...baseActivity({ conversationType: "channel" }),
+ conversation: {
+ conversationType: "channel",
+ id: "19:[email protected];messageid=THREAD_ROOT",
+ },
+ from: { id: "USER", name: "Ada" },
+ replyToId: "approval-card",
+ name: "adaptiveCard/action",
+ type: "invoke",
+ value: {
+ action: {
+ data: {
+ eve_input: {
+ kind: "tool-approval",
+ prompt: "Approve deployment?",
+ optionId: "cancel",
+ replyToActivityId: "THREAD_ROOT",
+ requestId: "approval_1",
+ },
+ },
+ },
+ },
+ });
+ const delivery = send.mock.calls[0]?.[1] as Extract<
+ ObservedChannelDelivery<TeamsChannelState>,
+ { readonly inputResponses: readonly unknown[] }
+ >;
+ await teamsAdapter.deliver!(
+ { inputResponses: delivery.inputResponses, state: delivery.state },
+ ctx,
+ );
+ expect(ctx.state.pendingApprovalCards).toEqual({
+ approval_1: { activityId: "approval-card", prompt: "Approve deployment?" },
+ });
+
+ await callEvent(
+ teamsAdapter,
+ makeEvent("approval.settled", {
+ outcome: "cancelled",
+ requestId: "approval_1",
+ responderPrincipalId: "teams:TENANT:USER",
+ sequence: 1,
+ stepIndex: 1,
+ turnId: "turn-1",
}),
+ ctx,
);
+
+ const updateCall = fetchMock.mock.calls.find(
+ ([url, init]) =>
+ String(url).endsWith(
+ "/v3/conversations/19%3Aconversation%40thread.tacv2/activities/approval-card",
+ ) && (init as RequestInit).method === "PUT",
+ );
+ expect(updateCall).toBeDefined();
+ const updateBody = JSON.parse(String((updateCall?.[1] as RequestInit).body)) as {
+ channelData?: unknown;
+ conversation?: unknown;
+ from?: unknown;
+ recipient?: unknown;
+ replyToId?: string;
+ text?: string;
+ type?: string;
+ };
+ expect(updateBody).toMatchObject({ type: "message" });
+ expect(updateBody.channelData).toBeUndefined();
+ expect(updateBody.conversation).toBeUndefined();
+ expect(updateBody.from).toBeUndefined();
+ expect(updateBody.recipient).toBeUndefined();
+ expect(updateBody.replyToId).toBeUndefined();
+ expect(updateBody.text).toBeUndefined();
});
it("handles unmentioned message-form HITL responses before the mention gate", async () => {
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.ts
index d970f8ee0..9b1c7d070 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts
@@ -1,3 +1,4 @@
+import { defaultDeliverResult } from "#channel/adapter.js";
import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import type { SessionHandle } from "#channel/session.js";
@@ -42,7 +43,9 @@ import {
import {
deriveTeamsInputResponses,
isTeamsInputResponseActivity,
+ isTeamsToolApprovalResponseActivity,
readTeamsInputReplyToActivityId,
+ readTeamsToolApprovalPrompt,
teamsInvokeResponse,
} from "#public/channels/teams/hitl.js";
import {
@@ -86,6 +89,11 @@ export interface TeamsChannelContext extends TeamsContext {
export interface TeamsEventContext extends TeamsChannelContext, ChannelContinuationOps {}
/** JSON-serializable Teams channel state. */
+export interface TeamsPendingApprovalCard {
+ readonly activityId: string;
+ readonly prompt: string;
+}
+
export interface TeamsChannelState {
/** Bot account captured from the inbound activity recipient. */
bot: TeamsChannelAccount | null;
@@ -102,6 +110,8 @@ export interface TeamsChannelState {
triggeringUser: TeamsChannelAccount | null;
/** Activity id for the default connection-auth card, when posted. */
pendingAuthActivityId?: string | null;
+ pendingApprovalCards?: Record<string, TeamsPendingApprovalCard>;
+ approvalResponderAccounts?: Record<string, TeamsChannelAccount>;
}
/** Teams channel credentials. */
@@ -166,6 +176,8 @@ type TeamsSessionFailedHandler = (
/** Event handlers supported by `teamsChannel({ events })`. */
export interface TeamsChannelEvents {
+ readonly "approval.candidate"?: TeamsEventHandler<"approval.candidate">;
+ readonly "approval.settled"?: TeamsEventHandler<"approval.settled">;
readonly "turn.started"?: TeamsEventHandler<"turn.started">;
readonly "actions.requested"?: TeamsEventHandler<"actions.requested">;
readonly "action.partial"?: TeamsEventHandler<"action.partial">;
@@ -300,6 +312,25 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {
return rebuildTeamsContext(state, session, config);
},
+ deliver(payload, channel) {
+ const state = payload.state as Partial<TeamsChannelState> | undefined;
+ const cards = state?.pendingApprovalCards;
+ if (cards !== undefined) {
+ channel.state.pendingApprovalCards = {
+ ...cards,
+ ...channel.state.pendingApprovalCards,
+ };
+ }
+ const responders = state?.approvalResponderAccounts;
+ if (responders !== undefined) {
+ channel.state.approvalResponderAccounts = {
+ ...channel.state.approvalResponderAccounts,
+ ...responders,
+ };
+ }
+ return defaultDeliverResult(payload);
+ },
+
routes: [
POST<TeamsChannelState>(
config.route ?? "/eve/v1/teams",
@@ -535,10 +566,12 @@ function buildTeamsHandle(input: {
const address = requireAddress();
return updateTeamsActivity({
...api,
- body: buildOutboundActivity(state, activity),
+ body: buildUpdateActivity(state, activity),
credentials,
activityId,
- conversationId: address.conversationId,
+ conversationId: normalizeTeamsContinuationAddress({
+ conversationId: address.conversationId,
+ }).conversationId,
serviceUrl: address.serviceUrl,
});
},
@@ -669,6 +702,7 @@ async function dispatchInputResponses(input: {
try {
await input.from(resolveInputContinuationToken(input.activity, state)).respond(inputResponses, {
auth: result.auth,
+ state: approvalResponseStatePatch(input.activity, result.auth),
});
} catch (error) {
log.error("Teams input response delivery failed", { error });
@@ -709,6 +743,29 @@ function resolveInputContinuationToken(
});
}
+function approvalResponseStatePatch(
+ activity: TeamsInvokeActivity | TeamsMessageActivity,
+ auth: SessionAuthContext | null,
+): Partial<TeamsChannelState> | undefined {
+ if (auth?.principalId === undefined || !isTeamsToolApprovalResponseActivity(activity)) {
+ return undefined;
+ }
+ const requestId = deriveTeamsInputResponses(activity)[0]?.requestId;
+ const activityId = activity.replyToId;
+ if (requestId === undefined || activityId === undefined) {
+ return { approvalResponderAccounts: { [auth.principalId]: activity.from } };
+ }
+ return {
+ approvalResponderAccounts: { [auth.principalId]: activity.from },
+ pendingApprovalCards: {
+ [requestId]: {
+ activityId,
+ prompt: readTeamsToolApprovalPrompt(activity) ?? "Tool approval",
+ },
+ },
+ };
+}
+
function defaultOnInputResponse(
_ctx: TeamsContext,
activity: TeamsInvokeActivity | TeamsMessageActivity,
@@ -726,6 +783,8 @@ function initialTeamsState(): TeamsChannelState {
channelId: null,
conversationId: null,
conversationType: null,
+ approvalResponderAccounts: {},
+ pendingApprovalCards: {},
pendingAuthActivityId: null,
replyToActivityId: null,
serviceUrl: null,
@@ -765,6 +824,26 @@ function buildOutboundActivity(
};
}
+function buildUpdateActivity(
+ _state: TeamsChannelState,
+ message: TeamsMessageBody | TeamsOutboundActivity | string,
+): TeamsOutboundActivity {
+ if (typeof message !== "string" && "type" in message && message.type === "typing") {
+ throw new Error("teamsChannel: cannot replace an activity with a typing indicator.");
+ }
+ const body = normalizeTeamsPostInput(message);
+ const {
+ channelData: _channelData,
+ conversation: _conversation,
+ from: _from,
+ recipient: _recipient,
+ replyToId: _replyToId,
+ type: _type,
+ ...content
+ } = body as TeamsOutboundActivity;
+ return { ...content, type: "message" };
+}
+
function mergeChannelData(
state: TeamsChannelState,
channelData: JsonObject | undefined,