AI Assistant Hooks demo

AI Assistant Hooks ·RFC draft 0.1

Adding AI Assistant Hooks to your AI assistant

Acme CRM is a made-up CRM with a built-in AI assistant, Acme AI. It shows what a vendor adds to a page it already has, so that voice tools, agents and screen readers can use the AI assistant without guessing. Level 1 is a few HTML attributes. Level 2 adds two JavaScript functions.

Try each level

Open Vendor view from the bar at the top of the demo to see what a client finds at each level, watch each answer’s state change, and make the next reply fail.

Why hooks §2

A tool that drives your AI assistant for someone, by voice or from an agent, has to work out from the page where to type, what to click, which element is the answer and when that answer is done. Your page already knows all four. Hooks let the page say so, which means the tool no longer guesses, and no longer breaks when you redesign.

The last of those guesses is the expensive one. In OpenPosse’s measurements, waiting to be sure an answer has finished costs about 4 seconds of a 14-second voice turn.

Level 1: mark the controls §4

Add one meta tag to the page’s head, so a client can tell from a single query that the page has hooks, and which version:

<meta name="assistant-hooks" content="0.1">

Then name each control with a data-assistant-hook attribute.

HookRequiredWhat it marksIn Acme CRM
composerYesWhere a question is typedThe question box, assistant-composer
sendYesThe button that sends what’s in the composerSend, assistant-send
answerYesEach reply, carrying its stateEach reply, assistant-answer
answer-bodyNoInside an answer, just the answer’s textassistant-answer-text. The Copy button sits outside it.
launcherNoWhat opens the AI assistant when the composer isn’t on the page“Ask Acme AI” in the top bar
stopNoWhat cancels a reply in progressStop, which takes Send’s place while Acme AI answers

A composer that sends on Enter, with no Send button, still needs send. A hidden button that sends is enough.

data-assistant-name on any hook gives the name a client should use for the AI assistant. Acme puts it on the launcher.

Here is Acme AI with Level 1 on, trimmed to the elements that carry hooks:

<button class="launcher" data-testid="assistant-launcher"
        data-assistant-hook="launcher" data-assistant-name="Acme AI">
  Ask Acme AI
</button>

<aside class="drawer" aria-label="Acme AI">
  <div class="conversation" data-testid="assistant-conversation" aria-live="polite">
    <div class="message question" data-testid="assistant-question">
      Which deals are missing an owner?
    </div>
    <div class="message answer" data-testid="assistant-answer"
         data-assistant-hook="answer" data-assistant-state="complete" aria-busy="false">
      <div class="answer-text" data-testid="assistant-answer-text"
           data-assistant-hook="answer-body">Twelve open deals have no owner…</div>
      <button class="copy" aria-label="Copy answer">…</button>
    </div>
  </div>

  <textarea data-testid="assistant-composer" data-assistant-hook="composer"
            aria-label="Ask Acme AI"></textarea>
  <button class="send" data-testid="assistant-send" data-assistant-hook="send"
          aria-label="Send">…</button>
  <!-- While Acme AI answers, Stop (data-assistant-hook="stop") takes Send's place. -->
</aside>

The hooks sit beside the data-testids Acme already had. Nothing was renamed, so a lasso OpenPosse recorded before the hooks existed still works, at every level.

In the demo, assistant.js adds these attributes when the page loads, because one page has to show all three levels. Your page would write them into its markup.

Answer states §4.1

Each answer carries data-assistant-state, so a client can tell when it has finished without timing anything.

StateMeans
pending (optional)Asked, and nothing has arrived yet
streamingText is arriving
completeYour page treats the reply as done, usually at the moment it hides Stop or re-enables Send. Set it once.
errorThe reply failed. Add data-assistant-error with a code from §6.

Acme sets the state, the error code and aria-busy together, in one function. Simplified from assistant.js:

function markState(answer, state, code = null) {
  answer.dataset.assistantState = state;
  if (code) answer.dataset.assistantError = code;
  else delete answer.dataset.assistantError;
  answer.setAttribute('aria-busy', String(state === 'pending' || state === 'streaming'));
}

Put the state on the answer, not on its body

Recorders, OpenPosse’s included, build the tightest selector that matches every answer they saw. A state on the answer’s body can end up in that selector, and the recording then names “an answer that is complete” instead of “an answer”.

Errors stay on screen

When a reply fails, Acme writes one plain sentence into the answer and sets error with the code. For rate_limited, the sentence is “Acme AI has had too many questions in a short time. Wait a minute, then ask again.”

A client that reads hooks gets the code. One that doesn’t yet, as OpenPosse doesn’t today, still finds an answer where it looks, with something true to say, instead of waiting until it times out.

Behaviour §4.2

Partial markup still helps. composer, send and answer on their own remove the hardest guesses.

