Reference

JS API Reference

All window.widgent() commands, events, and patterns.

Setup

widgent:ready event event

Fired on window when the widget script has loaded and is ready to receive commands.

js
window.addEventListener('widgent:ready', () => {
  // Safe to call window.widgent() here
});

// Handle already-loaded case (e.g. SPA hot reload)
if ((window as any).widgent?.ready) {
  initWidget();
}

Identity

setIdentityTokenFetcher command

Provide a function that returns a signed JWT identifying the current user. Called automatically on load and when the token expires.

js
window.widgent('setIdentityTokenFetcher', async () => {
  const res = await fetch('/api/widgent-token', {
    headers: { Authorization: `Bearer ${getAppToken()}` }
  });
  const { token } = await res.json();
  return token; // return '' for anonymous
});
Return an empty string to fall back to an anonymous session.

Context

setContext command

Send the current page state to the AI. Merged with existing context — not replaced. The AI sees this in every message.

js
window.widgent('setContext', {
  currentRoute: '/dashboard/orders',
  userId: user.id,
  userPlan: user.plan,
  selectedOrderId: order?.id,  // undefined removes the key
});
Keys with `undefined` values are removed from context. Call this whenever relevant state changes.

Tools

registerTools command

Register client-side functions the AI can call. Each value must be an async function.

js
window.widgent('registerTools', {
  navigateTo: async ({ path }) => {
    window.widgent('setToolStatus', 'Navigating...');
    router.push(path);
    window.widgent('setToolStatus', '');
    return { status: 'ok', path };
  },

  getOrderStatus: async ({ orderId }) => {
    const res = await fetch(`/api/orders/${orderId}`);
    return res.json();
  },
});
Tools must also be registered via the REST API with their JSON Schema so the LLM knows what to call.
setToolStatus command

Show a status message in the widget while a tool is running. Pass an empty string to clear it.

js
window.widgent('setToolStatus', 'Loading results...');
// ... async work ...
window.widgent('setToolStatus', ''); // clear

Widget Control

open / close / toggle command

Programmatically control widget visibility. Works with bubble, sidebar, and popup embed types.

js
window.widgent('open');
window.widgent('close');
window.widgent('toggle');
setGreeting command

Override the greeting message shown when the widget opens.

js
window.widgent('setGreeting',
  `You have ${count} unread messages.`
);
setSuggestedActions command

Override the quick-action buttons shown under the greeting.

js
window.widgent('setSuggestedActions', [
  { label: 'Track my order', message: 'Where is my latest order?' },
  { label: 'Get a refund',   message: 'I need to return an item' },
]);
This overrides what the LLM set. Use a guard to call only once per state transition.
send command

Programmatically send a message and trigger a full AI response.

js
window.widgent('send', { message: 'Show my recent orders' });

Headless Mode

send (with streaming callbacks) command

For headless embed only. Accepts streaming callbacks to build a fully custom UI.

js
window.widgent('send', {
  message: 'Hello',
  onChunk:    (text)          => appendToUI(text),
  onToolCall: (name, params)  => handleToolCall(name, params),
  onDone:     (fullText)      => finalizeMessage(fullText),
  onError:    (err)           => showError(err),
});

Events

Window events event

The widget fires DOM events on window for external listeners.

js
window.addEventListener('widgent:ready',   () => { /* loaded */ });
window.addEventListener('widgent:open',    () => { /* widget opened */ });
window.addEventListener('widgent:close',   () => { /* widget closed */ });

window.addEventListener('widgent:message', (e) => {
  // e.detail: { role: 'user' | 'assistant', content: string }
});

window.addEventListener('widgent:tool-call', (e) => {
  // e.detail: { tool: string, params: object }
});