Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 24 additions & 28 deletions agent/connections/notion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
},
},
});
});
6 changes: 4 additions & 2 deletions agent/extensions/link/lib/spend-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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(),
Expand All @@ -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(),
Expand Down
2 changes: 2 additions & 0 deletions agent/extensions/link/tools/mpp_decode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { disableTool } from "eve/tools";
export default disableTool();
2 changes: 2 additions & 0 deletions agent/extensions/link/tools/mpp_pay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { disableTool } from "eve/tools";
export default disableTool();
2 changes: 2 additions & 0 deletions agent/extensions/link/tools/retrieve_approval_policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { disableTool } from "eve/tools";
export default disableTool();
4 changes: 2 additions & 2 deletions agent/hooks/browser-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
},
});
34 changes: 14 additions & 20 deletions agent/hooks/task-state.ts
Original file line number Diff line number Diff line change
@@ -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,
},
});
6 changes: 1 addition & 5 deletions agent/lib/browser-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
};
6 changes: 3 additions & 3 deletions agent/lib/linq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { browserChannelEvents } from "./browser-runtime";

export const linqBrowserEvents: NonNullable<LinqChannelConfig["events"]> = {
...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.");
}
},
};
Expand Down
39 changes: 19 additions & 20 deletions agent/lib/task-state.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -74,25 +76,22 @@ export function initializeTask(
}
export function applyTaskEvent(
record: DurableTaskRecord,
event: {
type: string;
data?: Record<string, unknown>;
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 = {
...next,
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.
Expand All @@ -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
: {
Expand All @@ -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;
}
Expand Down Expand Up @@ -337,11 +336,11 @@ export function closeTaskBrowser(record: DurableTaskRecord): DurableTaskRecord {
updatedAt: new Date().toISOString(),
};
}
function classifyWait(data?: Record<string, unknown>): 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 {
Expand Down
Loading