JavaScript APIs injected into web pages for AI agent capabilities.
The Harbor extension injects these into every web page:
LanguageModel— Text generation, implementing the Prompt APIwindow.agent— Tools, browser access, and sessionsdocument.modelContext— The page's own tools, for the person's agent to call, implementing WebMCP
These APIs are gated by feature flags configured in Harbor's sidebar.
Building with an AI coding assistant? See LLMS.txt — a compact, token-efficient reference designed specifically for Claude, Cursor, Copilot, and other AI tools. It contains everything an AI assistant needs to write working code quickly.
- Quick Start
- Feature Flags
- Detecting the API
- LanguageModel API
- Writing Assistance, Proofreader and Translation APIs
- window.agent API
- Error Handling
- TypeScript Definitions
- Examples
<!DOCTYPE html>
<html>
<head>
<title>Web Agents API Demo</title>
</head>
<body>
<button id="ask">Ask AI</button>
<pre id="output"></pre>
<script>
document.getElementById('ask').onclick = async () => {
const output = document.getElementById('output');
// 1. Check if API is available
if (!self.LanguageModel || !window.agent) {
output.textContent = 'Web Agents API not available';
return;
}
// 2. Create session and prompt. create() asks you for the
// model:prompt grant itself, if this page doesn't already have
// it, and rejects with NotAllowedError on Deny.
try {
const session = await LanguageModel.create();
const response = await session.prompt('What is 2 + 2?');
output.textContent = response;
// 3. Clean up
session.destroy();
} catch (err) {
output.textContent = err.name === 'NotAllowedError' ? 'Permission denied' : err.message;
}
};
</script>
</body>
</html>A turned-off flag leaves its APIs present, but refusing: LanguageModel, window.agent and every member underneath it always exist, whatever the flags say. Users control the flags in the extension sidebar.
| Flag | Default | APIs Gated |
|---|---|---|
textGeneration |
✅ On | LanguageModel, Summarizer, Writer, Rewriter, Proofreader, Translator, LanguageDetector |
toolAccess |
✅ On | agent.mcp.register/discover/unregister (site MCP server registration) |
toolCalling |
✅ On | agent.run() |
browserInteraction |
❌ Off | agent.browser.activeTab.* (click, fill, scroll); activeTab.readability() also works under browserControl |
browserControl |
❌ Off | agent.browser.navigate(), agent.browser.tabs.*, agent.browser.fetch() |
Agentic Tool Use (toolCalling) is enabled by default when no saved value exists. Saved choices, including an explicit off setting, are preserved. Feature availability does not grant site permissions: model and tool requests still go through the existing permission checks. Browser interaction and browser control remain off by default.
When a feature is disabled, calling its APIs throws an error with code ERR_FEATURE_DISABLED (as a NotAllowedError DOMException on LanguageModel, which never uses Harbor's {code, message} shape). Harbor checks the setting again when the request arrives, so a page can't reach a disabled feature by messaging the extension directly. Prompts on an existing LanguageModel session are refused once textGeneration is off. The one exception is LanguageModel.availability(): with textGeneration off it resolves "unavailable", matching the Prompt API's own contract that availability() never rejects, rather than throwing ERR_FEATURE_DISABLED.
// LanguageModel and window.agent are there before your page's own first
// script runs, so a plain feature-detect works with no wait:
if (self.LanguageModel && window.agent) {
console.log('Web Agents API is available');
}
// To find out which features are currently enabled, read agent-ready's
// detail. It fires once the page has reached DOMContentLoaded (confirmed
// even if this script starts after that already happened, such as in a
// tab that was already open when Harbor installed or was enabled) and
// Harbor knows the person's real settings — whichever happens second —
// then again only when a setting actually changes.
//
// window.agent.capabilities().features reports the same thing
// synchronously, but can still read Harbor's defaults for a script that
// calls it before that first agent-ready: a script that runs very early
// should read capabilities() again inside its agent-ready listener,
// rather than trust a capabilities() call made before the event fired.
window.addEventListener('agent-ready', (event) => {
console.log('Version:', event.detail.version);
console.log('Features:', event.detail.features);
// { textGeneration: true, toolCalling: true, ... }
});window.addEventListener('agent-ready', (event) => {
const { features } = event.detail;
if (features.textGeneration) {
// Can use LanguageModel
}
if (features.toolCalling) {
// Can use agent.run()
}
if (features.browserControl) {
// Can use agent.browser.navigate(), tabs, fetch
}
});Harbor implements the Prompt API's LanguageModel for text generation, rather than a Harbor-specific API. The Prompt API spec is the reference for its shape (the Web IDL, availability(), create(), prompt(), promptStreaming(), append(), measureContextUsage(), clone(), destroy()); see spec/explainer.md for the full details and where Harbor differs from the spec (no image/audio, no tools, best-effort responseConstraint, contextWindow may be Infinity).
Chrome has its own LanguageModel, which runs Chrome's on-device model. Harbor is a polyfill, so it leaves Chrome's alone unless the person picked something else in Harbor:
- Chrome's model chosen, or nothing chosen: pages get Chrome's own
LanguageModel. Chrome answers, and Harbor isn't involved: no Harbor consent prompt, no Harbor record of the prompt. - Another backend chosen (the person's own agent, or a model Harbor reaches through the bridge): Harbor's
LanguageModelreplaces Chrome's on every page, runs on that choice, and asks before each site uses it.
A change applies to tabs when they next load. The sidebar's Run sites on setting says which case applies. Chrome's model is also a backend Harbor itself can use: once it's the default, window.agent and the sidebar run on it, on the device, with no bridge needed. It's text only, so agent.run() on it doesn't call tools.
Reports whether Harbor can answer. Needs no grant and never shows a prompt.
const availability = await LanguageModel.availability();
// 'unavailable' | 'downloadable' | 'downloading' | 'available'
if (availability !== 'unavailable') {
const session = await LanguageModel.create();
}Create a text generation session with conversation history. There's no model or provider option — the person picks what answers, in Harbor's sidebar, not the page. create() asks the person for the model:prompt grant itself if the page doesn't already have it, the same prompt agent.requestPermissions() shows; Deny, or a closed prompt, rejects with NotAllowedError.
const session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'You are a helpful assistant.' }],
});
// Simple prompt
const response = await session.prompt('Hello!');
console.log(response);
// Follow-up (maintains conversation context)
const followUp = await session.prompt('Tell me more');
// Streaming response. promptStreaming() returns a ReadableStream of plain
// string deltas, readable with for-await. A failure (such as
// NotAllowedError after the site's permission is revoked) is a
// DOMException, never Harbor's {code, message} shape.
try {
for await (const chunk of session.promptStreaming('Write a poem')) {
process.stdout.write(chunk);
}
} catch (err) {
console.error(err.name, err.message);
}
// Clean up when done
session.destroy();When the person has chosen their own agent instead of Harbor's built-in model, the session runs on that agent instead. There's no way for the page to tell which backend answered, or to list the backends available: that choice, and any listing of it, belongs to the person, in Harbor.
Harbor implements the Writing Assistance APIs' Summarizer, Writer and Rewriter, the Proofreader API's Proofreader, and the Translation API's Translator and LanguageDetector, the same way it implements LanguageModel: by the real specs' shapes, not a Harbor-specific API. All six run on the exact backend LanguageModel runs on (the person's chosen agent, or a model Harbor reaches through the bridge) and share its model:prompt grant — a page that already has model:prompt for LanguageModel doesn't see a second prompt for these.
Each is task-shaped rather than conversational: a call only sees its own create() options and that call's own input and context — Harbor never folds a previous call's input or output in itself. On the built-in model, that means no history at all: every call is exactly one system message plus one user message. On the person's own agent, Harbor still opens one ACP session per instance (so the agent sees Harbor's one steady identity, the way LanguageModel does) and phrases each call to it as its own independent task, not a turn in an ongoing conversation — but the agent itself keeps its own session/conversation state the way any ACP session does, and Harbor has no way to make it forget. So on that backend, a later call may still be colored by an earlier one through the agent's own memory of the session, even though Harbor itself sent it nothing but that call's own input.
In Chrome, each follows the exact same native-deferral rule as LanguageModel: a page that already has a native Summarizer/Writer/Rewriter/Proofreader/Translator/LanguageDetector keeps it, unless the person's chosen backend means Harbor's own should run instead, in which case all seven globals are replaced together.
// Summarizer
if ((await Summarizer.availability({ type: 'tldr' })) !== 'unavailable') {
const summarizer = await Summarizer.create({ type: 'tldr', format: 'plain-text', length: 'short' });
const summary = await summarizer.summarize(articleText, { context: 'A news article.' });
summarizer.destroy();
}
// Writer
const writer = await Writer.create({ tone: 'formal', length: 'medium' });
const draft = await writer.write('A short thank-you note to a colleague.');
writer.destroy();
// Rewriter
const rewriter = await Rewriter.create({ tone: 'more-casual' });
const casual = await rewriter.rewrite(formalParagraph);
rewriter.destroy();
// Proofreader
const proofreader = await Proofreader.create();
const { correctedInput, corrections } = await proofreader.proofread('I seen the dog yesterday.');
// corrections: [{ startIndex, endIndex, correction }, ...]
proofreader.destroy();
// Translator
const translator = await Translator.create({ sourceLanguage: 'en', targetLanguage: 'fr' });
const french = await translator.translate('Where is the train station?');
translator.destroy();
// LanguageDetector
const detector = await LanguageDetector.create();
const results = await detector.detect('Bonjour, comment allez-vous ?');
// results: [{ detectedLanguage: 'fr', confidence: 0.92 }, { detectedLanguage: 'und', confidence: 0.08 }]
detector.destroy();Summarizer, Writer and Rewriter also have summarizeStreaming()/writeStreaming()/rewriteStreaming() (each a ReadableStream<string> of plain-text deltas, readable with for await, matching LanguageModel.promptStreaming()), and measureInputUsage()/inputQuota (inputQuota is Infinity, matching LanguageModel.inputQuota, since there's no fixed context window to report).
Proofreader has no streaming call, no measureInputUsage()/inputQuota, no sharedContext, and no outputLanguage: the draft spec doesn't define any of these for it. Proofreading reads the whole input as one unit rather than a budget to measure against or a longer document to give running context for — and, unlike Summarizer/Writer/Rewriter, Proofreader's job is to correct the input's own language, not translate it, so there's no option to make it answer in a different one. outputLanguage isn't a declared member of Proofreader.create()'s options at all; Harbor ignores it if a page passes it, the same way a real WebIDL dictionary ignores a member it doesn't declare, and never lets it reach the model.
Proofreader's includeCorrectionTypes and includeCorrectionExplanations are not supported. A general-purpose model can't reliably classify a correction's grammatical type or explain its own correction the way a purpose-built proofreading model can, and Harbor would rather say so than guess. availability() reports 'unavailable' and create() rejects with NotSupportedError whenever either option is true. Harbor computes corrections itself, as a text diff between the input and the model's corrected text — so corrections are always exact spans that reproduce the corrected text when applied, but are a best-effort proofread from a general-purpose model, not a dedicated grammar checker's output. Expect it to miss or over-correct more than a purpose-built tool would, especially on a small local model. Proofreader also has its own correctionExplanationLanguage attribute (a single BCP 47 tag, null until set) — accepted and exposed for spec completeness, but it has no effect on anything Harbor does, since explanations are refused in the first place.
Translator's sourceLanguage and targetLanguage are required. create() rejects with TypeError if either is missing, and RangeError if either is malformed. Both must be well-formed BCP 47 tags, but Harbor places no other restriction on which pair — there's no fixed list of "supported" language pairs to check against, since the backend is a general model or agent, not a dedicated translation engine. An identity arc — sourceLanguage and targetLanguage naming the same language and script once each tag is maximized (so en-US → en-GB, or any tag to itself, counts, the same way the spec's own examples do; regional variants count as the same, but a script difference doesn't — zh-Hans → zh-Hant, Simplified to Traditional Chinese, is not an identity arc, since they're mutually unintelligible written forms) — is 'available' with no model or agent configured at all, as long as Text Generation itself is on (see below: that setting still gates it, like everything else these APIs answer), and translate()/translateStreaming() on one return the input unchanged without ever calling a model: there's nothing to translate. The same is true of empty or whitespace-only input, for any language pair. Consent and the usual permission/policy checks still apply in both cases, on every call, not just the first — Harbor never skips them just because a particular call happens not to need the model — and create() for an identity-arc Translator still opens a real agent session on the person's own backend, the same as any other instance. sourceLanguage/targetLanguage return exactly what the page passed in, uncanonicalized. The system prompt Harbor sends on a non-identity call names both languages, by tag and by their display name (via Intl.DisplayNames), and asks for the translation alone, with the input's formatting preserved — translation quality depends entirely on the backend, and a small local model will do noticeably worse than a frontier one or a capable agent.
LanguageDetector's expectedInputLanguages (a hint, not a restriction) is validated the same way the other APIs' own is: a well-formed BCP 47 tag list, null until set. detect() asks the backend for its own best guess as a small JSON object (a language tag mapped to a confidence number, for each language it considers, plus an "unknown" share) and Harbor then deterministically normalizes that reply into the spec's own result shape: malformed or non-numeric entries are dropped, duplicate tags that canonicalize to the same one are merged, every value is clamped to [0, 1] and rescaled so the language confidences plus unknown sum to exactly 1, then the spec's own result algorithm is applied unchanged (sorted by confidence, descending, stopping as soon as an entry scores zero, scores below unknown's own share, or cumulative confidence reaches 0.99), with { detectedLanguage: 'und', confidence: <unknown's share> } always appended last. A reply Harbor can't parse as that JSON shape at all becomes [{ detectedLanguage: 'und', confidence: 1 }] — "no idea" is itself an honest answer — and empty/whitespace-only input gets the same answer without ever asking the backend. detect() has no streaming form, matching the spec. As with Proofreader's corrections, detection quality is only as good as the backend: expect a small local model to be noticeably less reliable on short, ambiguous or mixed-language text than a frontier model or capable agent.
Any well-formed BCP 47 language tag is accepted for expectedInputLanguages, expectedContextLanguages, outputLanguage, correctionExplanationLanguage, sourceLanguage and targetLanguage — Harbor's backend is a general model, not a fixed set of supported languages, so there's no fixed allowlist to check against. A malformed tag rejects with the spec's own RangeError. outputLanguage (Summarizer/Writer/Rewriter only) is passed to the model as an instruction, not enforced structurally. expectedInputLanguages/expectedContextLanguages/outputLanguage/correctionExplanationLanguage are each null until the page sets them, per the specs.
All six follow the same Text Generation feature flag as LanguageModel, with no exception for a Translator identity arc or empty input: off, availability() always resolves 'unavailable', including for an identity arc (never rejects); everything else refuses, including a short-circuited translate()/translateStreaming()/detect() that would otherwise call no model at all — the setting gates the whole feature, not just the model round trip some calls happen to skip.
Tools, browser access, and sessions.
All agent capabilities require user permission. The permission system is per-origin — each website must request and be granted permissions separately.
Recommended for new code: call
agent.requestCapabilities()instead of the legacyrequestPermissionsflow. The new API operates in the same typed-action vocabulary as the policy engine, so what you ask for, what the user sees, and what the audit log records all line up. The full design is indocs/PERMISSIONS.md. The legacy flow below still works and is internally translated into the same engine calls, so existing pages keep running.
- Request: Your page calls
agent.requestPermissions()with desired scopes - Prompt: A permission dialog appears showing the origin, requested scopes, and optional reason
- User Choice: User can "Allow" (once or always) or "Deny"
- Storage: Grants are stored in the extension's local storage, keyed by origin
- Enforcement: All API calls check permissions before executing
Behind the scenes, every call from your page now flows through the
PolicyEngine, which evaluates the call against typed actions
(model.prompt.local, tool.call, browser.read.activeTab,
network.egress.cross_origin, etc.). Origin grants from requestPermissions are honored
at Tier 8 of the engine ladder; explicit deny rules in the user's
policy still win, and Tier 1–4 safety floors (managed denies,
sensitivity gates, information-flow checks, watchdog containment)
cannot be overridden by any grant. See
docs/PERMISSIONS.md for the full ladder.
| Grant Type | Lifetime | Use Case |
|---|---|---|
granted-always |
Persistent until revoked | Trusted sites the user visits frequently |
granted-once |
10 minutes, or until tab closes | One-time tasks, untrusted sites |
denied |
Persistent until revoked | User explicitly rejected |
not-granted |
N/A | Never requested, or expired |
Request permission scopes from the user. Shows a permission prompt if scopes aren't already granted.
The call waits up to 5 minutes for the person to answer, then rejects with ERR_TIMEOUT. If the page stops waiting first, because of that timeout or because the tab closes, Harbor discards the answer, so a late Allow grants nothing.
const result = await window.agent.requestPermissions({
scopes: [
'model:prompt', // Text generation
'model:tools', // Use AI with tools
'mcp:tools.list', // List available tools
'mcp:tools.call', // Execute tools
'browser:activeTab.read', // Read page content
],
reason: 'To help you with your task', // Shown in prompt
tools: ['time-wasm/time.now'] // Specific tools to allowlist
});
if (result.granted) {
console.log('All permissions granted');
} else {
// Check individual scopes
for (const [scope, grant] of Object.entries(result.scopes)) {
console.log(`${scope}: ${grant}`);
// grant is: 'granted-once' | 'granted-always' | 'denied' | 'not-granted'
}
}Options:
| Option | Type | Description |
|---|---|---|
scopes |
string[] |
Required. Permission scopes to request |
reason |
string |
Optional. Explanation shown in the permission prompt |
tools |
string[] |
Optional. Specific tools to add to the allowlist |
Response:
interface PermissionGrantResult {
granted: boolean; // true if ALL requested scopes were granted
scopes: Record<PermissionScope, PermissionGrant>; // Status per scope
allowedTools: string[]; // Tools the site may call; empty means none
}| Scope | Risk | Description |
|---|---|---|
model:prompt |
🟢 Low | Generate text using AI models (asked for by LanguageModel.create() itself) |
model:tools |
🟡 Medium | Use AI with tool calling (agentic loop) |
mcp:tools.list |
🟢 Low | List available MCP tools |
mcp:tools.call |
🟡 Medium | Execute MCP tools (may access external services) |
mcp:servers.register |
🟡 Medium | Register website MCP servers (BYOC) |
browser:activeTab.read |
🟡 Medium | Read content from the active tab |
browser:activeTab.interact |
🔴 High | Click, fill forms, scroll on active tab |
browser:activeTab.screenshot |
🟡 Medium | Capture screenshots of the active tab |
browser:tabs.read |
🟡 Medium | List browser tabs |
browser:tabs.create |
🔴 High | Open tabs on any site and close them; read them only while they show your own origin's pages |
chat:open |
🟢 Low | Open the chat sidebar |
web:fetch |
🔴 High | Fetch URLs bypassing CORS |
When requesting mcp:tools.call, you can specify which tools to allowlist:
// Request permission for specific tools only
const result = await window.agent.requestPermissions({
scopes: ['mcp:tools.call'],
tools: ['time-wasm/time.now', 'memory/save'],
reason: 'To check the time and save notes'
});
// The permission prompt shows checkboxes for each tool
// User can deselect tools they don't want to allow
console.log('Allowed tools:', result.allowedTools);If tools are specified, the permission prompt displays each tool with a checkbox, allowing users to grant access to specific tools only.
The recommended replacement for requestPermissions. Creates a session
for the capabilities you ask for. Model and browser access need the
matching origin grant first (model:prompt, or browser:activeTab.read,
.interact or .screenshot); without one the call fails instead of
asking for it.
Sessions carry LLM and browser capabilities only — there's no session
tool capability. To use the person's installed tools, start agent.run()
instead.
const session = await window.agent.requestCapabilities({
name: 'Article assistant',
reason: 'Read the page and propose follow-ups.',
require: [
{ action: 'model.prompt.local' },
{ action: 'browser.read.activeTab' },
],
optional: [
{ action: 'network.egress.cross_origin' },
],
budget: { ttlMinutes: 15 },
});
// Use the session like any other.
const reply = await session.prompt('What should I read next?');Behind the scenes the request becomes a session.create call; the
engine grants the intersection of what the user has granted, what
your require list asks for, and what your origin policy allows.
To get more authority later — e.g. write access after the user
clicks "Apply" — ask for the grant with agent.requestPermissions(), which shows
the user a prompt, then call agent.requestCapabilities() again for
a new session. requestCapabilities() doesn't ask for grants; it only prompts when
a policy rule or a watchdog restriction calls for it. The
new session is independent; the original session continues with its
narrower scope. Terminate a session when you're done with it.
For the full design, see
docs/PERMISSIONS.md.
Get current permission status for this origin.
const status = await window.agent.permissions.list();
console.log('Origin:', status.origin);
console.log('Scopes:', status.scopes);
console.log('Allowed tools:', status.allowedTools);
// Example output:
// {
// origin: 'https://example.com',
// scopes: {
// 'model:prompt': 'granted-always',
// 'mcp:tools.list': 'granted-once',
// 'mcp:tools.call': 'denied'
// },
// allowedTools: ['time-wasm/time.now']
// }- Request minimal scopes: Only request permissions you actually need
- Provide a reason: Explain why you need each capability
- Handle denial gracefully: Provide fallback functionality when permissions are denied
- Check before calling: Use
permissions.list()to check status before making API calls - Re-request when needed: If a
granted-oncepermission expires, request it again
// Example: Graceful permission handling
async function summarizePage() {
// Check current permissions
const { scopes } = await window.agent.permissions.list();
if (scopes['browser:activeTab.read'] !== 'granted-always' &&
scopes['browser:activeTab.read'] !== 'granted-once') {
// Request permission with explanation
const result = await window.agent.requestPermissions({
scopes: ['model:prompt', 'browser:activeTab.read'],
reason: 'To read and summarize this page'
});
if (!result.granted) {
// Fallback: let user paste content manually
return promptUserToPasteContent();
}
}
// Permission granted, proceed
const content = await window.agent.browser.activeTab.readability();
const session = await LanguageModel.create();
return session.prompt(`Summarize: ${content.text}`);
}Harbor names the requesting site and highlights the reason it supplied. When a site asks to use a selected agent, Harbor names that agent and explains its access to tools and memory. Requests for other capabilities list the scopes involved. Requested tools can be selected individually.
The person can deny the request, allow it for ten minutes, or grant ongoing access using a separate action below the temporary choice. They can revoke the decision in the sidebar.
- Origin Isolation: Permissions are scoped to the requesting origin (scheme + host + port)
- User Consent: Every permission requires explicit user action in the prompt
- Revocation: Users can revoke permissions at any time via the extension sidebar. On Harbor's built-in model, a running
agent.runsees a revoked or expired grant, or a narrowed tool allowlist, on its next model turn - Expiration:
granted-oncepermissions expire after 10 minutes or when the tab closes - Tool Filtering: Even with
mcp:tools.call, tools must be in the allowlist to be called - No Silent Grants: There's no way to bypass the permission prompt
Users can manage permissions through the extension sidebar:
- View granted permissions: See all origins with active permissions
- Revoke by origin: Remove all permissions for a specific website
- Revoke all: Clear all permissions across all websites
- View tool allowlists: See which tools each origin can access
There is no agent.tools.list() or agent.tools.call(). A page reaches
its own tools through WebMCP (document.modelContext, below). A page
cannot list or call the person's installed MCP tools (from connected
servers) directly — only the person's agent does, inside agent.run()
(gated by mcp:tools.list and mcp:tools.call, plus the origin's tool
allowlist) or agent.chat.open() on the person's own agent.
// Ask the agent to use an installed tool on your behalf
for await (const event of window.agent.run({
task: 'What time is it in New York?',
})) {
if (event.type === 'tool_result') console.log('Current time:', event.result);
}Pages can register JavaScript functions as "page tools" that appear alongside MCP tools. Page tools execute in the page context. The person's agent can call them too (see Page tools and the person's agent).
Registration API: document.modelContext, as in the WebMCP draft. There's no navigator.modelContext, addTool or removeTool. It's the same object every time you read document.modelContext. A document other than the page's own — from document.implementation.createHTMLDocument(), say — gets its own, inert modelContext: registerTool(), getTools() and executeTool() reject, and waitForToolsUntil() throws, all with InvalidStateError.
Register a page tool. Returns a promise that resolves to undefined.
const registration = new AbortController();
await document.modelContext.registerTool({
name: 'get_cart_items',
description: 'Returns the current shopping cart contents',
inputSchema: {
type: 'object',
properties: {
includeMetadata: { type: 'boolean', description: 'Include product metadata' }
}
},
execute: async (input, { signal }) => {
const items = document.querySelectorAll('.cart-item');
return Array.from(items).map(el => ({
name: el.querySelector('.name')?.textContent,
price: el.querySelector('.price')?.textContent,
}));
},
}, { signal: registration.signal });
// Later: unregister by aborting the signal you registered with
registration.abort();| Field | Required | Notes |
|---|---|---|
name |
yes | 1–128 ASCII letters, digits, _, - or . |
description |
yes | Must not be empty or only whitespace |
title |
no | A human-readable name, passed to the agent as MCP's title. getTools() reports "" if you didn't give one |
inputSchema |
no | JSON Schema for the input |
outputSchema |
no | JSON Schema for the result. Passed to the agent only when its type is "object", as MCP requires; return a matching object |
annotations |
no | The spec's four tool hints: readOnlyHint, untrustedContentHint, consequentialHint, debugging, each converted to a boolean. If you give annotations at all — even {} — getTools() reports all four, defaulting any you didn't set to false; if you don't give it, getTools() reports null. They inform the person's agent. An agent on the official MCP TypeScript SDK (@modelcontextprotocol/sdk) keeps only readOnlyHint as a field, so Harbor's ACP endpoint also states the other three in the tool's description (see PAGE_TOOLS_FOR_AGENTS.md); Harbor's own permission and policy checks ignore them (debugging in particular grants nothing) |
execute(input, { signal }) |
yes | Required; there is no handler alias |
A title or outputSchema of the wrong type is left out; the tool still registers. Registering, and later unregistering, each fire a toolchange event on document.modelContext. The promise settles in a later task — not within the same microtask — so aborting the signal right after the call still rejects it with the signal's reason.
The promise rejects with:
InvalidStateErrorfor a duplicate name, an invalid name, or a description that is empty or only whitespace.TypeErrorwhenexecuteis missing, or wheninputSchema/outputSchemais present but not an object.- the signal's abort reason when
options.signalis already aborted. SecurityErrorfor anoptions.exposedToentry that isn't a valid URL, or whose origin isn't potentially trustworthy. A valid, trustworthy entry is accepted and has no effect: Harbor's polyfill runs in the top frame only, so there's no other frame to expose a tool to.
Resolves to this document's own tools, sorted by name, as Tool objects (name, title, description, inputSchema, outputSchema, source, origin, annotations).
const tools = await document.modelContext.getTools();
console.log(`${tools.length} page tools registered`);A non-empty options.fromOrigins adds nothing: Harbor's polyfill runs in the top frame only, so no other frame is reachable and the result is the same either way. An entry that isn't a valid, potentially trustworthy origin rejects the whole call with SecurityError.
Runs a tool the page itself registered, returning a promise that resolves to the JSON string of its result. This is the page calling its own code, so it needs no Harbor permission.
const [tool] = await document.modelContext.getTools();
const result = await document.modelContext.executeTool(tool, { includeMetadata: true });inputObject can be any object, arrays included — accepts { anchor: 'p3' } or [1, 2, 3] alike. Rejects with NotFoundError if the tool isn't currently registered in this document, TypeError if inputObject isn't an object (a string, number, boolean or null) or can't be turned into JSON (a circular structure, or a toJSON() that returns undefined), and OperationError if execute rejects or its result can't be serialized. DataError is reserved for the one case those checks don't already cover: an object whose JSON form, once parsed back, isn't itself an object — a boxed new Number(1), say, which serializes to "1".
Aborting options.signal before execute even starts rejects promptly with the abort reason; no toolcancel fires, since the execution never started. Aborting mid-call rejects with the abort reason first, then aborts the execute call's own signal with an AbortError DOMException (not your raw abort reason — that's what the rejection itself carries), then fires toolcancel.
While promise is pending, Harbor holds off syncing the agent-facing tool list, so a page that registers several tools across a microtask or two doesn't flicker through a partial list. There's a single 10-second deadline, counted from your first outstanding call — a later call while one is already pending can't push that deadline out. Omitting the argument throws TypeError. Returns undefined.
ontoolchange fires after each registration and unregistration. ontoolactivated (a ToolActivatedEvent carrying toolName) fires for every tool execution — the person's agent calling a page tool, and your own executeTool() alike — right as it starts, not once it settles. ontoolcancel (a ToolCancelEvent carrying toolName) fires when the person's agent's call to a page tool is cancelled, and on an executeTool() abort.
The WebMCP draft also describes inferring tools from <form> markup. That part of the draft isn't implemented here; Harbor supports only the imperative registerTool() call above.
const tools = await document.modelContext.getTools();
// → [{ name: 'get_cart_items', description: '...', ... }]const cart = await document.modelContext.executeTool('get_cart_items', { includeMetadata: true });Page tool errors produce ERR_TOOL_FAILED errors, matching the behavior of MCP tool errors, when the person's agent calls them during agent.run() or agent.chat.open().
A page's tools also reach the agent work that page starts: agent.run(), and agent.chat.open() when the person has chosen their own agent. Page chat on Harbor's built-in model sends each message straight to the model, with no tools. The handlers still run in the page; only each tool's name, description and input schema leave it, plus its title, outputSchema and annotations when the page sets them.
- Harbor's built-in agent sees them in
agent.run()aspage:<host>/<tool>, beside Harbor's installed tools. - The person's own ACP agent (goose, Claude Code, Codex) gets them as an MCP server named after the site's host (for example
tale.example), alongside the tools of the site's registered MCP servers (as<server>__<tool>), which Harbor serves on127.0.0.1for that session only. The agent needs to support HTTP MCP servers. - No grant of their own. The grant that lets the page start the run or chat covers them.
mcp:tools.listandmcp:tools.callaren't needed, since those would also open the person's own MCP servers. A policy rule can still refuse them (tool.listortool.callon thepage:<host>server), and every check is in the audit log. - Lifetime. Tools last as long as the page's document. A reload or real navigation drops them, and a call in flight then fails with
ERR_TOOL_FAILED. A same-document hash orpushStatechange keeps them. A call also fails withERR_TOOL_FAILEDwhen the handler throws (its message is passed on), the result is over 1 MB, or the page doesn't answer within 60 seconds. Calls are never retried. - Budget. An
agent.run'smaxToolCallscounts page tool calls too. - Untrusted output. A tool's result reaches the agent as tool output only, never as instructions. An object result is also sent to an ACP agent as MCP
structuredContent. LanguageModelsessions never get page tools.
The page sends its current list before agent.run() or agent.chat.open(), so tools registered just before the call are included. A page that registers no tools sends nothing. See PAGE_TOOLS_FOR_AGENTS.md for the design.
Run an AI agent that can use tools to accomplish tasks.
Requires: toolCalling feature flag enabled
Execute an autonomous agent task. Returns an async iterator of events.
maxToolCalls (default 5) caps the tool calls for the whole run, even when the model asks for several in one turn; calls past it don't run, and the model is told. A turn whose tool calls are refused because the site lacks mcp:tools.call also counts as one. When the budget is spent, the model gives a final answer without tools.
When the person has chosen their own agent (over the Agent Client Protocol) instead of Harbor's built-in model, maxToolCalls is ignored: the agent decides how many tools to use.
for await (const event of window.agent.run({
task: 'What is the current time in Tokyo?',
maxToolCalls: 5,
systemPrompt: 'You are a helpful assistant.'
})) {
switch (event.type) {
case 'thinking':
console.log('[Thinking]', event.content);
break;
case 'tool_call':
console.log(`[Tool] Calling ${event.tool}`, event.args);
break;
case 'tool_result':
console.log(`[Tool] Result from ${event.tool}:`, event.result);
break;
case 'final':
console.log('[Answer]', event.output);
break;
case 'error':
console.error('[Error]', event.error.code, event.error.message);
break;
}
}Event Types:
| Type | Properties | Description |
|---|---|---|
thinking |
content |
Agent's reasoning process |
tool_call |
tool, args |
Tool being called |
tool_result |
tool, result |
Tool execution result |
final |
output |
Final response |
error |
error ({ code, message }) |
The run failed and is over |
agent.run() doesn't throw when a run fails. Every failure arrives as one error event, after which the run ends: a refusal before it starts (for example, ERR_PERMISSION_DENIED without model:prompt), the site's permission being revoked partway through, Harbor's policy engine refusing the tool list or, on Harbor's own model, a model call (ERR_BLOCKED_BY_POLICY, ERR_QUARANTINED), or a model call failing (ERR_MODEL_FAILED).
Create explicit sessions with LLM and browser capabilities and a TTL.
Sessions carry no tool capability; use agent.run() to call tools.
Create a session with defined capabilities.
const session = await window.agent.sessions.create({
name: 'Research Assistant',
reason: 'To help research this topic',
capabilities: {
llm: { provider: 'ollama', model: 'llama3.2' },
browser: ['read', 'screenshot']
},
limits: {
ttlMinutes: 30
},
options: {
systemPrompt: 'You are a research assistant.',
temperature: 0.3
}
});
// Use the session
const response = await session.prompt('Find information about AI safety');
console.log(response);
// Streaming
for await (const token of session.promptStreaming('Summarize your findings')) {
process.stdout.write(token);
}
// Clean up
await session.terminate();When the person has chosen their own agent instead of Harbor's built-in model, prompt() and promptStreaming() run on that agent, and capabilities.llm's provider, model and temperature are ignored. They don't limit the agent's own tools while it answers a prompt: those are the agent's, under its own settings. If the person switches agents, or switches back to the built-in model, a session with model access ends: a prompt gets ERR_SESSION_NOT_FOUND, and it no longer appears in agent.sessions.list(). Create a new one. Like any session, one that expires or sits idle for an hour ends, and so does its agent.
List active sessions.
const sessions = await window.agent.sessions.list();
for (const s of sessions) {
console.log(`${s.name || s.sessionId} (${s.status})`);
console.log(` Type: ${s.type}`); // always 'explicit' — only agent.sessions.create() sessions are listed here
console.log(` Created: ${new Date(s.createdAt)}`);
console.log(` Usage: ${s.usage.promptCount} prompts`);
}Get a specific session.
const session = await window.agent.sessions.get('session-id-here');
if (session) {
console.log('Status:', session.status);
}Terminate a session.
const terminated = await window.agent.sessions.terminate('session-id-here');
console.log('Terminated:', terminated);Control and read from browser tabs.
A stopgap, not part of the proposal. These calls click, fill and navigate under the person's login, so a site can't tell the agent's actions from the person's. They exist until sites expose what agents need as page tools (
document.modelContext.registerTool()), which arrive on their own channel. Prefer page tools, and don't build new designs on these calls. Both feature flags are off by default.
Interact with the current tab. Requires: browserInteraction feature flag.
// Get readable content from the page
const content = await window.agent.browser.activeTab.readability();
console.log('Title:', content.title);
console.log('Content:', content.text);
// Get interactive elements
const elements = await window.agent.browser.activeTab.getElements();
for (const el of elements) {
console.log(`[${el.ref}] ${el.role}: ${el.text || el.placeholder || ''}`);
}
// Click an element
await window.agent.browser.activeTab.click('ref-123');
// Fill a form field
await window.agent.browser.activeTab.fill('ref-456', 'Hello world');
// Select dropdown option
await window.agent.browser.activeTab.select('ref-789', 'option-value');
// Scroll the page
await window.agent.browser.activeTab.scroll('down', 500); // direction, amount
// Take a screenshot
const { dataUrl } = await window.agent.browser.activeTab.screenshot();
document.getElementById('preview').src = dataUrl;screenshot() captures the calling page only. It fails with ERR_PERMISSION_DENIED unless the calling tab is the one showing in its window, for example when the page is in a background tab.
Tabs open in the calling tab’s window by default. An explicit destination window must have the same private-browsing state. Firefox also preserves the calling tab’s cookie store, including its container. Harbor refuses tab creation if it cannot preserve that context. On Chrome, regular tabs open in a regular window and requests from incognito tabs are refused.
Navigate and manage tabs. Requires: browserControl feature flag.
// Navigate to a URL
await window.agent.browser.navigate('https://example.com');
// List all tabs
const tabs = await window.agent.browser.tabs.list();
for (const tab of tabs) {
console.log(`[${tab.id}] ${tab.title} - ${tab.url}`);
console.log(` Active: ${tab.active}, Can control: ${tab.canControl}`);
}
// Create a new tab. You can open any site, but you can read the tab only
// while it shows a page on your own origin.
const newTab = await window.agent.browser.tabs.create({
url: `${location.origin}/report`,
active: false
});
// Wait for tab to load
await window.agent.browser.tab.waitForLoad(newTab.id, { timeout: 10000 });
// Read content from spawned tab
const tabContent = await window.agent.browser.tab.readability(newTab.id);
console.log('Page content:', tabContent.text);
// Get HTML from spawned tab
const { html } = await window.agent.browser.tab.getHtml(newTab.id, 'main');
// Close the tab
await window.agent.browser.tabs.close(newTab.id);
// Fetch URL (bypasses CORS)
const response = await window.agent.browser.fetch('https://api.example.com/data', {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
console.log('Status:', response.status);
console.log('Body:', response.body);All of window.agent's APIs throw errors with consistent codes ({ code, message }). LanguageModel is the exception: it throws a DOMException, as the Prompt API spec requires, so check err.name, not err.code — see the mapping in spec/explainer.md.
try {
await document.modelContext.executeTool(tool, input);
} catch (err) {
switch (err.code) {
case 'ERR_FEATURE_DISABLED':
console.log('Enable the feature in extension settings');
break;
case 'ERR_PERMISSION_DENIED':
console.log('User denied permission');
break;
case 'ERR_TIMEOUT':
console.log('Request timed out');
break;
case 'ERR_HARBOR_NOT_FOUND':
console.log('Harbor extension not installed');
break;
default:
console.error('Unexpected error:', err.message);
}
}Error Codes:
General
| Code | Description |
|---|---|
ERR_PERMISSION_DENIED |
User denied permission, or declined Harbor's prompt for this call — including a missing scope Harbor asked about and the person declined (or couldn't be asked) |
ERR_FEATURE_DISABLED |
Feature flag is off |
ERR_BLOCKED_BY_POLICY |
A policy rule denied the call (see PERMISSIONS.md) |
ERR_QUARANTINED |
Harbor has quarantined this site; every call is refused until the user resets it |
ERR_LABEL_FLOW_BLOCKED |
The policy engine's information-flow check: the call carries a data label (credentials, payments, ...) the destination doesn't accept |
ERR_UNKNOWN_ACTION |
The policy engine doesn't know the requested action, so it refuses it |
ERR_HARBOR_NOT_FOUND |
Harbor extension not found |
ERR_TIMEOUT |
Request timed out |
ERR_ABORTED |
The page aborted an agent.run or a LanguageModel prompt, its tab closed, or its port disconnected |
ERR_INVALID_REQUEST |
The request was missing a required parameter or otherwise malformed |
ERR_INTERNAL |
Internal error |
ERR_NOT_IMPLEMENTED |
The requested method isn't implemented |
ERR_ELEMENT_NOT_FOUND |
A browser automation call (click, fill, select) couldn't find the target element |
Tools, models and sessions
| Code | Description |
|---|---|
ERR_TOOL_FAILED |
Tool execution failed, its handler threw, or it didn't answer within 60 seconds |
ERR_MODEL_FAILED |
LLM request failed |
ERR_SESSION_NOT_FOUND |
Session was destroyed |
ERR_NOT_SUPPORTED |
LanguageModel.create(): neither Harbor's built-in model nor an agent can answer (LanguageModel.availability() would report "unavailable") |
Agents
| Code | Description |
|---|---|
ERR_AGENT_FAILED |
The agent loop running agent.run, or a LanguageModel session on the ACP backend, failed — a model call, or (on the ACP backend) a transport failure, an agent exit before it answered, or a JSON-RPC error |
ERR_AGENT_REFUSED |
An ACP agent's turn ended with stopReason: "refusal" |
ERR_AGENT_LIMIT |
An ACP agent's turn ended with stopReason: "max_tokens" or "max_turn_requests" |
ERR_AGENT_BUSY |
Too many ACP agents are already running: this site's own cap (2 at once, counting agent.run and LanguageModel sessions together), or the person's bridge-wide limit |
Chat and MCP
| Code | Description |
|---|---|
ERR_CHAT |
agent.chat call failed for a reason other than policy |
ERR_CHAT_OPEN |
agent.chat.open failed for a reason other than policy |
ERR_CHAT_CLOSE |
agent.chat.close failed for a reason other than policy |
ERR_MCP_DISCOVER |
agent.mcp.discover failed for a reason other than policy |
ERR_MCP_REGISTER |
agent.mcp.register failed for a reason other than policy |
ERR_MCP_UNREGISTER |
agent.mcp.unregister failed for a reason other than policy |
// Feature flags
interface FeatureFlags {
textGeneration: boolean;
toolCalling: boolean;
toolAccess: boolean;
browserInteraction: boolean;
browserControl: boolean;
}
// Permission types
type PermissionScope =
| 'model:prompt'
| 'model:tools'
| 'mcp:tools.list'
| 'mcp:tools.call'
| 'mcp:servers.register'
| 'browser:activeTab.read'
| 'browser:activeTab.interact'
| 'browser:activeTab.screenshot'
| 'chat:open'
| 'web:fetch';
type PermissionGrant = 'granted-once' | 'granted-always' | 'denied' | 'not-granted';
interface PermissionGrantResult {
granted: boolean;
scopes: Record<PermissionScope, PermissionGrant>;
allowedTools?: string[];
}
// LanguageModel's own types come from the Prompt API spec, not from Harbor —
// see spec/explainer.md#languagemodel-prompt-api for its Web IDL.
// Tools
interface ToolDescriptor {
name: string;
description?: string;
inputSchema?: Record<string, unknown>;
serverId?: string;
}
// Agent run events
type AgentRunEvent =
| { type: 'thinking'; content: string }
| { type: 'tool_call'; tool: string; args: Record<string, unknown> }
| { type: 'tool_result'; tool: string; result: unknown }
| { type: 'final'; output: string }
| { type: 'error'; error: string };
// Session capabilities (LLM and browser only — no tool capability)
interface SessionCapabilities {
llm: { allowed: boolean; provider?: string; model?: string };
browser: { readActiveTab: boolean; interact: boolean; screenshot: boolean };
limits?: { expiresAt?: number };
}
interface AgentSession {
readonly sessionId: string;
readonly capabilities: SessionCapabilities;
prompt(input: string): Promise<string>;
promptStreaming(input: string): AsyncIterable<string>;
terminate(): Promise<void>;
}
// Browser APIs
interface ReadabilityContent {
url: string;
title: string;
text: string; // main text, line breaks kept, at most 50,000 characters
}
interface BrowserElement {
ref: string;
role: string;
text?: string;
placeholder?: string;
value?: string;
checked?: boolean;
rect?: { x: number; y: number; width: number; height: number };
}
// Global declarations
declare global {
// LanguageModel is declared by the Prompt API spec, not here.
interface Window {
agent: {
requestPermissions(options: {
scopes: PermissionScope[];
reason?: string;
tools?: string[];
}): Promise<PermissionGrantResult>;
permissions: {
list(): Promise<PermissionStatus>;
};
tools: {
list(): Promise<ToolDescriptor[]>;
call(options: { tool: string; args?: Record<string, unknown> }): Promise<unknown>;
};
run(options: {
task: string;
maxToolCalls?: number;
systemPrompt?: string;
}): AsyncIterable<AgentRunEvent>;
sessions: {
create(options: CreateSessionOptions): Promise<AgentSession>;
get(sessionId: string): Promise<SessionSummary | null>;
list(): Promise<SessionSummary[]>;
terminate(sessionId: string): Promise<boolean>;
};
browser: {
activeTab: {
readability(): Promise<ReadabilityContent>;
getElements(): Promise<BrowserElement[]>;
click(ref: string): Promise<{ success: boolean }>;
fill(ref: string, value: string): Promise<{ success: boolean }>;
scroll(direction: 'up' | 'down' | 'left' | 'right', amount?: number): Promise<{ success: boolean }>;
select(ref: string, value: string): Promise<{ success: boolean }>;
screenshot(): Promise<{ dataUrl: string }>;
};
navigate(url: string): Promise<{ success: boolean }>;
fetch(url: string, options?: RequestInit): Promise<{ body: string; status: number; headers: Record<string, string> }>;
tabs: {
list(): Promise<TabInfo[]>;
create(options: { url: string; active?: boolean }): Promise<TabInfo>;
close(tabId: number): Promise<boolean>;
};
tab: {
readability(tabId: number): Promise<ReadabilityContent>;
getHtml(tabId: number, selector?: string): Promise<{ html: string; url: string; title: string }>;
waitForLoad(tabId: number, options?: { timeout?: number }): Promise<void>;
};
};
};
}
interface WindowEventMap {
'agent-ready': CustomEvent<{
version: string;
languageModelDetected: boolean;
features: FeatureFlags;
}>;
}
}<!DOCTYPE html>
<html>
<head>
<title>Simple Chat</title>
<style>
#chat { max-width: 600px; margin: 20px auto; font-family: sans-serif; }
#messages { height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; }
.user { color: blue; }
.assistant { color: green; }
#input { width: 100%; padding: 10px; margin-top: 10px; }
</style>
</head>
<body>
<div id="chat">
<div id="messages"></div>
<input id="input" placeholder="Type a message..." />
</div>
<script>
const messages = document.getElementById('messages');
const input = document.getElementById('input');
let session = null;
function addMessage(role, text) {
const div = document.createElement('div');
div.className = role;
div.textContent = `${role}: ${text}`;
messages.appendChild(div);
messages.scrollTop = messages.scrollHeight;
}
async function init() {
if (!self.LanguageModel) {
addMessage('system', 'Web Agents API not available');
return;
}
// create() asks for the model:prompt grant itself, if this page
// doesn't already have it, and rejects with NotAllowedError on Deny.
try {
session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'You are a helpful assistant. Keep responses concise.' }],
});
addMessage('system', 'Ready to chat!');
} catch (err) {
addMessage('system', err.name === 'NotAllowedError' ? 'Permission denied' : err.message);
}
}
input.addEventListener('keydown', async (e) => {
if (e.key === 'Enter' && session && input.value.trim()) {
const userMessage = input.value.trim();
input.value = '';
addMessage('user', userMessage);
// Streaming response
const responseDiv = document.createElement('div');
responseDiv.className = 'assistant';
responseDiv.textContent = 'assistant: ';
messages.appendChild(responseDiv);
for await (const token of session.promptStreaming(userMessage)) {
responseDiv.textContent += token;
messages.scrollTop = messages.scrollHeight;
}
}
});
init();
</script>
</body>
</html><!DOCTYPE html>
<html>
<head>
<title>Tool Agent</title>
</head>
<body>
<h1>Time Agent</h1>
<button id="ask">What time is it?</button>
<pre id="output"></pre>
<script>
document.getElementById('ask').onclick = async () => {
const output = document.getElementById('output');
output.textContent = 'Working...\n';
try {
// Request permissions
await window.agent.requestPermissions({
scopes: ['model:tools', 'mcp:tools.list', 'mcp:tools.call'],
reason: 'To check the time'
});
// Run agent
for await (const event of window.agent.run({
task: 'What is the current time?',
maxToolCalls: 3
})) {
if (event.type === 'tool_call') {
output.textContent += `Calling: ${event.tool}\n`;
}
if (event.type === 'tool_result') {
output.textContent += `Result: ${JSON.stringify(event.result)}\n`;
}
if (event.type === 'final') {
output.textContent += `\nAnswer: ${event.output}`;
}
}
} catch (err) {
output.textContent = `Error: ${err.message}`;
}
};
</script>
</body>
</html><!DOCTYPE html>
<html>
<head>
<title>Page Summarizer</title>
</head>
<body>
<h1>Summarize Current Page</h1>
<button id="summarize">Summarize</button>
<div id="summary"></div>
<script>
document.getElementById('summarize').onclick = async () => {
const summaryDiv = document.getElementById('summary');
summaryDiv.textContent = 'Reading page...';
try {
// Request permissions
await window.agent.requestPermissions({
scopes: ['model:prompt', 'browser:activeTab.read'],
reason: 'To summarize this page'
});
// Get page content
const content = await window.agent.browser.activeTab.readability();
summaryDiv.textContent = `Title: ${content.title}\nAnalyzing...`;
// Create session and summarize
const session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'Summarize the following text in 2-3 sentences.' }],
});
summaryDiv.textContent = `Title: ${content.title}\n\nSummary: `;
for await (const chunk of session.promptStreaming(content.text)) {
summaryDiv.textContent += chunk;
}
session.destroy();
} catch (err) {
summaryDiv.textContent = `Error: ${err.message}`;
}
};
</script>
</body>
</html>- Developer Guide — Full Harbor developer guide
- Sessions Guide — When to use
LanguageModelvsagent.sessions - JS API Reference — Detailed API reference
- Demo Code — Working examples
Version: Web Agents API v1.0