Skip to content
Draft
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
2 changes: 0 additions & 2 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ jobs:
with:
persist-credentials: false
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4
with:
version: 10.33.4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 24
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

## Run locally

Requires Node.js 24, pnpm 10.33.4, and OpenAI and Browserbase API keys.
Requires Node.js 24, pnpm 12.21.0, and OpenAI and Browserbase API keys.

```sh
git clone https://github.com/browserbase/bell-stack.git
Expand Down
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";
},
},
});
});
4 changes: 2 additions & 2 deletions agent/extensions/link/lib/spend-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,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: z.iso.datetime().optional(),
recurring: z.object({
interval: z.string(),
interval_count: z.number().optional(),
Expand All @@ -83,7 +83,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: z.iso.datetime().nullable().optional(),
}).optional(),
}).optional(),
}).nullable().optional(),
Expand Down
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);
},
},
});
38 changes: 19 additions & 19 deletions agent/hooks/task-state.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
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));
function reduce(event: HookEvent, ctx: HookContext, current: ReturnType<typeof taskState.get>) {
return applyTaskEvent(current, event, ctx.session.id, {
id: ctx.occurrence.idempotencyKey, at: ctx.now.toISOString(),
});
}

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) => reduce(event, ctx, current));

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 = reduce(event, ctx, current);
if (current.status === "waiting_for_user" && next.status === "running")
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);
},
};
8 changes: 5 additions & 3 deletions agent/lib/linq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ 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
43 changes: 21 additions & 22 deletions agent/lib/task-state.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { defineState } from "eve/context";
import type { HookEvent } from "eve/hooks";

import type { BrowserProxyLocation, BrowserState } from "../../server/browser/types.js";

Expand Down Expand Up @@ -74,25 +75,20 @@ export function initializeTask(
}
export function applyTaskEvent(
record: DurableTaskRecord,
event: {
type: string;
data?: Record<string, unknown>;
meta?: { id?: string; at?: string };
},
event: HookEvent,
sessionId: string,
{ id, at }: { id: string; at: string },
): DurableTaskRecord {
const id = event.meta?.id,
at = event.meta?.at ?? new Date().toISOString();
let next = initializeTask(record, sessionId, at);
if (id && next.processedEventIds.includes(id)) return next;
if (next.processedEventIds.includes(id)) return next;
next = {
...next,
processedEventIds: id ? [...next.processedEventIds, id].slice(-2_000) : next.processedEventIds,
processedEventIds: [...next.processedEventIds, id].slice(-2_000),
updatedAt: at,
};
if (event.type === "message.received") {
if (event.type === "delivery.consumed") {
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(" "));
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 +107,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.status === "waiting_for_user" && !captchaNeedsReply(next))
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 +134,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" && event.data.outcome === "completed")
next = { ...next, status: "complete", activeStep: undefined };
return next;
}
Expand Down Expand Up @@ -337,11 +333,14 @@ 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 captchaNeedsReply(record: DurableTaskRecord): boolean {
return record.captcha?.status === "errored" || record.captcha?.status === "timed_out";
}
function classifyWait(request: { kind: string; prompt: string }): DurableTaskRecord["waitReason"] {
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";
if (request.kind === "approval" || value.includes("approval")) return "approval";
return "other";
}
export function safeText(value: unknown): string | undefined {
Expand Down
Loading
Loading