diff --git a/agent/connections/notion.ts b/agent/connections/notion.ts index 88bd707..6227b72 100644 --- a/agent/connections/notion.ts +++ b/agent/connections/notion.ts @@ -3,33 +3,29 @@ import { notionAuth } from "../lib/notion-auth"; import { notionEnabled, notionEndpoint, notionOwner, safeNotion } from "../../server/notion/config"; import { getNotionOAuth } from "../../server/notion/oauth"; -export default defineDynamic({ - events: { - "turn.started": (_event, ctx) => { - if (!notionEnabled()) return null; - const auth = ctx.session.auth.current; - if (auth?.principalType !== "user" || !["bell:operator", "linq"].includes(auth.issuer ?? "")) return null; - const principal = { type: "user" as const, id: auth.principalId, issuer: auth.issuer }; - const owner = notionOwner(principal); - return defineMcpClientConnection({ - url: notionEndpoint, - instanceKey: owner, - description: "Notion: the user's personal preferences, routines, plans, decisions, and notes across conversations. Search before relying on remembered information.", - protocolVersionDiscovery: false, - auth: notionAuth, - tools: { allow: [ - "notion-search", "notion-fetch", "notion-memory-search", "notion-get-self", - "notion-get-tool-access", "notion-query-data-sources", - "notion-create-pages", "notion-update-page", "notion-create-database", "notion-update-data-source", - "notion-get-async-task", "notion-delete-pages", - ] }, - approval: async ({ toolName }) => { - if (toolName.startsWith("notion__") && (await safeNotion(() => getNotionOAuth().status(principal))).status !== "connected") - return "denied"; - return /__(?:notion-create-database|notion-update-data-source|notion-delete-pages)$/.test(toolName) - ? "user-approval" : "not-applicable"; - }, - }); +export default defineDynamic((ctx) => { + if (!notionEnabled()) return null; + const auth = ctx.session.auth.current; + if (auth?.principalType !== "user" || !["bell:operator", "linq"].includes(auth.issuer ?? "")) return null; + const principal = { type: "user" as const, id: auth.principalId, issuer: auth.issuer }; + const owner = notionOwner(principal); + return defineMcpClientConnection({ + url: notionEndpoint, + instanceKey: owner, + description: "Notion: the user's personal preferences, routines, plans, decisions, and notes across conversations. Search before relying on remembered information.", + protocolVersionDiscovery: false, + auth: notionAuth, + tools: { allow: [ + "notion-search", "notion-fetch", "notion-memory-search", "notion-get-self", + "notion-get-tool-access", "notion-query-data-sources", + "notion-create-pages", "notion-update-page", "notion-create-database", "notion-update-data-source", + "notion-get-async-task", "notion-delete-pages", + ] }, + approval: async ({ toolName }) => { + if (toolName.startsWith("notion__") && (await safeNotion(() => getNotionOAuth().status(principal))).status !== "connected") + return "denied"; + return /__(?:notion-create-database|notion-update-data-source|notion-delete-pages)$/.test(toolName) + ? "user-approval" : "not-applicable"; }, - }, + }); }); diff --git a/agent/extensions/link/lib/spend-requests.ts b/agent/extensions/link/lib/spend-requests.ts index 7286b10..448401e 100644 --- a/agent/extensions/link/lib/spend-requests.ts +++ b/agent/extensions/link/lib/spend-requests.ts @@ -34,6 +34,8 @@ const total = z.object({ amount: z.number(), }); +const expiration = z.union([z.number(), z.iso.datetime({ offset: true })]); + const metadata = z.object({ id: spendRequestId, status: z.string(), @@ -56,7 +58,7 @@ const metadata = z.object({ totals: z.array(total).optional(), approval_url: z.string().optional(), activity_url: z.string().optional(), - expires_at: z.number().optional(), + expires_at: expiration.optional(), recurring: z.object({ interval: z.string(), interval_count: z.number().optional(), @@ -83,7 +85,7 @@ const metadata = z.object({ display_message: z.string().optional(), action_url: z.string().nullable().optional(), resolution: z.string().optional(), - expires_at: z.number().nullable().optional(), + expires_at: expiration.nullable().optional(), }).optional(), }).optional(), }).nullable().optional(), diff --git a/agent/extensions/link/tools/mpp_decode.ts b/agent/extensions/link/tools/mpp_decode.ts new file mode 100644 index 0000000..a908e44 --- /dev/null +++ b/agent/extensions/link/tools/mpp_decode.ts @@ -0,0 +1,2 @@ +import { disableTool } from "eve/tools"; +export default disableTool(); diff --git a/agent/extensions/link/tools/mpp_pay.ts b/agent/extensions/link/tools/mpp_pay.ts new file mode 100644 index 0000000..a908e44 --- /dev/null +++ b/agent/extensions/link/tools/mpp_pay.ts @@ -0,0 +1,2 @@ +import { disableTool } from "eve/tools"; +export default disableTool(); diff --git a/agent/extensions/link/tools/retrieve_approval_policy.ts b/agent/extensions/link/tools/retrieve_approval_policy.ts new file mode 100644 index 0000000..a908e44 --- /dev/null +++ b/agent/extensions/link/tools/retrieve_approval_policy.ts @@ -0,0 +1,2 @@ +import { disableTool } from "eve/tools"; +export default disableTool(); diff --git a/agent/hooks/browser-lifecycle.ts b/agent/hooks/browser-lifecycle.ts index a5bab4e..9dda121 100644 --- a/agent/hooks/browser-lifecycle.ts +++ b/agent/hooks/browser-lifecycle.ts @@ -4,8 +4,8 @@ import { saveBrowserRuntime } from "../lib/browser-runtime"; export default defineHook({ events: { - async "turn.completed"(_event, ctx) { - await saveBrowserRuntime(ctx.session.id); + async "turn.settled"(event, ctx) { + if (event.data.outcome === "completed") await saveBrowserRuntime(ctx.session.id); }, }, }); diff --git a/agent/hooks/task-state.ts b/agent/hooks/task-state.ts index b17dbfa..d86feee 100644 --- a/agent/hooks/task-state.ts +++ b/agent/hooks/task-state.ts @@ -1,36 +1,30 @@ -import { defineHook, type HookEvent } from "eve/hooks"; +import { defineHook, type HookContext, type HookEvent } from "eve/hooks"; import { closeBrowserRuntime, resumeBrowserAfterHumanInput } from "../lib/browser-runtime"; import { applyTaskEvent, taskState } from "../lib/task-state"; -const update = (event: HookEvent, ctx: { session: { id: string } }) => - taskState.update((current) => applyTaskEvent(current, event, ctx.session.id)); - -const cancel = async (event: HookEvent<"turn.cancelled">, ctx: { session: { id: string } }) => { - await closeBrowserRuntime(ctx.session.id); - update(event, ctx); -}; +const update = (event: HookEvent, ctx: HookContext) => + taskState.update((current) => applyTaskEvent(current, event, ctx.session.id, ctx.position, ctx.now.toISOString())); export default defineHook({ events: { "session.started": update, "turn.started": update, - "message.received": (event, ctx) => { + "delivery.consumed": (event, ctx) => { taskState.update((current) => { - const next = applyTaskEvent(current, event, ctx.session.id); - if (next !== current && current.status === "waiting_for_user") + const next = applyTaskEvent(current, event, ctx.session.id, ctx.position, ctx.now.toISOString()); + if (next !== current && current.status === "waiting_for_user" && event.data.parts.length > 0) resumeBrowserAfterHumanInput(ctx.session.id); return next; }); }, - "step.started": update, - "input.requested": update, - "input.resolved": update, - "turn.completed": update, - "turn.failed": update, - "turn.cancelled": cancel, - "session.waiting": update, - "session.failed": update, - "session.completed": update, + "model.started": update, + "interaction.opened": update, + "interaction.settled": update, + async "turn.settled"(event, ctx) { + if (event.data.outcome === "cancelled") await closeBrowserRuntime(ctx.session.id); + update(event, ctx); + }, + "session.ended": update, }, }); diff --git a/agent/lib/browser-runtime.ts b/agent/lib/browser-runtime.ts index 6f9839e..b5d204e 100644 --- a/agent/lib/browser-runtime.ts +++ b/agent/lib/browser-runtime.ts @@ -358,12 +358,8 @@ function scheduleIdleClose(sessionId: string, runtime: BrowserRuntime): void { } // Channel callbacks also run when Eve ends a session outside a turn. -// Global stream hooks do not run on that path in Eve 0.79.1. export const browserChannelEvents = { - async "session.completed"(_event: unknown, _channel: unknown, ctx: { session: { id: string } }) { + async "session.ended"(_event: unknown, ctx: { session: { id: string } }) { await closeBrowserRuntime(ctx.session.id); }, - async "session.failed"(event: { sessionId: string }) { - await closeBrowserRuntime(event.sessionId); - }, }; diff --git a/agent/lib/linq.ts b/agent/lib/linq.ts index 9462924..bf48cb4 100644 --- a/agent/lib/linq.ts +++ b/agent/lib/linq.ts @@ -3,11 +3,11 @@ import { browserChannelEvents } from "./browser-runtime"; export const linqBrowserEvents: NonNullable = { ...browserChannelEvents, - async "session.failed"(event, channel) { + async "session.ended"(event, ctx) { try { - await browserChannelEvents["session.failed"](event); + await browserChannelEvents["session.ended"](event, ctx); } finally { - await channel.thread?.post("This session could not recover from an error. Start a new conversation to continue."); + if (event.data.outcome === "failed") await ctx.channel.thread?.post("This session could not recover from an error. Start a new conversation to continue."); } }, }; diff --git a/agent/lib/task-state.ts b/agent/lib/task-state.ts index f90ed56..fab1aec 100644 --- a/agent/lib/task-state.ts +++ b/agent/lib/task-state.ts @@ -1,4 +1,6 @@ import { defineState } from "eve/context"; +import type { FactPosition, InteractionRequest } from "eve/events"; +import type { HookEvent } from "eve/hooks"; import type { BrowserProxyLocation, BrowserState } from "../../server/browser/types.js"; @@ -74,15 +76,12 @@ export function initializeTask( } export function applyTaskEvent( record: DurableTaskRecord, - event: { - type: string; - data?: Record; - meta?: { id?: string; at?: string }; - }, + event: HookEvent, sessionId: string, + position?: FactPosition, + at = new Date().toISOString(), ): DurableTaskRecord { - const id = event.meta?.id, - at = event.meta?.at ?? new Date().toISOString(); + const id = position && `${position.line}:${position.index}`; let next = initializeTask(record, sessionId, at); if (id && next.processedEventIds.includes(id)) return next; next = { @@ -90,9 +89,9 @@ export function applyTaskEvent( processedEventIds: id ? [...next.processedEventIds, id].slice(-2_000) : next.processedEventIds, updatedAt: at, }; - if (event.type === "message.received") { + if (event.type === "delivery.consumed" && event.data.parts.length > 0) { if (next.title === "New task") { - const text = safeText(event.data?.message ?? event.data?.text); + const text = safeText(event.data.parts.flatMap((part) => part.kind === "text" ? [part.text] : []).join("\n")); if (text) next = { ...next, title: text.slice(0, 64) }; } // A reply after handoff permits a fresh observation of the existing page. @@ -111,25 +110,25 @@ export function applyTaskEvent( activeStep: "agent turn", waitReason: undefined, }; - else if (event.type === "step.started") + else if (event.type === "model.started") next = captchaBlocksGeneric(next) ? next : { ...next, status: "running", activeStep: "model step" }; - else if (event.type === "input.requested") + else if (event.type === "interaction.opened") next = { ...next, status: "waiting_for_user", activeStep: "waiting for user", - waitReason: classifyWait(event.data), + waitReason: classifyWait(event.data.request), }; - else if (event.type === "input.resolved") + else if (event.type === "interaction.settled") next = { ...next, status: "running", activeStep: "resuming", waitReason: undefined, }; - else if (event.type === "turn.completed" || event.type === "session.waiting") + else if (event.type === "turn.settled" && event.data.outcome === "completed") next = captchaBlocksGeneric(next) ? next : { @@ -138,16 +137,16 @@ export function applyTaskEvent( activeStep: undefined, waitReason: undefined, }; - else if (event.type === "turn.failed" || event.type === "session.failed") + else if ((event.type === "turn.settled" || event.type === "session.ended") && event.data.outcome === "failed") next = { ...next, status: "failed", activeStep: undefined }; - else if (event.type === "turn.cancelled") + else if (event.type === "turn.settled" && event.data.outcome === "cancelled") next = closeTaskBrowser({ ...next, status: "canceled", activeStep: undefined, waitReason: undefined, }); - else if (event.type === "session.completed") + else if (event.type === "session.ended") next = { ...next, status: "complete", activeStep: undefined }; return next; } @@ -337,11 +336,11 @@ export function closeTaskBrowser(record: DurableTaskRecord): DurableTaskRecord { updatedAt: new Date().toISOString(), }; } -function classifyWait(data?: Record): DurableTaskRecord["waitReason"] { - const value = JSON.stringify(data ?? {}).toLowerCase(); +function classifyWait(request: InteractionRequest): DurableTaskRecord["waitReason"] { + if (request.kind === "approval") return "approval"; + const value = request.prompt.toLowerCase(); if (value.includes("captcha")) return "captcha"; if (value.includes("otp") || value.includes("code")) return "otp"; - if (value.includes("approval")) return "approval"; return "other"; } export function safeText(value: unknown): string | undefined { diff --git a/app/chat.tsx b/app/chat.tsx index d2f9cb1..5a4a596 100644 --- a/app/chat.tsx +++ b/app/chat.tsx @@ -1,8 +1,9 @@ "use client"; import Image from "next/image"; import { useRouter } from "next/navigation"; +import { Client, ClientError, SessionNotActiveError } from "eve/client"; import { useEveAgent } from "eve/react"; -import { Client } from "eve/client"; +import { activeTurn, openInteractions, signInEnding } from "eve/events"; import { useState } from "react"; import { browserPreview } from "./projection"; @@ -19,16 +20,11 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU window.history.replaceState(null, "", `/s/${encodeURIComponent(session.sessionId)}`); }, }); - const busy = agent.status === "submitted" || agent.status === "streaming"; + const busy = agent.status === "busy"; const waiting = busy || agent.status === "resuming" || retiring; + const canStop = activeTurn(agent.view) !== undefined; const preview = browserPreview(agent.events); - const pending = agent.data.messages - .flatMap((message) => message.parts) - .flatMap((part) => { - if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return []; - const request = part.toolMetadata?.eve?.inputRequest; - return request ? [request] : []; - }); + const pending = openInteractions(agent.view).filter(({ request }) => request.kind !== "sign-in"); async function send(text: string) { if (!text.trim() || waiting) return; setError(""); @@ -44,10 +40,15 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU setRetiring(true); setError(""); try { - const activeSessionId = agent.session?.sessionId ?? sessionId; - if (activeSessionId) - await new Client({ host: "" }).sessions.attach(activeSessionId).reset(); - agent.reset(); + try { + if (agent.session) await agent.end(); + else if (sessionId) await new Client({ baseUrl: "" }).sessions.attach(sessionId).end(); + } catch (error) { + const inactive = SessionNotActiveError.is(error) && !error.retryable; + const expired = ClientError.is(error) && error.code === "session_expired"; + if (!inactive && !expired) throw error; + } + agent.newSession(); setInput(""); router.push("/"); } catch { @@ -89,28 +90,30 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU Open demo site ↗
- {agent.data.messages + {agent.messages .filter((message) => message.role === "user" || message.role === "assistant") .map((message) => (
{message.role === "user" ? "You" : "Bell"} - {message.parts.map((part, index) => - part.type === "text" ?

{part.text}

- : part.type === "authorization" ? ( -
- {part.state === "completed" ? ( -

{part.outcome === "authorized" ? `${part.displayName} connected.` : `${part.displayName} authorization ${part.outcome}.`}

- ) : ( - <> -

{part.description}

- {part.authorization?.url && ( - Connect {part.displayName} - )} - - )} -
- ) : null, - )} + {message.parts.map((part, index) => { + if (part.type === "text") return

{part.text}

; + const interaction = part.type === "interaction" ? part + : part.type === "tool" ? part.interaction : undefined; + if (!interaction || interaction.request.kind !== "sign-in") return null; + const { request, outcome } = interaction; + const name = request.signIn?.displayName ?? "Account"; + const url = request.link?.url ?? request.signIn?.url; + return ( +
+ {outcome ?

{name} {signInEnding(outcome)}.

: ( + <> +

{request.prompt}

+ {url && {request.link?.label ?? `Connect ${name}`}} + + )} +
+ ); + })}
))}
@@ -123,8 +126,8 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU {" "}

)} - {pending.map((request) => ( -
+ {pending.map(({ interactionId, request }) => ( +
{request.prompt} {request.options?.map((option) => ( )} @@ -177,7 +180,7 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU - {busy && ( + {canStop && (