← back to Agent Ad Network
sdk/waitad.mjs
27 lines
// waitad — drop-in SDK: show an ad while an agent waits on something slow.
// Fail-open by design: if the ad server is down/empty, the wait proceeds silently.
// import { withAd, fetchAd } from './waitad.mjs';
// const result = await withAd(longRunningPromise, { context: ['deploy', 'shopify'] });
const BASE = process.env.WAITAD_BASE || 'http://127.0.0.1:9932';
const MIN_WAIT_MS = 400; // don't flash ads on fast operations
export async function fetchAd(context = []) {
try {
const ctl = new AbortController();
const t = setTimeout(() => ctl.abort(), 800);
const r = await fetch(`${BASE}/ad?format=json&context=${encodeURIComponent(context.join(','))}`, { signal: ctl.signal });
clearTimeout(t);
return (await r.json()).ad || null;
} catch { return null; }
}
export async function withAd(promise, { context = [], stream = process.stderr } = {}) {
let shown = false;
const timer = setTimeout(async () => {
const ad = await fetchAd(context);
if (ad) { shown = true; stream.write(`\n [sponsored while you wait] ${ad.headline} — ${ad.body}\n → ${ad.clickUrl}\n\n`); }
}, MIN_WAIT_MS);
try { return await promise; }
finally { clearTimeout(timer); if (shown) stream.write(''); }
}