Test it from the console

Paste this into the console on your page. It opens the AI assistant if there’s a launcher, then sends a question the way a client would:

document.querySelector('[data-assistant-hook="launcher"]')?.click();
const composer = document.querySelector('[data-assistant-hook="composer"]');
composer.focus();
document.execCommand('insertText', false, 'Hello.');
document.querySelector('[data-assistant-hook="send"]').click();

When the reply has finished, the newest answer reports its state:

[...document.querySelectorAll('[data-assistant-hook="answer"]')].at(-1).dataset.assistantState
// "complete"

Level 2: a small API §5

Level 2 is for clients that can run script in your page, such as browser extensions and agents. In Acme CRM it’s one file, assistant-hooks.js, loaded after Level 1:

window.assistantHooks = Object.freeze({
  version: '0.1',
  name: 'Acme AI',

  // Asks as if the user had typed `prompt` and pressed Send.
  // Resolves { ok: true, text } or { ok: false, error }. Never throws.
  async ask(prompt) {
    if (typeof prompt !== 'string' || !prompt.trim()) return { ok: false, error: 'unavailable' };
    try {
      return await submit(prompt.trim(), { via: 'level 2' });
    } catch (error) {
      return { ok: false, error: 'unavailable' };
    }
  },

  // The text of the newest complete answer, or null before there is one.
  async lastAnswer() {
    return lastAnswerText();
  },
});

ask goes through submit, the same function the Send button calls. A question asked through Level 2 therefore lands in the same conversation, waits behind a reply already in progress, is held to the same limits, and appears on screen as if it had been typed. Don’t build a second path to your backend for it.

Results are plain JSON, so they reach an extension intact. An extension calls ask like this:

const [{ result }] = await chrome.scripting.executeScript({
  target: { tabId },
  world: 'MAIN',
  func: (prompt) => window.assistantHooks?.ask(prompt) ?? { ok: false, error: 'unavailable' },
  args: [prompt],
});

world: 'MAIN' is needed because window.assistantHooks lives in the page’s own JavaScript, which an extension’s isolated world can’t see.

ask resolves when the answer is complete. A client that wants to show the answer while it streams reads the Level 1 markup in the meantime.

WebMCP

WebMCP is a browser proposal that lets a page offer tools to an agent running in the browser. Where the browser has it, Acme offers two, ask_assistant and get_last_response. RFC draft 0.1 names navigator.modelContext, but the current explainer has moved it to document.modelContext, so Acme checks both and does nothing where neither exists.

const modelContext = document.modelContext ?? navigator.modelContext;
if (typeof modelContext?.registerTool === 'function') {
  modelContext.registerTool({
    name: 'ask_assistant',
    description: 'Ask Acme AI, the assistant built into Acme CRM, a question about the deals and contacts in the CRM.',
    inputSchema: {
      type: 'object',
      properties: { prompt: { type: 'string' } },
      required: ['prompt'],
    },
    async execute(inputs) {
      const result = await window.assistantHooks.ask(inputs?.prompt);
      const text = result.ok ? result.text : `Acme AI couldn't answer: ${result.error}.`;
      return { content: [{ type: 'text', text }] };
    },
  });
}

get_last_response is registered the same way, and calls lastAnswer.

Errors §6

An error answer carries data-assistant-error, and ask returns the same code. Each code tells the user something different to do.

CodeMeaningThe user’s next stepWhat Acme AI says
auth_requiredSigned outSign in again“Acme AI needs you to sign in again before it can answer. Sign in, then ask again.”
rate_limitedToo many requestsWait, then ask again“Acme AI has had too many questions in a short time. Wait a minute, then ask again.”
not_entitledThe user’s plan doesn’t include the AI assistantAsk an admin“Your Acme plan doesn’t include Acme AI. Ask your admin to turn it on for you.”
refusedThe AI assistant declined to answerRephrase the question“Acme AI can’t help with that request. Try rephrasing it, or ask about your deals.”
unavailableAnything else went wrongTry again later“Acme AI isn’t available right now. Try again in a few minutes.”

Clients pass unknown codes on unchanged, and ignore hook names and states they don’t recognise, so your page can add its own without breaking anyone.

Mapping your backend’s errors

With a Claude key set, Acme maps the Anthropic API’s failures onto these codes:

When in doubt, use unavailable. A wrong auth_required sends someone off to sign in when signing in won’t help.

In Claude mode, the sentences for auth_required, not_entitled and unavailable talk about the API key and the connection instead, because those are what the user can fix.

Try it

To see an error without breaking anything, open Vendor view, choose a code under Errors and press “Fail the next reply”. The next question, typed or asked through Level 2, fails with that code.

Security §7

How Acme applies them

Checklist

Level 1

Level 2