Repository navigation
Expand file tree
/
Copy pathLLMS.txt
More file actions
576 lines (445 loc) · 20.9 KB
/
Copy pathLLMS.txt
File metadata and controls
576 lines (445 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# Harbor Web Agent API - Reference for AI Coding Assistants
> **WHAT THIS IS**: A compact, token-efficient reference for Claude, Cursor, Copilot, or any AI assistant building web apps with the Web Agent API. This doc matches `extension/src/page-api/injected.ts` exactly — if it's not here, it isn't shipped.
>
> **HUMAN DOCS**: For prose explanations, see `docs/WEB_AGENTS_API.md`, `docs/BUILDING_ON_HARBOR.md`, and `docs/AGENTIC_BROWSER_ROADMAP.md`.
---
## TL;DR - Copy This to Start
```javascript
if (!window.agent) throw new Error('Web Agents API not available');
// 1. Feature-detect (synchronous, no permission needed)
const caps = window.agent.capabilities();
if (!caps.features.textGeneration) throw new Error('Text generation disabled');
// 2. Request permissions (REQUIRED before any API use)
const { granted } = await window.agent.requestPermissions({
scopes: ['model:prompt', 'mcp:tools.list', 'mcp:tools.call'],
reason: 'Enable AI features'
});
if (!granted) throw new Error('Permissions denied');
// 3. Use text generation — create() asks for model:prompt itself if you
// skipped step 2 for it; LanguageModel is the Prompt API's own global.
const session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'Be helpful.' }],
});
const response = await session.prompt('Hello!');
session.destroy();
// 4. Or run an autonomous agent (requires toolCalling flag)
if (caps.features.toolCalling) {
for await (const ev of window.agent.run({ task: 'Search for AI news' })) {
if (ev.type === 'final') console.log(ev.output);
}
}
```
---
## Global Objects
| Object | Purpose |
|--------|---------|
| `LanguageModel` | Text generation, implementing the [Prompt API](https://webmachinelearning.github.io/prompt-api/) |
| `window.agent` | Tools, browser control, sessions, MCP, chat |
| `document.modelContext` | WebMCP polyfill — page-defined tools |
Where the browser has its own `LanguageModel` (Chrome), pages keep it unless the person chose a different backend in Harbor (their own agent, or a model through the bridge); then Harbor's replaces it, behind Harbor's consent prompt. `window.agent` and `document.modelContext` are Harbor's either way.
---
## Detection
```javascript
if (window.agent && self.LanguageModel) { /* present from the first script, no wait needed */ }
// agent-ready fires once DOMContentLoaded has happened (confirmed even
// if this script starts after that already happened) and Harbor knows
// the real settings (whichever is later), then again only on a change.
window.addEventListener('agent-ready', (e) => {
console.log('Version:', e.detail.version); // '1.0.0'
console.log('Features:', e.detail.features); // FeatureFlags
});
// Synchronous capability snapshot — can still read Harbor's defaults if
// called before the first agent-ready; re-read it inside that listener
// instead of trusting an earlier call.
const caps = window.agent.capabilities();
// → { apiVersion, features, surfaces, scopes }
```
---
## Permissions (MUST REQUEST FIRST)
All APIs require permission. There are two paths — pick one per session:
### Recommended — `agent.requestCapabilities()` (typed actions)
Creates a session for the actions you ask for. Model and browser access need the origin grant first (requestPermissions); it fails without one.
Plays nicely with budgets and the activity feed.
```javascript
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' },
],
budget: { ttlMinutes: 15 },
});
// Need more later? Ask with requestPermissions() (that shows the
// prompt), then call requestCapabilities() again for a new session.
```
### Legacy — `agent.requestPermissions()` (origin-level scopes)
Still works; mapped to typed actions internally.
```javascript
const result = await window.agent.requestPermissions({
scopes: ['model:prompt', 'mcp:tools.call'],
reason: 'To help with your task',
tools: ['time-wasm/time.now'] // Optional allowlist for mcp:tools.call
});
if (result.granted) { /* all scopes granted */ }
else { /* check result.scopes['model:prompt'] === 'granted-always' */ }
```
### Permission Scopes
| Scope | Risk | Enables |
|-------|------|---------|
| `model:prompt` | Low | `LanguageModel.create`, `session.prompt` (asked for by `create()` itself if missing) |
| `model:tools` | Medium | `agent.run` autonomous loop |
| `mcp:tools.list` | Low | `agent.run()` seeing the person's installed tools |
| `mcp:tools.call` | Medium | `agent.run()` using the person's installed tools |
| `mcp:servers.register` | Medium | `agent.mcp.register` (BYOC) |
| `browser:activeTab.read` | Medium | `agent.browser.activeTab.readability/getElements` |
| `browser:activeTab.interact` | High | `click`, `fill`, `select`, `scroll` |
| `browser:activeTab.screenshot` | Medium | `agent.browser.activeTab.screenshot` |
| `browser:tabs.read` | Medium | `agent.browser.tabs.list`, `tab.*` reads |
| `browser:tabs.create` | High | `agent.browser.tabs.create/close`, drive spawned tabs |
| `browser:navigate` | High | `agent.browser.navigate` (active tab) |
| `web:fetch` | High | `agent.browser.fetch` (CORS-bypassing) |
| `chat:open` | Low | `agent.chat.open/close` (messages sent from the chat also need `model:prompt`) |
### Grant Types
| Grant | Meaning |
|-------|---------|
| `granted-always` | Persistent until revoked |
| `granted-once` | ~10 min or until tab closes |
| `denied` | User said no |
| `not-granted` | Never requested |
```javascript
const { scopes, allowedTools } = await window.agent.permissions.list();
```
---
## Capability Discovery
```javascript
const caps = window.agent.capabilities();
// {
// apiVersion: '1.4.0',
// features: { textGeneration, toolCalling, toolAccess,
// browserInteraction, browserControl },
// surfaces: {
// run,
// browser: { activeTab, tabs, navigate, fetch },
// mcp, chat, sessions, modelContext
// },
// scopes: PermissionScope[]
// }
```
Use `caps.features.*` instead of try/catching `ERR_FEATURE_DISABLED`.
`surfaces.mcp`, `chat`, `sessions` and `modelContext` are always `true`
because no toggle gates them. There is no `surfaces.tools`: a page reaches
its own tools through `document.modelContext`, and only the person's agent
reaches their installed tools. Sessions still need a `model:prompt` grant
for model access; they no longer carry tool access.
---
## LanguageModel - Text Generation
Harbor implements the [Prompt API](https://webmachinelearning.github.io/prompt-api/)'s `LanguageModel`, not a Harbor-specific session API. No `provider`/`model` option: the person picks what answers, in Harbor.
```javascript
// create() asks for the model:prompt grant itself, if you skipped step 2 for it
const session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'You are helpful.' }], // Optional
});
// Plain prompt
const response = await session.prompt('What is 2+2?');
// Streaming — a ReadableStream of plain string deltas, readable with for-await
for await (const chunk of session.promptStreaming('Tell me a story')) {
process.stdout.write(chunk);
}
session.destroy();
```
### Availability probe
```javascript
const availability = await LanguageModel.availability();
// 'unavailable' | 'downloadable' | 'downloading' | 'available' — needs no grant
```
> Note: `LanguageModel` has no `runtime.*` (native AI bridging) or `providers.*` (provider listing/selection) namespace, in the spec or in Harbor's implementation. The person picks their model, or their own agent, in Harbor's sidebar — there's no page-facing provider choice.
---
## Tools
There is no `window.agent.tools`. A page reaches its own tools through
WebMCP (`document.modelContext`, below). A page cannot call the person's
installed MCP tools directly; only the person's agent does, inside
`agent.run()` or `agent.chat.open()`, gated by the `mcp:tools.list` and
`mcp:tools.call` scopes and the per-origin tool allowlist.
---
## window.agent.run - Autonomous Agent (toolCalling flag)
```javascript
for await (const ev of window.agent.run({
task: 'What time is it in Tokyo?',
maxToolCalls: 5, // default 5; caps tool calls for the whole run
systemPrompt: 'Be concise.',
})) {
switch (ev.type) {
case 'thinking': console.log('reasoning:', ev.content); break;
case 'tool_call': console.log('calling', ev.tool, ev.args); break;
case 'tool_result': console.log('got', ev.result); break;
case 'final': console.log('answer:', ev.output); break;
case 'error': throw new Error(ev.error);
}
}
```
Event union (exhaustive):
```ts
| { 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 }
```
---
## Browser APIs
### Active tab — `browserInteraction` flag
```javascript
const { title, url, content, length } =
await window.agent.browser.activeTab.readability();
const { elements } = await window.agent.browser.activeTab.getElements({
selector: 'a, button, input',
});
await window.agent.browser.activeTab.click('ref-123');
await window.agent.browser.activeTab.fill('ref-456', 'Hello');
await window.agent.browser.activeTab.select('ref-789', 'option-value');
await window.agent.browser.activeTab.scroll('down', 500);
const { dataUrl } = await window.agent.browser.activeTab.screenshot();
```
### Active-tab navigation & fetch — `browserControl` flag
```javascript
// Navigate the page itself
await window.agent.browser.navigate('https://example.com');
// CORS-bypassing fetch (http/https only; refuses this device and private networks)
const r = await window.agent.browser.fetch('https://api.example.com/data', {
method: 'GET',
headers: { 'X-Foo': 'bar' },
});
// → { ok, status, statusText, headers, body, url }
```
### Owned tabs — `browserControl` flag
```javascript
// Readable only while the tab shows a page on your own origin.
const tab = await window.agent.browser.tabs.create({
url: `${location.origin}/search`,
active: false,
});
await window.agent.browser.tab.waitForLoad(tab.id);
const { html } = await window.agent.browser.tab.getHtml(tab.id, 'main');
const { title, url, text } = await window.agent.browser.tab.readability(tab.id);
const tabs = await window.agent.browser.tabs.list();
await window.agent.browser.tabs.close(tab.id);
```
You can only drive tabs your origin spawned (same-origin or "owned" model). You cannot drive arbitrary user tabs.
---
## Sessions API
Capability-bounded, named sessions with budgets. Sessions carry LLM and
browser capabilities only; there is no session tool access, so no
`callTool()`, `listAllowedTools()` or `maxToolCalls` limit.
```javascript
const session = await window.agent.sessions.create({
name: 'Research Assistant',
reason: 'multi-step research',
capabilities: {
llm: { provider: 'ollama', model: 'llama3.2' },
browser: ['read', 'screenshot'],
},
limits: { ttlMinutes: 30 },
options: { systemPrompt: 'Cite sources.', temperature: 0.2 },
});
const response = await session.prompt('Find AI news');
await session.terminate();
const summaries = await window.agent.sessions.list();
```
---
## BYOC — `document.modelContext` + `agent.mcp` + `agent.chat`
### Page-declared tools (WebMCP polyfill)
```javascript
await document.modelContext.registerTool({
name: 'add_to_cart',
description: 'Add a product to the cart',
inputSchema: { type: 'object', properties: { productId: { type: 'string' } } },
execute: async ({ productId }, { signal }) => { /* … */ },
}, { signal: controller.signal }); // controller.abort() unregisters
```
`document.modelContext.getTools()` resolves to this document's own registered tools. `registerTool` follows the WebMCP draft: it is async, `execute` is required (there's no `handler` alias), it rejects a duplicate or invalid name (1–128 of `A-Z a-z 0-9 _ - .`) or a description that's empty or all whitespace with `InvalidStateError`, and it validates each `exposedTo` entry (`SecurityError` for an invalid URL or a non-trustworthy origin) but otherwise accepts it with no effect, since Harbor's polyfill runs in the top frame only and has no other frame to expose a tool to. There is no `navigator.modelContext`, `addTool` or `removeTool`; unregister by aborting the `signal` passed to `registerTool`'s options.
The person's agent can call page tools during the `agent.run()` the page starts (both backends), and during its `agent.chat.open()` only on the person's ACP agent (built-in page chat has no tools). Harbor's built-in agent sees them as `page:<host>/<tool>`, and the person's ACP agent gets one MCP server named by the site's host on 127.0.0.1 for that session, carrying the page's tools and the site's registered servers' tools (`<server>__<tool>`). They need no extra permission: `mcp:tools.*` isn't needed, and a policy rule on server `page:<host>` can refuse them. They last as long as the document; a hash or `pushState` change keeps them. A failed, timed-out (60 s) or orphaned call is `ERR_TOOL_FAILED`. `maxToolCalls` counts them. `LanguageModel` sessions never get them. The person's own agent outside the browser can also call them, on pages it opened or the person shared (via `harbor-mcp`; see AGENT_REACHES_TABS.md). A page doesn't need an Ask button.
### Site-hosted MCP server registration
```html
<link rel="mcp-server" href="https://shop.example/mcp"
title="Shop" data-tools="search,add_to_cart">
```
`discover()` also reads `rel="mcp"`. A link without `data-transport` reports `'streamable-http'`.
```javascript
const servers = await window.agent.mcp.discover();
const reg = await window.agent.mcp.register({
url: 'https://shop.example/mcp',
name: 'Shop Assistant',
tools: ['search', 'add_to_cart'],
transport: 'streamable-http', // 'streamable-http' | 'sse' | 'websocket'
});
await window.agent.mcp.unregister(reg.serverId);
```
A registered server's tools reach the person's agent under the same gate as page tools: no `mcp:tools.*` grant, no allowlist, a policy check per server and per call. Harbor connects to the server itself; the person's ACP agent reaches the tools through Harbor's endpoint, never the server's URL.
### Open the user's chat with a site-specific config
Harbor shows its chat on the page. Messages sent from it are the page's prompts: each is checked and audited under the page's origin and needs `model:prompt`. On the person's own agent, the chat can use the site's page tools and registered servers' tools; on Harbor's built-in model it has none.
```javascript
const chat = await window.agent.chat.open({
systemPrompt: 'Shopping assistant',
initialMessage: 'How can I help?',
tools: ['search', 'add_to_cart'],
style: { theme: 'light', accentColor: '#ff9900', position: 'right' },
});
await window.agent.chat.close(chat.chatId);
```
---
## Error Codes
See [WEB_AGENTS_API.md#error-handling](WEB_AGENTS_API.md#error-handling) for the full list.
| Code | Meaning |
|------|---------|
| `ERR_FEATURE_DISABLED` | Feature flag is off (check `agent.capabilities()`) |
| `ERR_HARBOR_NOT_FOUND` | Harbor extension not found |
| `ERR_PERMISSION_DENIED` | User denied, or a required scope was missing and they declined |
| `ERR_INVALID_REQUEST` | Bad parameters |
| `ERR_TOOL_FAILED` | Tool execution failed, or didn't answer in time |
| `ERR_MODEL_FAILED` | LLM error |
| `ERR_SESSION_NOT_FOUND` | Session terminated/destroyed |
| `ERR_TIMEOUT` | Request timed out |
| `ERR_ELEMENT_NOT_FOUND` | DOM ref not found |
| `ERR_AGENT_FAILED` | `agent.run()` or an ACP backend session failed |
| `ERR_INTERNAL` | Internal error |
```javascript
try {
await document.modelContext.executeTool(tool, input);
} catch (err) {
if (err.code === 'ERR_FEATURE_DISABLED') { /* tell user to enable in sidebar */ }
if (err.code === 'ERR_PERMISSION_DENIED') { /* fall back */ }
}
```
---
## Feature Flags
Users toggle these in Harbor's sidebar. Read them at runtime via `agent.capabilities().features`. A turned-off flag leaves its surface present but refusing (`ERR_FEATURE_DISABLED`) — the surface itself always exists, whatever the flags say. The one exception is `LanguageModel.availability()`, which resolves `"unavailable"` with `textGeneration` off rather than throwing, matching the Prompt API's own contract that `availability()` never rejects.
| Flag | Default | Surfaces |
|------|---------|----------|
| `textGeneration` | ON | `LanguageModel` |
| `toolAccess` | ON | `agent.mcp.register/discover/unregister` (site MCP server registration) |
| `toolCalling` | ON | `agent.run()` |
| `browserInteraction` | OFF | `agent.browser.activeTab.*` |
| `browserControl` | OFF | `agent.browser.navigate/fetch/tabs/tab` |
---
## Debug logging
The injected script is silent by default. Opt in via any of:
```html
<meta name="web-agents-api-debug" content="1">
```
```javascript
localStorage.setItem('web-agents-api:debug', '1');
window.__webAgentsApiDebug = true; // before injection
```
---
## TypeScript Types (Quick Reference)
```typescript
type PermissionScope =
| 'model:prompt' | 'model:tools'
| 'mcp:tools.list' | 'mcp:tools.call' | 'mcp:servers.register'
| 'browser:activeTab.read' | 'browser:activeTab.interact' | 'browser:activeTab.screenshot'
| 'browser:tabs.read' | 'browser:tabs.create' | 'browser:navigate'
| 'web:fetch' | 'chat:open';
type PermissionGrant = 'granted-once' | 'granted-always' | 'denied' | 'not-granted';
interface ToolDescriptor {
serverId: string;
name: string;
description?: string;
inputSchema?: unknown;
}
type RunEvent =
| { 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 };
// LanguageModel's own types come from the Prompt API spec, not from Harbor:
// https://webmachinelearning.github.io/prompt-api/
interface ActiveTabReadability {
url: string; title: string; text: string; // tab.readability(id) returns the same shape
}
interface TabInfo { id: number; url: string; title: string; active: boolean; }
interface FetchResponse {
ok: boolean; status: number; statusText: string;
headers: Record<string, string>; body: string; url: string;
}
```
---
## Common Patterns
### Initialize app with feature detection + permissions
```javascript
async function init() {
if (!window.agent) { showError('Install Harbor extension'); return false; }
const caps = window.agent.capabilities();
if (!caps.features.textGeneration) { showError('Enable text generation'); return false; }
const { granted } = await window.agent.requestPermissions({
scopes: ['model:prompt', 'mcp:tools.list', 'mcp:tools.call'],
reason: 'Enable AI features',
});
return granted;
}
```
### Streaming chat
```javascript
let session;
async function sendMessageStreaming(text, onChunk) {
session ??= await LanguageModel.create({ initialPrompts: [{ role: 'system', content: 'Be helpful.' }] });
for await (const chunk of session.promptStreaming(text)) onChunk(chunk);
}
```
### Page summarizer
```javascript
async function summarizePage() {
const { text, title } = await window.agent.browser.activeTab.readability();
const session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'Summarize in 2-3 sentences.' }],
});
const summary = await session.prompt(text.slice(0, 10000));
session.destroy();
return { title, summary };
}
```
### Tool-calling agent
```javascript
async function runAgent(task) {
const events = [];
for await (const ev of window.agent.run({ task, maxToolCalls: 5 })) {
events.push(ev);
if (ev.type === 'final') return { output: ev.output, events };
if (ev.type === 'error') throw new Error(ev.error);
}
}
```
### Graceful degradation
```javascript
async function getAIResponse(prompt) {
if (window.agent?.capabilities().features.textGeneration) {
try {
const { granted } = await window.agent.requestPermissions({ scopes: ['model:prompt'] });
if (granted) {
const session = await LanguageModel.create();
const response = await session.prompt(prompt);
session.destroy();
return response;
}
} catch (e) { console.warn('Web Agents API failed:', e); }
}
return await fetch('/api/ai', { method: 'POST', body: JSON.stringify({ prompt }) })
.then(r => r.json());
}
```
---
## Key Files (for Harbor development)
```
extension/src/page-api/
├── injected.ts # LanguageModel/agent/document.modelContext (this doc's source of truth)
├── content-script.ts # Page ↔ background relay
├── background.ts # Port listener; origin from the connecting port's sender
├── harbor-core.ts # In-process call into the rest of Harbor
└── handlers/ # Per-message handlers (browser, sessions, mcp, chat, tools)
extension/src/ # Harbor core: LLM providers, MCP client, native bridge
bridge-rs/src/ # Native messaging host (Rust)
```
---
## Version
Web Agent API v1.4.0 / Harbor v1