The Open Framework for Building Agents
feat(channels): send and receive iMessage tapbacks on Photon and Linq (#5055)
Ben Pankowcf824a88505d
diff --git a/.changeset/imessage-tapbacks.md b/.changeset/imessage-tapbacks.mdnew file mode 100644index 000000000..caa631a28--- /dev/null+++ b/.changeset/imessage-tapbacks.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The Photon and Linq channels can now pass tapbacks to the agent with a new `onTapback` hook, which can also answer the approval or question posted in the message the tapback is on, for example approving with a like. `channel.tapbackTool()` gives the model a tool that reacts to the latest message with a standard tapback or any emoji. Tapbacks stay ignored unless you opt in.diff --git a/docs/channels/linq.mdx b/docs/channels/linq.mdxindex 112e9a596..fbbfb3cf7 100644--- a/docs/channels/linq.mdx+++ b/docs/channels/linq.mdx@@ -39,6 +39,57 @@ export default linqChannel({Set `route` to override the webhook path or `webhookVerifier` to use a different trusted-forwarder verifier.+## Tapbacks++eve ignores tapbacks people send unless you pass `onTapback`. It receives the tapback and returns the same result as `onMessage`, or `null` to ignore it:++```ts title="agent/channels/linq.ts"+import { connectLinqCredentials } from "@vercel/connect/eve";+import { defaultLinqAuth, linqChannel } from "eve/channels/linq";++export default linqChannel({+ credentials: connectLinqCredentials("linq/my-agent"),+ onTapback(_ctx, tapback) {+ if (!tapback.added) return null;+ return { auth: defaultLinqAuth(tapback) };+ },+});+```++The agent reads an accepted tapback as a message in the form iMessage uses when it shows a tapback as text, such as `Tapback: Loved “See you at 7”` or `Tapback: Removed a like tapback from a message`. The quoted text appears when Linq can return the message the tapback is on. `tapback.tapback` is `love`, `like`, `dislike`, `laugh`, `emphasize`, or `question`, or the emoji itself for an emoji tapback. `tapback.messageId` and `tapback.author` identify the message and the person. An accepted tapback starts or steers a turn like any other message, following `turnPolicy`. The agent's own tapbacks never reach `onTapback`. `onTapback` runs instead of `onMessage` for tapbacks, so repeat any sender checks from `onMessage` there. Tapbacks arrive through the `reaction.added` and `reaction.removed` webhook events, which `eve add channel/linq` subscribes to.++To let the agent send tapbacks, export the channel's tapback tool from a file in `agent/tools/`. The file name becomes the tool name:++```ts title="agent/tools/tapback.ts"+import linq from "../channels/linq";++export default linq.tapbackTool();+```++The model calls it with a standard tapback, such as `{ "tapback": "love" }`, or any single emoji, such as `{ "tapback": "🎉" }`, and eve reacts to the latest message someone sent in the conversation. A standard tapback's own emoji, such as `👍`, sends that tapback. The model can send a tapback alongside a reply. To let a tapback be the whole answer, also add [`no_reply`](../concepts/built-in-tools#no_reply). The tool is never added on its own, and subagents don't receive it. In a session that didn't come through this channel, such as a web chat, or before anyone has sent a message, the call fails with an error the model reads.++### Answer approvals with a tapback++Return `answer` from `onTapback` to answer the input request eve posted in the message the tapback is on. A [tool approval](/docs/human-in-the-loop#approvals) offers the options `approve` and `cancel`, so a like or dislike on the approval prompt can approve or cancel it:++```ts title="agent/channels/linq.ts"+import { connectLinqCredentials } from "@vercel/connect/eve";+import { defaultLinqAuth, linqChannel } from "eve/channels/linq";++export default linqChannel({+ credentials: connectLinqCredentials("linq/my-agent"),+ onTapback(_ctx, tapback) {+ if (!tapback.added) return null;+ const auth = defaultLinqAuth(tapback);+ if (tapback.tapback === "like") return { auth, answer: "approve" };+ if (tapback.tapback === "dislike") return { auth, answer: "cancel" };+ return { auth };+ },+});+```++`answer` settles only the request posted in that message, and only while it is still waiting and offers that option. A tapback on any other message, or on a prompt that was already answered, reaches the agent as an ordinary tapback, such as `Tapback: Liked “Got it”`. The approval's response policy still decides whether the person who sent the tapback may answer. For a [question](/docs/human-in-the-loop#questions), return one of its option ids. To replace the text the agent receives for a tapback, return `message`. Don't set `message` to an option's id, label, or number: eve reads that text like a typed reply, which answers the first waiting approval no matter which message the tapback is on.+## Other hostsFor a host without Vercel Connect, choose **Use portable credentials** during `eve add channel/linq`. eve writes `LINQ_API_KEY` and `LINQ_WEBHOOK_SECRET` to `.env.local`.diff --git a/docs/channels/photon.mdx b/docs/channels/photon.mdxindex 76023b784..f3e363fb1 100644--- a/docs/channels/photon.mdx+++ b/docs/channels/photon.mdx@@ -61,6 +61,66 @@ export default photonIMessageChannel({Set `route` to override the webhook path or `webhookVerifier` to use a differenttrusted-forwarder verifier.+## Tapbacks++eve ignores tapbacks people send unless you pass `onTapback`. It receives the+tapback and returns the same result as `onMessage`, or `null` to ignore it:++```ts title="agent/channels/photon.ts"+import { connectPhotonCredentials } from "@vercel/connect/eve";+import { defaultPhotonAuth, photonIMessageChannel } from "eve/channels/photon";++export default photonIMessageChannel({+ credentials: connectPhotonCredentials("photon/my-agent"),+ onTapback(_ctx, tapback) {+ if (!tapback.added) return null;+ return { auth: defaultPhotonAuth(tapback) };+ },+});+```++The agent reads an accepted tapback as a message in the form iMessage uses when+it shows a tapback as text, such as `Tapback: Loved “See you at 7”`. Photon+reports only added tapbacks, so `tapback.added` is always `true` and removing a+tapback never reaches `onTapback`. The quoted text appears when Photon can return the message the tapback is on. `tapback.tapback` is `love`,+`like`, `dislike`, `laugh`, `emphasize`, or `question`, or the emoji itself for+an emoji tapback. `tapback.messageId` and `tapback.author` identify the message+and the person. An accepted tapback starts or steers a turn like any other+message, following `turnPolicy`. The agent's own tapbacks never reach `onTapback`. `onTapback` runs instead of `onMessage` for tapbacks, so repeat any sender checks from `onMessage` there.++To let the agent send tapbacks, export the channel's tapback tool from a file in+`agent/tools/`. The file name becomes the tool name:++```ts title="agent/tools/tapback.ts"+import photon from "../channels/photon";++export default photon.tapbackTool();+```++The model calls it with a standard tapback, such as `{ "tapback": "love" }`, or any single emoji, such as `{ "tapback": "🎉" }`, and eve reacts to the latest message someone sent in the conversation. A standard tapback's own emoji, such as `👍`, sends that tapback. The model can send a tapback alongside a reply. To let a tapback be the whole answer, also add [`no_reply`](../concepts/built-in-tools#no_reply). The tool is never added on its own, and subagents don't receive it. In a session that didn't come through this channel, such as a web chat, or before anyone has sent a message, the call fails with an error the model reads.++### Answer approvals with a tapback++Return `answer` from `onTapback` to answer the input request eve posted in the message the tapback is on. A [tool approval](/docs/human-in-the-loop#approvals) offers the options `approve` and `cancel`, so a like or dislike on the approval prompt can approve or cancel it:++```ts title="agent/channels/photon.ts"+import { connectPhotonCredentials } from "@vercel/connect/eve";+import { defaultPhotonAuth, photonIMessageChannel } from "eve/channels/photon";++export default photonIMessageChannel({+ credentials: connectPhotonCredentials("photon/my-agent"),+ onTapback(_ctx, tapback) {+ if (!tapback.added) return null;+ const auth = defaultPhotonAuth(tapback);+ if (tapback.tapback === "like") return { auth, answer: "approve" };+ if (tapback.tapback === "dislike") return { auth, answer: "cancel" };+ return { auth };+ },+});+```++`answer` settles only the request posted in that message, and only while it is still waiting and offers that option. A tapback on any other message, or on a prompt that was already answered, reaches the agent as an ordinary tapback, such as `Tapback: Liked “Got it”`. The approval's response policy still decides whether the person who sent the tapback may answer. For a [question](/docs/human-in-the-loop#questions), return one of its option ids. To replace the text the agent receives for a tapback, return `message`. Don't set `message` to an option's id, label, or number: eve reads that text like a typed reply, which answers the first waiting approval no matter which message the tapback is on.+## Other hostsFor a host without Vercel Connect, choose **Use portable credentials** duringdiff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex e0298a601..290f23b3f 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -171,6 +171,87 @@ describe("chatSdkChannel", () => {]);});+ it("records each delivery's message as the thread's latest, skipping the bot's own", () => {+ const bridge = chatSdkChannel({+ adapters: { test: testAdapter() },+ state: memoryState(),+ userName: "bot",+ });+ const adapter = getAdapter(bridge.channel);+ const state: ChatSdkChannelState = { thread: null };+ const deliver = (id: string, isMe: boolean) =>+ adapter.deliver?.(+ {+ message: "hello",+ state: {+ thread: {+ _type: "chat:Thread",+ adapterName: "test",+ channelId: CHANNEL_ID,+ currentMessage: { author: { isBot: isMe, isMe, userId: id }, id },+ id: THREAD_ID,+ isDM: true,+ },+ },+ } as never,+ { session: { auth: { current: null } }, state } as never,+ );++ deliver("first", false);+ deliver("second", false);+ deliver("bot-post", true);++ expect(state.latestMessageId).toBe("second");+ });++ it("answers only the waiting request on the card a delivery's inputAnswer names", () => {+ const bridge = chatSdkChannel({+ adapters: { test: testAdapter() },+ state: memoryState(),+ userName: "bot",+ });+ const adapter = getAdapter(bridge.channel);+ const approval = {+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve Deploy?",+ };+ const state: ChatSdkChannelState = {+ pendingInputCards: {+ "answered-card": {+ requests: [{ ...approval, requestId: "answered" }],+ resolved: { answered: { outcome: "answered", requestId: "answered" } },+ },+ "deploy-card": { requests: [{ ...approval, requestId: "deploy" }], resolved: {} },+ },+ thread: null,+ } as never;+ const deliver = (messageId: string, optionId: string) =>+ adapter.deliver?.(+ {+ context: [],+ message: "Tapback: Liked a message",+ state: { inputAnswer: { messageId, optionId } },+ } as never,+ { session: { auth: { current: null } }, state } as never,+ );++ expect(deliver("deploy-card", "approve")).toEqual({+ context: [],+ inputResponses: [{ optionId: "approve", requestId: "deploy" }],+ });+ expect(deliver("other-message", "approve")).toMatchObject({+ message: "Tapback: Liked a message",+ });+ expect(deliver("answered-card", "approve")).toMatchObject({+ message: "Tapback: Liked a message",+ });+ expect(deliver("deploy-card", "maybe")).toMatchObject({ message: "Tapback: Liked a message" });+ });+it("routes GET verification challenges to the adapter webhook", async () => {const bridge = chatSdkChannel({adapters: { test: testAdapter() },@@ -1020,6 +1101,66 @@ describe("chatSdkChannel", () => {});});+ it("tracks posted input cards without edit support, so an answer can name its card", async () => {+ const adapter = testAdapter();+ adapter.editError = new NotImplementedError("editMessage");+ const bridge = chatSdkChannel({+ adapters: { test: adapter },+ concurrency: "concurrent",+ state: memoryState(),+ logger: "warn",+ userName: "bot",+ });+ const state: ChatSdkChannelState = { thread: serializedThread() };+ const channelAdapter = withState(getAdapter(bridge.channel), state);+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());+ const request = (requestId: string) => ({+ action: { callId: `call-${requestId}`, name: "deploy", type: "tool-call" as const },+ display: "confirmation" as const,+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Deploy?",+ requestId,+ });++ await callEvent(+ channelAdapter,+ makeEvent("input.requested", {+ requests: [request("request-1")],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn-1",+ }),+ ctx,+ );+ await callEvent(+ channelAdapter,+ makeEvent("input.resolved", {+ resolutions: [{ optionId: "approve", requestId: "request-1" }],+ sequence: 2,+ stepIndex: 0,+ turnId: "turn-1",+ }),+ ctx,+ );+ expect(state.editSupported).toBe(false);+ expect(state.pendingInputCards).toEqual({});++ await callEvent(+ channelAdapter,+ makeEvent("input.requested", {+ requests: [request("request-2")],+ sequence: 3,+ stepIndex: 0,+ turnId: "turn-1",+ }),+ ctx,+ );+ expect(Object.keys(state.pendingInputCards ?? {})).toEqual(["posted-2"]);+ });+it("asks for a typed reply when an input request accepts a freeform answer", async () => {const adapter = testAdapter();const bridge = chatSdkChannel({diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex 5684f3005..a634c0623 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -98,6 +98,8 @@ export interface ChatSdkChannelState extends Record<string, unknown>, PromptQueuusersByPrincipal?: Record<string, string | null>;/** Posted input request cards, keyed by message id, until eve resolves every request on them. */pendingInputCards?: Record<string, ChatSdkPendingInputCard>;+ /** Id of the latest message someone other than the bot sent in the thread. */+ latestMessageId?: string;streamStepIndex?: number | null;}@@ -171,6 +173,12 @@ interface ChatSdkThreadOptions {* determines the eve continuation token and persisted channel state.*/export interface ChatSdkSendOptions extends ChatSdkThreadOptions, Omit<ChannelSendOptions, "auth"> {+ /**+ * Answers the input request on the card eve posted as `messageId` with+ * `optionId`, when that card is still waiting on it. Otherwise eve delivers+ * the message as usual.+ */+ readonly inputAnswer?: ChatSdkInputAnswer;/*** Controls how this input interacts with an active eve turn on the same* thread. Defaults to the channel's `turnPolicy`, then `"steer"`.@@ -178,6 +186,12 @@ export interface ChatSdkSendOptions extends ChatSdkThreadOptions, Omit<ChannelSereadonly turnPolicy?: TurnPolicy;}+/** An option chosen for the input request card posted as `messageId`. */+export interface ChatSdkInputAnswer {+ readonly messageId: string;+ readonly optionId: string;+}+/** Options for `bridge.respond`: channel respond options plus the thread. */export interface ChatSdkRespondOptionsextends ChatSdkThreadOptions, Omit<ChannelRespondOptions, "auth" | "state"> {}@@ -383,6 +397,11 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(channel: ChatSdkChannelContext<TAdapters> & { readonly session: SessionHandle },) {recordPrincipalUser(channel.state, channel.session.auth.current, payload);+ recordLatestMessage(channel.state, payload);+ const answer = resolveInputAnswer(channel.state, payload);+ if (answer !== undefined) {+ return { context: payload.context, inputResponses: parseInputResponses([answer]) };+ }return defaultDeliverResult(payload);},events: mergedEvents,@@ -410,7 +429,8 @@ function defaultEvents<TAdapters extends ChatSdkAdapters>(async function showPrompt(channel: EventChannel, request: InputRequest) {if (!channel.thread) return false;const posted = await channel.thread.post(renderInputRequests([request], inputActionPrefix));- if (!posted.id || channel.state.editSupported === false) return;+ if (!posted.id) return;+ // Tracked even without edit support, so an answer can name the card it is on.channel.state.pendingInputCards = {...channel.state.pendingInputCards,[posted.id]: { requests: [request], resolved: {} },@@ -438,6 +458,7 @@ function defaultEvents<TAdapters extends ChatSdkAdapters>()? rest: { ...rest, [messageId]: { requests: card.requests, resolved } };+ if (channel.state.editSupported === false) continue;try {await thread.adapter.editMessage(thread.id,@@ -450,8 +471,6 @@ function defaultEvents<TAdapters extends ChatSdkAdapters>(continue;}channel.state.editSupported = false;- channel.state.pendingInputCards = {};- return;}}}@@ -676,12 +695,14 @@ async function bridgeSend<TAdapters extends ChatSdkAdapters>(options: ChatSdkSendOptions,): Promise<Session> {const from = activeFrom("send");- const { adapterName, auth, thread: threadInput, ...sendOptions } = options;+ const { adapterName, auth, inputAnswer, thread: threadInput, ...sendOptions } = options;const thread = serializeThread(bot, threadInput, adapterName);+ const state: ChatSdkDeliveryState = { thread };+ if (inputAnswer !== undefined) state.inputAnswer = inputAnswer;return from(thread.id).send(message, {...sendOptions,auth: auth ?? null,- state: { thread },+ state,});}@@ -721,6 +742,44 @@ function recordPrincipalUser(};}+/**+ * Records the delivery's message as the thread's latest. Session state keeps+ * the thread from the first delivery, so its `currentMessage` goes stale.+ */+function recordLatestMessage(state: ChatSdkChannelState, payload: DeliverPayload): void {+ const message = (payload.state as Partial<ChatSdkChannelState> | undefined)?.thread+ ?.currentMessage;+ if (message === undefined || message.author.isMe) return;+ state.latestMessageId = message.id;+}++/** Channel state a delivery carries. `inputAnswer` lives only on the delivery. */+interface ChatSdkDeliveryState extends ChatSdkChannelState {+ inputAnswer?: ChatSdkInputAnswer;+}++/**+ * The response for a delivery's `inputAnswer`, when its card still waits on a+ * request that offers the option. Matching the card keeps an answer meant for+ * one prompt from settling a different request.+ */+function resolveInputAnswer(+ state: ChatSdkChannelState,+ payload: DeliverPayload,+): InputResponse | undefined {+ const answer = (payload.state as Partial<ChatSdkDeliveryState> | undefined)?.inputAnswer;+ if (answer === undefined) return undefined;+ const card = state.pendingInputCards?.[answer.messageId];+ const request = card?.requests.find(+ (candidate) =>+ card.resolved[candidate.requestId] === undefined &&+ candidate.options?.some((option) => option.id === answer.optionId) === true,+ );+ return request === undefined+ ? undefined+ : { optionId: answer.optionId, requestId: request.requestId };+}+function activeFrom(operation: "respond" | "send"): ChannelFrom<ChatSdkChannelState> {const active = contextStorage.getStore()?.get(ActiveWebhookKey);if (!active) {diff --git a/packages/eve/src/public/channels/chat-sdk/index.ts b/packages/eve/src/public/channels/chat-sdk/index.tsindex 4895e2102..398f80553 100644--- a/packages/eve/src/public/channels/chat-sdk/index.ts+++ b/packages/eve/src/public/channels/chat-sdk/index.ts@@ -7,6 +7,7 @@ export {type ChatSdkChannelEvents,type ChatSdkChannelState,type ChatSdkEventContext,+ type ChatSdkInputAnswer,type ChatSdkInstrumentationMetadata,type ChatSdkReceiveTarget,type ChatSdkRespondOptions,diff --git a/packages/eve/src/public/channels/imessage-tapbacks.test.ts b/packages/eve/src/public/channels/imessage-tapbacks.test.tsnew file mode 100644index 000000000..ac6da5de4--- /dev/null+++ b/packages/eve/src/public/channels/imessage-tapbacks.test.ts@@ -0,0 +1,210 @@+import { describe, expect, it, vi } from "vitest";++import { ContextContainer, contextStorage } from "#context/container.js";+import { getEmoji, Message, type ReactionEvent } from "#compiled/chat/index.js";+import {+ dispatchIMessageTapbacks,+ iMessageTapbackText,+ iMessageTapbackTool,+ toIMessageTapback,+} from "#public/channels/imessage-tapbacks.js";+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";++const author = { fullName: "Alice", isBot: false, isMe: false, userId: "alice", userName: "alice" };++function message(text: string): Message {+ return new Message({+ attachments: [],+ author,+ formatted: { type: "root", children: [] },+ id: "message-id",+ metadata: { dateSent: new Date(0), edited: false },+ raw: {},+ text,+ threadId: "thread-id",+ });+}++function reaction(overrides: Partial<ReactionEvent> = {}): ReactionEvent {+ return {+ adapter: {} as ReactionEvent["adapter"],+ added: true,+ emoji: getEmoji("heart"),+ messageId: "message-id",+ raw: {},+ rawEmoji: "❤️",+ thread: { toJSON: () => ({ id: "thread-id" }) } as never,+ threadId: "thread-id",+ user: author,+ ...overrides,+ };+}++describe("iMessage tapbacks", () => {+ it("names standard tapbacks the same way for every provider", () => {+ expect(+ toIMessageTapback(reaction({ emoji: getEmoji("thumbs_up"), rawEmoji: "like" })).tapback,+ ).toBe("like");+ expect(+ toIMessageTapback(reaction({ emoji: getEmoji("exclamation"), rawEmoji: "‼️" })).tapback,+ ).toBe("emphasize");+ expect(toIMessageTapback(reaction({ emoji: getEmoji("🎉"), rawEmoji: "🎉" })).tapback).toBe(+ "🎉",+ );+ });++ it("shows tapbacks to the model the way iMessage writes them as text", () => {+ const base = toIMessageTapback(reaction({ message: message("See you at 7") }));++ expect(iMessageTapbackText(base)).toBe("Tapback: Loved “See you at 7”");+ expect(iMessageTapbackText({ ...base, added: false })).toBe(+ "Tapback: Removed a love tapback from “See you at 7”",+ );+ expect(iMessageTapbackText({ ...base, message: undefined, tapback: "🎉" })).toBe(+ "Tapback: Reacted 🎉 to a message",+ );+ });++ it("sends accepted tapbacks and skips the agent's own and declined ones", async () => {+ const onReaction = vi.fn();+ const send = vi.fn();+ const bridge = { bot: { onReaction }, send } as never;+ const onTapback = vi.fn((_ctx, tapback: { tapback: string }) =>+ tapback.tapback === "love" ? { auth: null, context: ["ctx"] } : null,+ );+ dispatchIMessageTapbacks(bridge, onTapback);+ const handler = onReaction.mock.calls[0]?.[0] as (event: ReactionEvent) => Promise<void>;++ await handler(reaction({ user: { ...author, isMe: true } }));+ await handler(reaction({ emoji: getEmoji("thumbs_up"), rawEmoji: "like" }));+ await handler(reaction());++ expect(onTapback).toHaveBeenCalledTimes(2);+ expect(send).toHaveBeenCalledTimes(1);+ expect(send).toHaveBeenCalledWith("Tapback: Loved a message", {+ auth: null,+ context: ["ctx"],+ thread: { id: "thread-id" },+ title: undefined,+ });+ });++ it("fetches the reacted message when the event leaves it out, and passes the hook's answer for that message", async () => {+ const onReaction = vi.fn();+ const send = vi.fn();+ dispatchIMessageTapbacks({ bot: { onReaction }, send } as never, (_ctx, tapback) =>+ tapback.tapback === "like" && tapback.message?.text === "See you at 7"+ ? { answer: "approve", auth: null }+ : null,+ );+ const handler = onReaction.mock.calls[0]?.[0] as (event: ReactionEvent) => Promise<void>;+ const fetchMessage = vi.fn(async () => message("See you at 7"));++ await handler(+ reaction({+ adapter: { fetchMessage } as never,+ emoji: getEmoji("thumbs_up"),+ rawEmoji: "like",+ }),+ );++ expect(fetchMessage).toHaveBeenCalledWith("thread-id", "message-id");+ expect(send).toHaveBeenCalledWith(+ "Tapback: Liked “See you at 7”",+ expect.objectContaining({+ auth: null,+ inputAnswer: { messageId: "message-id", optionId: "approve" },+ }),+ );+ });++ describe("tapback tool", () => {+ const channel = { __kind: "eve:channel", adapter: { kind: "channel:photon" }, routes: [] };++ function setup(state: Record<string, unknown>, kind = "channel:photon") {+ const addReaction = vi.fn();+ const sendEmoji = vi.fn();+ const bot = { getAdapter: vi.fn(() => ({ addReaction })), initialize: vi.fn() };+ const tool = iMessageTapbackTool({+ adapterName: "imessage",+ bot: bot as never,+ channel: channel as never,+ channelLabel: "Photon iMessage",+ sendEmoji,+ });+ const ctx = new ContextContainer();+ ctx.set(ChannelKey, { kind, state } as never);+ const run = (tapback: string) =>+ contextStorage.run(ctx, async () => tool.execute({ tapback } as never, {} as never));+ return { addReaction, bot, run, sendEmoji };+ }++ const conversation = { latestMessageId: "latest-id", thread: { id: "imessage:chat" } };++ it("reacts to the latest message in the session's conversation", async () => {+ const { addReaction, bot, run } = setup({+ latestMessageId: "latest-id",+ thread: { id: "imessage:chat" },+ });++ await expect(run("love")).resolves.toBe("Sent a love tapback.");+ expect(bot.getAdapter).toHaveBeenCalledWith("imessage");+ expect(addReaction).toHaveBeenCalledWith("imessage:chat", "latest-id", "love");+ });++ it("sends a standard tapback's own emoji as that tapback", async () => {+ const { addReaction, run, sendEmoji } = setup(conversation);++ await expect(run("👍")).resolves.toBe("Sent a like tapback.");+ expect(addReaction).toHaveBeenCalledWith("imessage:chat", "latest-id", "like");+ expect(sendEmoji).not.toHaveBeenCalled();+ });++ it("sends any other single emoji as an emoji tapback", async () => {+ const { addReaction, run, sendEmoji } = setup(conversation);++ await expect(run("🎉")).resolves.toBe("Sent a 🎉 tapback.");+ await run("👩💻");+ expect(sendEmoji).toHaveBeenNthCalledWith(+ 1,+ { addReaction },+ "imessage:chat",+ "latest-id",+ "🎉",+ );+ expect(sendEmoji).toHaveBeenNthCalledWith(+ 2,+ { addReaction },+ "imessage:chat",+ "latest-id",+ "👩💻",+ );+ });++ it.each(["party", "🎉🎉", "a"])("rejects %j", async (tapback) => {+ const { addReaction, run, sendEmoji } = setup(conversation);++ await expect(run(tapback)).rejects.toThrow(`Unknown tapback "${tapback}"`);+ expect(addReaction).not.toHaveBeenCalled();+ expect(sendEmoji).not.toHaveBeenCalled();+ });++ it("refuses sessions from another channel", async () => {+ const { addReaction, run } = setup(+ { latestMessageId: "latest-id", thread: { id: "slack:chat" } },+ "channel:slack",+ );++ await expect(run("love")).rejects.toThrow(+ "Tapbacks work only in a conversation that came through the Photon iMessage channel.",+ );+ expect(addReaction).not.toHaveBeenCalled();+ });++ it("explains when there is nothing to react to", async () => {+ const { run } = setup({ thread: { id: "imessage:chat" } });++ await expect(run("love")).rejects.toThrow("There is no message in this conversation");+ });+ });+});diff --git a/packages/eve/src/public/channels/imessage-tapbacks.ts b/packages/eve/src/public/channels/imessage-tapbacks.tsnew file mode 100644index 000000000..78004f054--- /dev/null+++ b/packages/eve/src/public/channels/imessage-tapbacks.ts@@ -0,0 +1,264 @@+import type { SessionAuthContext } from "#channel/types.js";+import { loadContext } from "#context/container.js";+import type {+ Adapter,+ Author,+ Chat,+ Message,+ ReactionEvent,+ Thread,+} from "#compiled/chat/index.js";+import type {+ ChatSdkChannel,+ ChatSdkChannelBridge,+ ChatSdkChannelState,+} from "#public/channels/chat-sdk/index.js";+import { isChannel } from "#public/channels/index.js";+import { fetchMessageBestEffort } from "#public/channels/chat-sdk/fetch-message.js";+import { defineTool, type ToolDefinition } from "#public/tools/index.js";+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";++/** The six standard iMessage tapbacks. */+export const IMESSAGE_TAPBACKS = [+ "love",+ "like",+ "dislike",+ "laugh",+ "emphasize",+ "question",+] as const;++/** A standard iMessage tapback. */+export type IMessageTapbackType = (typeof IMESSAGE_TAPBACKS)[number];++/** A tapback someone added to or removed from a message in an iMessage conversation. */+export interface IMessageTapback {+ /** `true` when the tapback was added, `false` when it was removed. */+ readonly added: boolean;+ /** The person who sent the tapback. */+ readonly author: Author;+ /** The message the tapback is on, when the provider includes it. */+ readonly message?: Message;+ /** Id of the message the tapback is on. */+ readonly messageId: string;+ /** The provider's raw event. */+ readonly raw: unknown;+ /** A standard tapback, or the emoji itself for an emoji tapback. */+ readonly tapback: IMessageTapbackType | (string & {});+}++/** Result of an `onTapback` hook. Return `null` to ignore the tapback. */+export type IMessageTapbackResult = {+ /**+ * Option id that answers the input request eve posted in the message the+ * tapback is on, such as `"approve"` or `"cancel"` for a tool approval.+ * When that message isn't waiting on an answer with this option, the agent+ * receives the tapback as a message instead.+ */+ readonly answer?: string;+ readonly auth: SessionAuthContext | null;+ readonly context?: readonly string[];+ /**+ * Replaces the text the agent receives. Defaults to text like+ * `Tapback: Loved “See you at 7”`.+ */+ readonly message?: string;+ /** Overrides the workflow run title without changing the message sent to the model. */+ readonly title?: string;+} | null;++/** Input of the tool returned by `tapbackTool()`. */+export interface IMessageTapbackToolInput {+ /** A standard tapback, or a single emoji such as `"🎉"`. */+ readonly tapback: IMessageTapbackType | (string & {});+}++/** Context passed to an `onTapback` hook. */+export interface IMessageTapbackContext {+ /** Low-level Chat SDK thread for iMessage-specific operations. */+ readonly thread: Thread<unknown>;+}++type TapbackHook = (+ ctx: IMessageTapbackContext,+ tapback: IMessageTapback,+) => IMessageTapbackResult | Promise<IMessageTapbackResult>;++/** Sends an emoji tapback (not one of the six standard ones) through the channel's adapter. */+export type SendEmojiTapback = (+ adapter: Adapter,+ threadId: string,+ messageId: string,+ emoji: string,+) => Promise<void>;++const TAPBACK_BY_EMOJI_NAME: Readonly<Record<string, IMessageTapbackType>> = {+ exclamation: "emphasize",+ heart: "love",+ laugh: "laugh",+ question: "question",+ thumbs_down: "dislike",+ thumbs_up: "like",+};++// The emoji iMessage shows for each standard tapback, so the model can pass either.+const TAPBACK_BY_GLYPH: Readonly<Record<string, IMessageTapbackType>> = {+ "❓": "question",+ "❤": "love",+ "❤️": "love",+ "‼": "emphasize",+ "‼️": "emphasize",+ "👍": "like",+ "👎": "dislike",+ "😂": "laugh",+};++const EMOJI = /\p{Extended_Pictographic}|\p{Regional_Indicator}/u;+const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });++// iMessage's own wording when it shows a tapback as text.+const ADDED_VERB: Readonly<Record<IMessageTapbackType, string>> = {+ dislike: "Disliked",+ emphasize: "Emphasized",+ laugh: "Laughed at",+ like: "Liked",+ love: "Loved",+ question: "Questioned",+};++const MAX_QUOTED_CHARS = 200;++/** Normalizes a Chat SDK reaction event from an iMessage adapter. */+export function toIMessageTapback(event: ReactionEvent): IMessageTapback {+ return {+ added: event.added,+ author: event.user,+ message: event.message,+ messageId: event.messageId,+ raw: event.raw,+ tapback: TAPBACK_BY_EMOJI_NAME[event.emoji.name] ?? event.rawEmoji,+ };+}++/** Model-visible text for a tapback, in the form iMessage uses for tapbacks shown as text. */+export function iMessageTapbackText(tapback: IMessageTapback): string {+ const text = tapback.message?.text.trim();+ const target = text+ ? `“${text.length > MAX_QUOTED_CHARS ? `${text.slice(0, MAX_QUOTED_CHARS - 1)}…` : text}”`+ : "a message";+ const standard = isStandardTapback(tapback.tapback);+ if (!tapback.added) {+ return `Tapback: Removed ${standard ? `a ${tapback.tapback} tapback` : tapback.tapback} from ${target}`;+ }+ return standard+ ? `Tapback: ${ADDED_VERB[tapback.tapback as IMessageTapbackType]} ${target}`+ : `Tapback: Reacted ${tapback.tapback} to ${target}`;+}++/** Sends tapbacks people add or remove to eve when `onTapback` accepts them. */+export function dispatchIMessageTapbacks<TAdapters extends Record<string, Adapter>>(+ bridge: ChatSdkChannelBridge<TAdapters>,+ onTapback: TapbackHook,+): void {+ bridge.bot.onReaction(async (event: ReactionEvent) => {+ if (event.user.isMe) return;+ const tapback = toIMessageTapback({+ ...event,+ // Photon and Linq leave the reacted message out of the event, but both can fetch it by id.+ message:+ event.message ??+ (await fetchMessageBestEffort(event.adapter, event.threadId, event.messageId)) ??+ undefined,+ });+ const result = await onTapback({ thread: event.thread }, tapback);+ if (result === null) return;+ await bridge.send(result.message ?? iMessageTapbackText(tapback), {+ auth: result.auth,+ context: [...(result.context ?? [])],+ inputAnswer:+ result.answer === undefined+ ? undefined+ : { messageId: tapback.messageId, optionId: result.answer },+ thread: event.thread.toJSON(),+ title: result.title,+ });+ });+}++/**+ * Builds a tool that reacts to the latest message in the session's iMessage+ * conversation. It acts only in sessions that came through `channel`.+ */+export function iMessageTapbackTool(options: {+ readonly adapterName: string;+ readonly bot: Chat;+ readonly channel: ChatSdkChannel;+ readonly channelLabel: string;+ /** Defaults to the adapter's `addReaction`. */+ readonly sendEmoji?: SendEmojiTapback;+}): ToolDefinition<IMessageTapbackToolInput, string> {+ const { adapterName, bot, channel, channelLabel } = options;+ const sendEmoji: SendEmojiTapback =+ options.sendEmoji ??+ ((adapter, threadId, messageId, emoji) => adapter.addReaction(threadId, messageId, emoji));+ return defineTool<IMessageTapbackToolInput, string>({+ availableInSubagents: false,+ description:+ "React to the latest message in this iMessage conversation with a tapback: love (heart), like (thumbs up), dislike (thumbs down), laugh (haha), emphasize (!!), question (?), or any single emoji such as 🎉. Use it to acknowledge a message, alone or alongside a reply.",+ inputSchema: {+ type: "object",+ properties: {+ tapback: {+ type: "string",+ description: `One of ${IMESSAGE_TAPBACKS.join(", ")}, or a single emoji.`,+ },+ },+ required: ["tapback"],+ additionalProperties: false,+ },+ async execute(input) {+ const tapback = normalizeOutgoingTapback(input.tapback);+ if (tapback === undefined) {+ throw new Error(+ `Unknown tapback "${input.tapback}". Use one of ${IMESSAGE_TAPBACKS.join(", ")}, or a single emoji.`,+ );+ }+ const adapter = loadContext().get(ChannelKey);+ if (adapter === undefined || !isChannel({ kind: adapter.kind }, channel)) {+ throw new Error(+ `Tapbacks work only in a conversation that came through the ${channelLabel} channel.`,+ );+ }+ const state = adapter.state as Partial<ChatSdkChannelState> | undefined;+ const threadId = state?.thread?.id;+ const messageId = state?.latestMessageId;+ if (!threadId || !messageId) {+ throw new Error("There is no message in this conversation to react to yet.");+ }+ // The step may run where the webhook didn't, so the adapter may not be initialized yet.+ await bot.initialize();+ const chatAdapter = bot.getAdapter(adapterName);+ if (isStandardTapback(tapback)) {+ await chatAdapter.addReaction(threadId, messageId, tapback);+ } else {+ await sendEmoji(chatAdapter, threadId, messageId, tapback);+ }+ return `Sent a ${tapback} tapback.`;+ },+ });+}++/** A standard tapback name for a standard name or its emoji, the emoji itself for any other single emoji. */+function normalizeOutgoingTapback(value: string): string | undefined {+ const trimmed = value.trim();+ const lower = trimmed.toLowerCase();+ if (isStandardTapback(lower)) return lower;+ const standard = TAPBACK_BY_GLYPH[trimmed];+ if (standard !== undefined) return standard;+ const segments = [...graphemes.segment(trimmed)];+ return segments.length === 1 && EMOJI.test(trimmed) ? trimmed : undefined;+}++function isStandardTapback(value: string): value is IMessageTapbackType {+ return (IMESSAGE_TAPBACKS as readonly string[]).includes(value);+}diff --git a/packages/eve/src/public/channels/linq/index.ts b/packages/eve/src/public/channels/linq/index.tsindex 92a3df568..5af87c228 100644--- a/packages/eve/src/public/channels/linq/index.ts+++ b/packages/eve/src/public/channels/linq/index.ts@@ -9,3 +9,11 @@ export {type LinqInboundResult,type LinqInboundResultOrPromise,} from "#public/channels/linq/linqChannel.js";+export {+ IMESSAGE_TAPBACKS,+ type IMessageTapback,+ type IMessageTapbackContext,+ type IMessageTapbackResult,+ type IMessageTapbackToolInput,+ type IMessageTapbackType,+} from "#public/channels/imessage-tapbacks.js";diff --git a/packages/eve/src/public/channels/linq/linqChannel.test.ts b/packages/eve/src/public/channels/linq/linqChannel.test.tsindex e772fb349..d83dcacf3 100644--- a/packages/eve/src/public/channels/linq/linqChannel.test.ts+++ b/packages/eve/src/public/channels/linq/linqChannel.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";-const { createLinqAdapter, directMessage, fetchMessage, markRead, newMessage, send } = vi.hoisted(- () => ({+const { createLinqAdapter, directMessage, fetchMessage, markRead, newMessage, reaction, send } =+ vi.hoisted(() => ({createLinqAdapter: vi.fn((_config: { credentials?: () => unknown | Promise<unknown> }) => ({name: "linq",})),@@ -9,9 +9,9 @@ const { createLinqAdapter, directMessage, fetchMessage, markRead, newMessage, sefetchMessage: vi.fn(),markRead: vi.fn(),newMessage: vi.fn(),+ reaction: vi.fn(),send: vi.fn(),- }),-);+ }));vi.mock("#public/channels/chat-sdk/index.js", () => ({chatSdkChannel: () => ({@@ -19,6 +19,7 @@ vi.mock("#public/channels/chat-sdk/index.js", () => ({getAdapter: () => ({ fetchMessage, markRead }),onDirectMessage: directMessage,onNewMessage: newMessage,+ onReaction: reaction,},channel: { routes: [] },send,@@ -34,7 +35,7 @@ vi.mock("#compiled/@linqapp/chat-sdk-adapter/index.js", () => ({vi.mock("#public/channels/auth.js", () => ({ vercelOidc: vi.fn() }));import { Message } from "#compiled/chat/index.js";-import { linqChannel } from "#public/channels/linq/linqChannel.js";+import { defaultLinqAuth, linqChannel } from "#public/channels/linq/linqChannel.js";describe("linqChannel", () => {beforeEach(() => {@@ -156,4 +157,29 @@ describe("linqChannel", () => {expect(markRead).toHaveBeenCalledWith(thread.id, message.id);expect(send).not.toHaveBeenCalled();});++ it("ignores tapbacks unless onTapback accepts them", () => {+ linqChannel({ credentials: { apiKey: "linq-api-key", signingSecret: "linq-signing-secret" } });+ expect(reaction).not.toHaveBeenCalled();++ linqChannel({+ credentials: { apiKey: "linq-api-key", signingSecret: "linq-signing-secret" },+ onTapback: (_ctx, tapback) => ({ auth: defaultLinqAuth(tapback) }),+ });+ expect(reaction).toHaveBeenCalledTimes(1);+ });++ it("offers a tapback tool that takes standard tapbacks and emoji", () => {+ const channel = linqChannel({+ credentials: { apiKey: "linq-api-key", signingSecret: "linq-signing-secret" },+ });++ expect(channel.tapbackTool().inputSchema).toMatchObject({+ properties: {+ tapback: {+ description: "One of love, like, dislike, laugh, emphasize, question, or a single emoji.",+ },+ },+ });+ });});diff --git a/packages/eve/src/public/channels/linq/linqChannel.ts b/packages/eve/src/public/channels/linq/linqChannel.tsindex dc782c7c8..a15ac5aa1 100644--- a/packages/eve/src/public/channels/linq/linqChannel.ts+++ b/packages/eve/src/public/channels/linq/linqChannel.ts@@ -11,6 +11,15 @@ import {} from "#public/channels/chat-sdk/index.js";import { createMemoryState } from "#compiled/@chat-adapter/state-memory/index.js";import type { Channel } from "#public/definitions/channel.js";+import {+ dispatchIMessageTapbacks,+ iMessageTapbackTool,+ type IMessageTapback,+ type IMessageTapbackContext,+ type IMessageTapbackResult,+ type IMessageTapbackToolInput,+} from "#public/channels/imessage-tapbacks.js";+import type { ToolDefinition } from "#public/tools/index.js";import {createLinqAdapter,type LinqAdapterConfig,@@ -71,6 +80,15 @@ export interface LinqChannelConfig {ctx: LinqInboundMessageContext,message: Message,) => LinqInboundResultOrPromise;+ /**+ * Inbound tapback policy. Tapbacks are ignored by default. Return a result to+ * send the tapback to the agent as a message such as `Tapback: Loved “See you at 7”`,+ * or `null` to ignore it.+ */+ readonly onTapback?: (+ ctx: IMessageTapbackContext,+ tapback: IMessageTapback,+ ) => IMessageTapbackResult | Promise<IMessageTapbackResult>;/** Override the default webhook route (`/eve/v1/linq`). */readonly route?: string;/** Policy for accepted messages that arrive while a turn is active. */@@ -84,7 +102,13 @@ export interface LinqChannel extends Channel<ChatSdkChannelState,ChatSdkReceiveTarget,ChatSdkInstrumentationMetadata-> {}+> {+ /**+ * Returns a tool that lets the model react to the latest message in the+ * conversation with a tapback. Export it from a file in `agent/tools/`.+ */+ tapbackTool(): ToolDefinition<IMessageTapbackToolInput, string>;+}/*** Creates an eve channel for Linq-powered iMessage and SMS conversations.@@ -123,8 +147,18 @@ export function linqChannel(config: LinqChannelConfig): LinqChannel {bridge.bot.onNewMessage(/[\s\S]*/, async (thread: Thread, message: Message) => {await dispatchMessage(bridge, onMessage, thread, message);});+ if (config.onTapback) dispatchIMessageTapbacks(bridge, config.onTapback);- return bridge.channel;+ const channel: LinqChannel = Object.assign(bridge.channel, {+ tapbackTool: () =>+ iMessageTapbackTool({+ adapterName: "linq",+ bot: bridge.bot,+ channel,+ channelLabel: "Linq",+ }),+ });+ return channel;}function normalizeCredentials(@@ -161,7 +195,7 @@ async function resolveCredentialValue(value: LinqCredentialValue): Promise<strin}/** Default Linq auth projection for inbound Chat SDK message authors. */-export function defaultLinqAuth(message: Message): SessionAuthContext {+export function defaultLinqAuth(message: Pick<Message, "author">): SessionAuthContext {const attributes: Record<string, string> = {};if (message.author.userName !== undefined) attributes.user_name = message.author.userName;return {diff --git a/packages/eve/src/public/channels/photon/index.ts b/packages/eve/src/public/channels/photon/index.tsindex e81e86a6e..b5b343de3 100644--- a/packages/eve/src/public/channels/photon/index.ts+++ b/packages/eve/src/public/channels/photon/index.ts@@ -8,3 +8,11 @@ export {type PhotonInboundResult,type PhotonInboundResultOrPromise,} from "#public/channels/photon/photonIMessageChannel.js";+export {+ IMESSAGE_TAPBACKS,+ type IMessageTapback,+ type IMessageTapbackContext,+ type IMessageTapbackResult,+ type IMessageTapbackToolInput,+ type IMessageTapbackType,+} from "#public/channels/imessage-tapbacks.js";diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.tsindex acaf1bf6c..6e7a89535 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts@@ -1,19 +1,23 @@import { beforeEach, describe, expect, it, vi } from "vitest";-const { directMessage, newMessage, send } = vi.hoisted(() => ({+const { directMessage, fetchMessage, newMessage, reaction, send } = vi.hoisted(() => ({directMessage: vi.fn(),+ fetchMessage: vi.fn(),newMessage: vi.fn(),+ reaction: vi.fn(),send: vi.fn(),}));vi.mock("#public/channels/chat-sdk/index.js", () => ({chatSdkChannel: () => ({bot: {- getAdapter: () => ({ markRead: vi.fn() }),+ getAdapter: () => ({ fetchMessage, markRead: vi.fn() }),+ initialize: vi.fn(),onDirectMessage: directMessage,onNewMessage: newMessage,+ onReaction: reaction,},- channel: { routes: [] },+ channel: { __kind: "eve:channel", adapter: { kind: "channel:photon" }, routes: [] },send,}),messageToUserContent: (message: Message) => message.text,@@ -26,14 +30,49 @@ vi.mock("#compiled/@photon-ai/chat-adapter-imessage/index.js", () => ({}));vi.mock("#public/channels/auth.js", () => ({ vercelOidc: vi.fn() }));-import { photonIMessageChannel } from "#public/channels/photon/photonIMessageChannel.js";+import {+ defaultPhotonAuth,+ photonIMessageChannel,+} from "#public/channels/photon/photonIMessageChannel.js";import { Message } from "#compiled/chat/index.js";+import { ContextContainer, contextStorage } from "#context/container.js";+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";describe("photonIMessageChannel", () => {beforeEach(() => {vi.clearAllMocks();});+ it("sends emoji tapbacks through the fetched spectrum message", async () => {+ const react = vi.fn();+ fetchMessage.mockResolvedValue({ raw: { react } });+ const tool = photonIMessageChannel({+ credentials: async () => ({ projectId: "project-id", projectSecret: "project-secret" }),+ }).tapbackTool();+ const ctx = new ContextContainer();+ ctx.set(ChannelKey, {+ kind: "channel:photon",+ state: { latestMessageId: "latest-id", thread: { id: "imessage:chat" } },+ } as never);++ await contextStorage.run(ctx, () => tool.execute({ tapback: "🎉" }, {} as never));++ expect(fetchMessage).toHaveBeenCalledWith("imessage:chat", "latest-id");+ expect(react).toHaveBeenCalledWith("🎉");+ });++ it("ignores tapbacks unless onTapback accepts them", () => {+ const credentials = async () => ({ projectId: "project-id", projectSecret: "project-secret" });+ photonIMessageChannel({ credentials });+ expect(reaction).not.toHaveBeenCalled();++ photonIMessageChannel({+ credentials,+ onTapback: (_ctx, tapback) => ({ auth: defaultPhotonAuth(tapback) }),+ });+ expect(reaction).toHaveBeenCalledTimes(1);+ });+it("inherits the shared steering default for a direct message", async () => {photonIMessageChannel({credentials: async () => ({ projectId: "project-id", projectSecret: "project-secret" }),diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.tsindex 0001ffb57..7c5c1c5d7 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.ts@@ -7,7 +7,16 @@ import {type ChatSdkChannelBridge,type ChatSdkChannelEvents,} from "#public/channels/chat-sdk/index.js";-import type { Message, Thread } from "#compiled/chat/index.js";+import {+ dispatchIMessageTapbacks,+ iMessageTapbackTool,+ type IMessageTapback,+ type IMessageTapbackContext,+ type IMessageTapbackResult,+ type IMessageTapbackToolInput,+} from "#public/channels/imessage-tapbacks.js";+import type { ToolDefinition } from "#public/tools/index.js";+import type { Adapter, Message, Thread } from "#compiled/chat/index.js";import { createMemoryState } from "#compiled/@chat-adapter/state-memory/index.js";import {createiMessageAdapter,@@ -58,6 +67,15 @@ export interface PhotonIMessageChannelConfig {ctx: PhotonInboundMessageContext,message: Message,) => PhotonInboundResultOrPromise;+ /**+ * Inbound tapback policy. Tapbacks are ignored by default. Return a result to+ * send the tapback to the agent as a message such as `Tapback: Loved “See you at 7”`,+ * or `null` to ignore it.+ */+ readonly onTapback?: (+ ctx: IMessageTapbackContext,+ tapback: IMessageTapback,+ ) => IMessageTapbackResult | Promise<IMessageTapbackResult>;/** Override the default webhook route (`/eve/v1/photon`). */readonly route?: string;/** Policy for accepted messages that arrive while a turn is active. */@@ -71,7 +89,13 @@ export interface PhotonIMessageChannelConfig {}/** First-class eve channel backed by Photon iMessage. */-export interface PhotonIMessageChannel extends ChatSdkChannel {}+export interface PhotonIMessageChannel extends ChatSdkChannel {+ /**+ * Returns a tool that lets the model react to the latest message in the+ * conversation with a tapback. Export it from a file in `agent/tools/`.+ */+ tapbackTool(): ToolDefinition<IMessageTapbackToolInput, string>;+}/*** Creates an eve channel for Photon-powered iMessage.@@ -115,12 +139,41 @@ export function photonIMessageChannel(config: PhotonIMessageChannelConfig): Photbridge.bot.onNewMessage(/[\s\S]*/, async (thread: Thread, message: Message) => {await dispatchMessage(bridge, onMessage, thread, message);});+ if (config.onTapback) dispatchIMessageTapbacks(bridge, config.onTapback);++ const channel: PhotonIMessageChannel = Object.assign(bridge.channel, {+ tapbackTool: () =>+ iMessageTapbackTool({+ adapterName: "imessage",+ bot: bridge.bot,+ channel,+ channelLabel: "Photon iMessage",+ sendEmoji: sendPhotonEmojiTapback,+ }),+ });+ return channel;+}- return bridge.channel;+/**+ * The Photon adapter's `addReaction` accepts only the six standard tapbacks,+ * but the spectrum message it returns from `fetchMessage` can react with any emoji.+ */+async function sendPhotonEmojiTapback(+ adapter: Adapter,+ threadId: string,+ messageId: string,+ emoji: string,+): Promise<void> {+ const message = await adapter.fetchMessage?.(threadId, messageId);+ const target = message?.raw as { react?: (emoji: string) => Promise<unknown> } | undefined;+ if (typeof target?.react !== "function") {+ throw new Error("Photon could not find the message to react to.");+ }+ await target.react(emoji);}/** Default Photon auth projection for inbound Chat SDK message authors. */-export function defaultPhotonAuth(message: Message): SessionAuthContext {+export function defaultPhotonAuth(message: Pick<Message, "author">): SessionAuthContext {const attributes: Record<string, string> = {};if (message.author.userName !== undefined) attributes.user_name = message.author.userName;return {