import type { Page } from 'playwright-core';
// 1. A first run opens the store and buys nothing.
const opener = await bu.runs.create({
task: 'Open https://shop.agentcard.sh and stop there. Do not click anything.',
});
const ready = await bu.runs.waitForEvent(opener.id, 'browser.ready');
const browserId = ready.data.browser_session_id as string;
const res = await fetch(`https://api.browser-use.com/api/v4/browsers/${browserId}`, {
headers: { 'X-Browser-Use-API-Key': process.env.BROWSER_USE_API_KEY! },
});
const { cdpUrl } = await res.json();
// 2. Attach Agentcard to every page, and wait until it is attached.
const browser = await chromium.connectOverCDP(cdpUrl);
const context = browser.contexts()[0];
const attach = (page: Page) =>
attachToPlaywright(page, {
vault,
user: 'usr_8f3k2m',
merchant: 'shop.agentcard.sh',
amount: 583,
currency: 'usd',
onApprovalUrl: (url) => sendToUser(url),
});
const checkouts = await Promise.all(context.pages().map(attach));
// The agent can open the checkout in a new tab, so attach to every page it opens.
context.on('page', (page) => {
attach(page).then(
(checkout) => checkouts.push(checkout),
(err) => console.error('Agentcard could not attach to a new tab', err),
);
});
await bu.runs.waitForCompletion(opener.id);
// 3. The shopping task runs in the same session, on the browser Agentcard is attached to.
// The placeholder the agent types: any of Stripe's published test cards.
const card = process.env.PLACEHOLDER_CARD_NUMBER!;
const run = await bu.runs.create({
sessionId: opener.sessionId,
task: `Buy one Enamel Camp Mug. Pay with card ${card}, expiry 12/34, CVC 123, and click Pay once. The payment then waits for the cardholder to approve on their phone. Do not click Pay again. Wait until the page shows the order is paid.`,
});
const dispatched = await bu.runs.waitForEvent(run.id, 'run.dispatched');
if (dispatched.data.browser_session_id !== browserId) {
// Browser Use moved the session to a new browser, and Agentcard is not attached there.
await bu.runs.cancel(run.id);
throw new Error('The session moved to a new browser. Attach to it and start the purchase again.');
}
await bu.runs.waitForCompletion(run.id);