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
- No hooks
?hooks=0What most AI assistants ship today. OpenPosse can still record it. - Level 1
?hooks=1The markup in §4: a hook on each control, and a state on each answer. - Level 2
?hooks=2Level 1, pluswindow.assistantHooksand two WebMCP tools. It’s the default.
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.
| Hook | Required | What it marks | In Acme CRM |
|---|---|---|---|
composer | Yes | Where a question is typed | The question box, assistant-composer |
send | Yes | The button that sends what’s in the composer | Send, assistant-send |
answer | Yes | Each reply, carrying its state | Each reply, assistant-answer |
answer-body | No | Inside an answer, just the answer’s text | assistant-answer-text. The Copy button sits outside it. |
launcher | No | What opens the AI assistant when the composer isn’t on the page | “Ask Acme AI” in the top bar |
stop | No | What cancels a reply in progress | Stop, 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.
| State | Means |
|---|---|
pending (optional) | Asked, and nothing has arrived yet |
streaming | Text is arriving |
complete | Your page treats the reply as done, usually at the moment it hides Stop or re-enables Send. Set it once. |
error | The reply failed. Add data-assistant-error with a code from §6. |
- The newest answer comes last in the page.
- The state goes on whichever element is the current answer. If your page swaps that element for another while it streams, set the state on the new one.
- A failure before any reply arrives still produces an
erroranswer. It may behiddenif your page shows the failure somewhere else. - A regenerated reply goes back to
pendingorstreaming. - Set
aria-busy="true"on the answer while it’s in progress and"false"after, so screen readers wait for the finished answer.
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
- Hooks must be reachable. Put them in the page, in an open shadow root or in a same-origin frame. A closed shadow root hides them.
- Marking an element is consent.
click()must work on it, and its handlers must not reject an event becauseisTrustedis false. - The composer takes inserted text. Focusing it, inserting text with
execCommand('insertText')and clickingsendmust send exactly that text. This is a test your page should pass, not an API you have to use. - Hooks are a public interface. Renaming or removing one is a version change.
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.
| Code | Meaning | The user’s next step | What Acme AI says |
|---|---|---|---|
auth_required | Signed out | Sign in again | “Acme AI needs you to sign in again before it can answer. Sign in, then ask again.” |
rate_limited | Too many requests | Wait, then ask again | “Acme AI has had too many questions in a short time. Wait a minute, then ask again.” |
not_entitled | The user’s plan doesn’t include the AI assistant | Ask an admin | “Your Acme plan doesn’t include Acme AI. Ask your admin to turn it on for you.” |
refused | The AI assistant declined to answer | Rephrase the question | “Acme AI can’t help with that request. Try rephrasing it, or ask about your deals.” |
unavailable | Anything else went wrong | Try 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:
- 401, or an
authentication_error, becomesauth_required - 403, or a
permission_error, becomesnot_entitled - 429, or a
rate_limit_error, becomesrate_limited - a
stop_reasonofrefusalbecomesrefused - anything else, such as a 500, a 529, a dropped connection or an empty reply, becomes
unavailable
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
- No credentials. Text goes in and text comes out. The sign-in stays in the browser’s cookies, and a client never sees a token.
- Nothing that wasn’t possible before. Hooks label elements that any script on the page can already reach, and
askdoes what such a script could already do by clicking. - Nothing is fetched. The hooks are part of the page the user already loaded. There’s no file to download and no new endpoint.
- The user decides. Clients use hooks only on sites the user has allowed them to act on.
- Answers are untrusted. A client never follows instructions found in answer text.
How Acme applies them
- Answers are written with
textContent, never as HTML, whichever source they come from. - Vendor view’s log holds event types and error codes, never a question or an answer.
- With a Claude key set, the page calls Anthropic directly with the visitor’s own key, the way your page calls your own backend. The key stays in the browser, outside every hook, and
askreturns only text.
Checklist
Level 1
<meta name="assistant-hooks" content="0.1">in the headcomposer,sendandansweron their elements, pluslauncher,stopandanswer-bodywhere your page has themdata-assistant-stateon each answer:streaming, thencompleteonce, orerrorwithdata-assistant-error- The newest answer last in the page
aria-busy="true"while a reply is in progress, and"false"after- A failed reply still produces an
erroranswer - The console test sends exactly the inserted text
Level 2
window.assistantHookswithversion,name,askandlastAnswerasktakes the same path as Send, and never throws- Every failure returns a §6 code
ask_assistantandget_last_responseoffered to WebMCP, only where the browser has it