@jantcz/webai 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +135 -0
  2. package/README.md +24 -2
  3. package/agents/.claude-plugin/plugin.json +4 -0
  4. package/agents/README.md +17 -0
  5. package/agents/agents/a11y-reviewer.md +16 -0
  6. package/agents/agents/copy-editor.md +14 -0
  7. package/agents/skills/czech-copy/SKILL.md +18 -0
  8. package/agents/skills/element-edit/SKILL.md +51 -0
  9. package/agents/skills/stock-images/SKILL.md +25 -0
  10. package/agents/skills/verify-change/SKILL.md +19 -0
  11. package/agents/skills/web-styling/SKILL.md +20 -0
  12. package/bin/webai-agent.js +373 -0
  13. package/bin/webai-bridge.js +5 -0
  14. package/bin/webai.js +4 -0
  15. package/package.json +85 -4
  16. package/src/agents/claude.js +194 -0
  17. package/src/agents/codex.js +111 -0
  18. package/src/agents/custom.js +64 -0
  19. package/src/agents/docker.js +46 -0
  20. package/src/agents/gemini.js +102 -0
  21. package/src/agents/index.js +25 -0
  22. package/src/agents/opencode.js +117 -0
  23. package/src/agents/pack.js +99 -0
  24. package/src/agents/pi.js +143 -0
  25. package/src/agents/webai.js +66 -0
  26. package/src/astro/annotate.js +163 -0
  27. package/src/astro/index.d.ts +5 -0
  28. package/src/astro/index.js +40 -0
  29. package/src/bridge.js +63 -0
  30. package/src/cli.js +119 -0
  31. package/src/client/overlay.js +1169 -0
  32. package/src/config.js +23 -0
  33. package/src/core.js +116 -0
  34. package/src/history.js +108 -0
  35. package/src/html.js +43 -0
  36. package/src/index.d.ts +244 -0
  37. package/src/index.js +10 -0
  38. package/src/inject.js +80 -0
  39. package/src/mcp/endpoint.js +71 -0
  40. package/src/mcp/stdio.js +103 -0
  41. package/src/mcp/tools.js +126 -0
  42. package/src/next/index.d.ts +8 -0
  43. package/src/next/index.js +59 -0
  44. package/src/next/script.d.ts +3 -0
  45. package/src/next/script.js +13 -0
  46. package/src/pages.js +202 -0
  47. package/src/prompt.js +17 -0
  48. package/src/proxy.js +68 -0
  49. package/src/server.js +252 -0
  50. package/src/session.js +497 -0
  51. package/src/static.js +64 -0
  52. package/src/vite.d.ts +5 -0
  53. package/src/vite.js +145 -0
@@ -0,0 +1,1169 @@
1
+ // Client side: element inspector and chat panel. Runs only in development.
2
+ // Everything lives in the shadow DOM of <webai-overlay>, so site styles don't leak in.
3
+ //
4
+ // Talks to the agent through a transport: the default is HTTP + SSE to the dev server
5
+ // (`/__webai/*`); the web demo (`demo/`) injects its own that runs
6
+ // entirely in the browser.
7
+
8
+ const STORE_OPEN = 'webai:open';
9
+ const STORE_TARGET = 'webai:target';
10
+ const STORE_DRAFT = 'webai:draft';
11
+ const STORE_SIDE = 'webai:side';
12
+ const STORE_GEOMETRY = 'webai:geometry';
13
+ const MIN_W = 300;
14
+ const MIN_H = 320;
15
+ const STORE_TRIGGERS = 'webai:triggers';
16
+ const STORE_TAB = 'webai:tab';
17
+ const STORE_NAV = 'webai:nav';
18
+
19
+ const TRIGGERS = [
20
+ ['shift-click', 'Shift + click'],
21
+ ['alt-click', 'Alt + click'],
22
+ ['contextmenu', 'Right click (Shift + right click = native menu)'],
23
+ ];
24
+
25
+ const PING_MS = 15000; // the server's heartbeat (server.js)
26
+
27
+ const TOOL_ICONS = { Edit: '✎', MultiEdit: '✎', Write: '✚', Read: '◉', Bash: '$', Grep: '⌕', Glob: '⌕' };
28
+
29
+ export function start(cfg) {
30
+ if (window.__webai) return;
31
+ window.__webai = true;
32
+ // Right away, not after DOMContentLoaded: the console of the page's own start-up is what matters most.
33
+ const capture = cfg.transport ? null : installCapture(cfg.base);
34
+ const run = () => new Overlay(cfg, capture);
35
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run, { once: true });
36
+ else run();
37
+ }
38
+
39
+ /**
40
+ * Transport to the dev server. Interface:
41
+ * - `request(method, path, body)` → data; failures throw an Error with a readable message
42
+ * - `subscribe({ onEvent, onReady, onLost, onPing, onCommand, tab })` → unsubscribe function (`onPing`, `onCommand`, `tab` are optional); first
43
+ * replays the whole history, then `onReady({ busy })`, then live events
44
+ */
45
+ export function httpTransport(cfg) {
46
+ return {
47
+ async request(method, path, body) {
48
+ let res;
49
+ try {
50
+ res = await fetch(cfg.base + path, {
51
+ method,
52
+ headers: { 'Content-Type': 'application/json', 'X-WebAI-Token': cfg.token },
53
+ body: body ? JSON.stringify(body) : undefined,
54
+ });
55
+ } catch {
56
+ throw new Error('The dev server is not responding. Is it running? Reload the page after a restart.');
57
+ }
58
+ const data = await res.json().catch(() => ({}));
59
+ if (res.status === 403) throw new Error('The dev server has restarted in the meantime, reload the page.');
60
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
61
+ return data;
62
+ },
63
+
64
+ subscribe({ onEvent, onReady, onLost, onPing, onCommand, tab }) {
65
+ const es = new EventSource(`${cfg.base}/events?token=${cfg.token}${tab ? `&tab=${encodeURIComponent(tab)}` : ''}`);
66
+ es.addEventListener('command', (m) => onCommand?.(JSON.parse(m.data)));
67
+ es.onmessage = (m) => onEvent(JSON.parse(m.data));
68
+ es.addEventListener('ready', (m) => onReady(JSON.parse(m.data)));
69
+ es.addEventListener('ping', () => onPing?.());
70
+ es.onerror = () => {
71
+ if (es.readyState === EventSource.CLOSED) onLost('Lost connection to the dev server. Reload the page.');
72
+ };
73
+ return () => es.close();
74
+ },
75
+ };
76
+ }
77
+
78
+ class Overlay {
79
+ constructor(cfg, capture = null) {
80
+ this.cfg = cfg;
81
+ this.transport = cfg.transport ?? httpTransport(cfg);
82
+ this.target = null;
83
+ this.busy = false;
84
+ this.live = null;
85
+ this.unsubscribe = null;
86
+ this.mount();
87
+ this.bindInspector();
88
+ // A reload after an edit must not eat what is being typed.
89
+ this.el.input.value = sessionStorage.getItem(STORE_DRAFT) ?? '';
90
+ this.el.input.addEventListener('input', () => {
91
+ if (this.el.input.value) sessionStorage.setItem(STORE_DRAFT, this.el.input.value);
92
+ else sessionStorage.removeItem(STORE_DRAFT);
93
+ });
94
+ // Over HTTP the page also reports to the server (for MCP tools), so the connection is always on.
95
+ // Before the panel opens: it would otherwise connect without the tab.
96
+ if (capture) this.startLink(capture);
97
+ const open = sessionStorage.getItem(STORE_OPEN) === '1';
98
+ // Without the chat there is no panel to remember the selection by: it is restored on its own.
99
+ if (open || cfg.chat === false) {
100
+ const saved = readJson(sessionStorage.getItem(STORE_TARGET));
101
+ if (saved) this.setTarget(saved, findElement(saved, cfg.srcAttr));
102
+ }
103
+ if (open) this.open();
104
+ this.watchTarget();
105
+ // No selection came back from the last page load: tell the server (a stale one would otherwise stay).
106
+ if (capture && !this.target) this.reportSelection();
107
+ }
108
+
109
+ // ---------- DOM ----------
110
+
111
+ mount() {
112
+ this.host = document.createElement('webai-overlay');
113
+ const root = this.host.attachShadow({ mode: 'open' });
114
+ root.innerHTML = `<style>${STYLES}</style>
115
+ <div class="hover" hidden><span class="label"></span></div>
116
+ <div class="pick" hidden></div>
117
+ <button class="fab" hidden title="WebAI – open chat (or Shift+click an element)">✦</button>
118
+ <section class="panel" hidden>
119
+ <header>
120
+ <strong>WebAI</strong><span class="agent"></span>
121
+ <span class="spacer"></span>
122
+ <span class="versions" hidden><button class="back" title="Previous version">◀</button><span class="vnum"></span><button class="fwd" title="Next version">▶</button></span>
123
+ <button class="gear" title="Settings" aria-label="Settings">${GEAR_ICON}</button>
124
+ <button class="reset" title="Start a new conversation">New</button>
125
+ <button class="close" title="Close (Esc)">×</button>
126
+ </header>
127
+ <div class="settings" hidden></div>
128
+ <div class="log"></div>
129
+ <div class="activity" hidden></div>
130
+ <div class="target" hidden><code></code><button title="Don't send the element">×</button></div>
131
+ <form>
132
+ <textarea rows="2" placeholder="What should happen to the element? Enter sends, Shift+Enter adds a new line"></textarea>
133
+ <button type="submit" class="send">Send</button>
134
+ </form>
135
+ <footer class="hint"></footer>
136
+ <div class="grip nw" data-grip="-1,-1"></div><div class="grip ne" data-grip="1,-1"></div>
137
+ <div class="grip sw" data-grip="-1,1"></div><div class="grip se" data-grip="1,1"></div>
138
+ </section>`;
139
+ const $ = (s) => root.querySelector(s);
140
+ this.el = {
141
+ hover: $('.hover'), label: $('.hover .label'), pick: $('.pick'), panel: $('.panel'),
142
+ agent: $('.agent'), log: $('.log'), activity: $('.activity'), target: $('.target'), targetCode: $('.target code'),
143
+ form: $('form'), input: $('textarea'), send: $('.send'), fab: $('.fab'), settings: $('.settings'),
144
+ gear: $('.gear'), hint: $('.hint'),
145
+ versions: $('.versions'), vnum: $('.vnum'), back: $('.back'), fwd: $('.fwd'),
146
+ };
147
+ this.el.back.onclick = () => this.restoreVersion(this.history.current - 1);
148
+ this.el.fwd.onclick = () => this.restoreVersion(this.history.current + 1);
149
+ $('.close').onclick = () => this.close();
150
+ $('.reset').onclick = () => this.reset();
151
+ this.el.gear.onclick = () => this.toggleSettings();
152
+ this.el.fab.onclick = () => {
153
+ this.open();
154
+ this.el.input.focus();
155
+ };
156
+ this.el.fab.hidden = !this.cfg.fab;
157
+ $('.target button').onclick = () => this.setTarget(null);
158
+ this.el.form.onsubmit = (e) => {
159
+ e.preventDefault();
160
+ this.busy ? this.stop() : this.send();
161
+ };
162
+ this.el.input.addEventListener('keydown', (e) => {
163
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
164
+ e.preventDefault();
165
+ if (!this.busy) this.send();
166
+ }
167
+ });
168
+ this.applySide();
169
+ this.initGeometry(root);
170
+ this.updateHint();
171
+ document.documentElement.appendChild(this.host);
172
+ const follow = () => this.drawPick();
173
+ addEventListener('scroll', follow, { passive: true, capture: true });
174
+ addEventListener('resize', follow, { passive: true });
175
+ }
176
+
177
+ // ---------- inspector ----------
178
+
179
+ // Read on every mouse move, so cached in memory rather than read from localStorage.
180
+ get triggers() {
181
+ this._triggers ??= readJson(localStorage.getItem(STORE_TRIGGERS)) ?? this.cfg.triggers;
182
+ return this._triggers;
183
+ }
184
+
185
+ bindInspector() {
186
+ const ours = (e) => e.composedPath().includes(this.host);
187
+ const armed = (e) => {
188
+ const triggers = this.triggers;
189
+ return (triggers.includes('shift-click') && e.shiftKey && !e.metaKey && !e.ctrlKey) ||
190
+ (triggers.includes('alt-click') && e.altKey && !e.metaKey && !e.ctrlKey);
191
+ };
192
+
193
+ addEventListener('mousemove', (e) => {
194
+ if (!armed(e) || ours(e)) return this.hideHover();
195
+ this.showHover(e.target);
196
+ }, { passive: true, capture: true });
197
+ addEventListener('keyup', (e) => (e.key === 'Shift' || e.key === 'Alt') && this.hideHover(), true);
198
+ addEventListener('blur', () => this.hideHover());
199
+
200
+ // Otherwise Shift+mousedown would start selecting text.
201
+ addEventListener('mousedown', (e) => {
202
+ if (e.button === 0 && armed(e) && !ours(e)) e.preventDefault();
203
+ }, true);
204
+ addEventListener('click', (e) => {
205
+ if (e.button !== 0 || !armed(e) || ours(e)) return;
206
+ e.preventDefault();
207
+ e.stopImmediatePropagation();
208
+ this.pick(e.target);
209
+ }, true);
210
+ // Shift+right click keeps the native menu (Inspect element).
211
+ addEventListener('contextmenu', (e) => {
212
+ if (!this.triggers.includes('contextmenu') || e.shiftKey || ours(e)) return;
213
+ e.preventDefault();
214
+ this.pick(e.target);
215
+ }, true);
216
+ addEventListener('keydown', (e) => {
217
+ if (e.key === 'Escape' && !this.el.panel.hidden) this.close();
218
+ else if (e.key === 'Escape' && this.cfg.chat === false && this.target) this.setTarget(null); // clears the selection
219
+ });
220
+ }
221
+
222
+ showHover(node) {
223
+ const el = node instanceof Element ? node : node.parentElement;
224
+ if (!el) return;
225
+ const r = el.getBoundingClientRect();
226
+ Object.assign(this.el.hover.style, box(r));
227
+ const src = el.closest(`[${this.cfg.srcAttr}]`)?.getAttribute(this.cfg.srcAttr);
228
+ this.el.label.textContent = `${el.tagName.toLowerCase()}${src ? ` ${src}` : ''}`;
229
+ this.el.label.classList.toggle('below', r.top < 24);
230
+ this.el.hover.hidden = false;
231
+ }
232
+
233
+ hideHover() {
234
+ this.el.hover.hidden = true;
235
+ }
236
+
237
+ pick(node) {
238
+ const el = node instanceof Element ? node : node.parentElement;
239
+ if (!el) return;
240
+ this.hideHover();
241
+ getSelection()?.removeAllRanges(); // Shift+click extends the text selection
242
+ this.setTarget(describe(el, this.cfg.srcAttr), el);
243
+ if (this.cfg.chat === false) return; // select only: the highlight stays, MCP tools can read it
244
+ this.open();
245
+ this.el.input.focus();
246
+ }
247
+
248
+ /**
249
+ * The selection survives a reload, but the page may draw the element later (an app that renders after its data
250
+ * arrives), replace it, or change it (hot reload): after the page settles, look for it again when it is missing and
251
+ * describe it again when it changed, so the server and the agent are told what is there now.
252
+ */
253
+ watchTarget() {
254
+ let timer = null;
255
+ new MutationObserver(() => {
256
+ if (timer || !this.target) return;
257
+ timer = setTimeout(() => {
258
+ timer = null;
259
+ if (!this.target) return;
260
+ const el = this.targetEl?.isConnected ? this.targetEl : findElement(this.target, this.cfg.srcAttr);
261
+ if (!el) return;
262
+ const info = describe(el, this.cfg.srcAttr);
263
+ if (el !== this.targetEl || JSON.stringify(info) !== JSON.stringify(this.target)) this.setTarget(info, el);
264
+ }, 300);
265
+ }).observe(document.documentElement, { childList: true, subtree: true, characterData: true, attributes: true });
266
+ }
267
+
268
+ setTarget(info, el = null) {
269
+ this.target = info;
270
+ this.targetEl = el;
271
+ if (info) sessionStorage.setItem(STORE_TARGET, JSON.stringify(info));
272
+ else sessionStorage.removeItem(STORE_TARGET);
273
+ this.el.target.hidden = !info;
274
+ if (info) this.el.targetCode.textContent = `<${info.tag.match(/^<?([\w-]+)/)?.[1] ?? '?'}> ${info.src ?? info.selector}`;
275
+ this.drawPick();
276
+ this.reportSelection();
277
+ }
278
+
279
+ drawPick() {
280
+ const el = this.targetEl;
281
+ if (!el || !el.isConnected || (this.el.panel.hidden && this.cfg.chat !== false)) {
282
+ this.el.pick.hidden = true;
283
+ return;
284
+ }
285
+ Object.assign(this.el.pick.style, box(el.getBoundingClientRect()));
286
+ this.el.pick.hidden = false;
287
+ }
288
+
289
+ // ---------- panel ----------
290
+
291
+ open() {
292
+ sessionStorage.setItem(STORE_OPEN, '1');
293
+ this.el.panel.hidden = false;
294
+ this.el.fab.hidden = true;
295
+ this.drawPick();
296
+ if (!this.unsubscribe) this.connect();
297
+ }
298
+
299
+ close() {
300
+ sessionStorage.removeItem(STORE_OPEN);
301
+ this.el.panel.hidden = true;
302
+ this.el.pick.hidden = true;
303
+ this.el.fab.hidden = !this.cfg.fab;
304
+ this.showSettings(false);
305
+ if (this.tab) return; // the connection also carries MCP commands for this page
306
+ this.unsubscribe?.();
307
+ this.unsubscribe = null;
308
+ }
309
+
310
+ applySide() {
311
+ const left = localStorage.getItem(STORE_SIDE) === 'left';
312
+ this.el.panel.classList.toggle('left', left);
313
+ this.el.fab.classList.toggle('left', left);
314
+ }
315
+
316
+ // ---------- moving and resizing ----------
317
+
318
+ // The header moves the panel, the corners resize it; both remember the result.
319
+ // A double click on the header docks it back to its side at its default size.
320
+ initGeometry(root) {
321
+ const header = root.querySelector('header');
322
+ header.addEventListener('pointerdown', (e) => {
323
+ if (e.button === 0 && !e.target.closest('button')) this.gesture(e, null);
324
+ });
325
+ header.addEventListener('dblclick', (e) => {
326
+ if (e.target.closest('button')) return;
327
+ localStorage.removeItem(STORE_GEOMETRY);
328
+ this.applyGeometry();
329
+ });
330
+ for (const grip of root.querySelectorAll('[data-grip]')) {
331
+ grip.addEventListener('pointerdown', (e) => {
332
+ if (e.button === 0) this.gesture(e, grip.dataset.grip.split(',').map(Number));
333
+ });
334
+ }
335
+ addEventListener('resize', () => this.applyGeometry(), { passive: true });
336
+ this.applyGeometry();
337
+ }
338
+
339
+ /** Move (`dir` null) or resize from a corner (`dir` = [±1, ±1]) while the pointer is down. */
340
+ gesture(e, dir) {
341
+ e.preventDefault();
342
+ const panel = this.el.panel;
343
+ const start = panel.getBoundingClientRect();
344
+ const [x0, y0] = [e.clientX, e.clientY];
345
+ let started = false;
346
+ const move = (ev) => {
347
+ const dx = ev.clientX - x0;
348
+ const dy = ev.clientY - y0;
349
+ // A click (or the first half of a double click) moves nothing.
350
+ if (!started) {
351
+ if (Math.hypot(dx, dy) < 4) return;
352
+ started = true;
353
+ panel.setPointerCapture(ev.pointerId);
354
+ panel.classList.add('dragging');
355
+ }
356
+ let { left: x, top: y, width: w, height: h } = start;
357
+ if (!dir) {
358
+ x += dx;
359
+ y += dy;
360
+ } else {
361
+ const [sx, sy] = dir;
362
+ const nw = Math.max(MIN_W, w + sx * dx);
363
+ const nh = Math.max(MIN_H, h + sy * dy);
364
+ if (sx < 0) x += w - nw;
365
+ if (sy < 0) y += h - nh;
366
+ [w, h] = [nw, nh];
367
+ }
368
+ this.applyGeometry({ x, y, w, h });
369
+ };
370
+ const end = (ev) => {
371
+ removeEventListener('pointermove', move);
372
+ removeEventListener('pointerup', end);
373
+ removeEventListener('pointercancel', end);
374
+ if (!started) return;
375
+ panel.releasePointerCapture(ev.pointerId);
376
+ panel.classList.remove('dragging');
377
+ const r = panel.getBoundingClientRect();
378
+ localStorage.setItem(STORE_GEOMETRY, JSON.stringify({ x: r.left, y: r.top, w: r.width, h: r.height }));
379
+ };
380
+ addEventListener('pointermove', move);
381
+ addEventListener('pointerup', end);
382
+ addEventListener('pointercancel', end);
383
+ }
384
+
385
+ /** The remembered (or given) position and size, kept inside the window; none = docked to its side. */
386
+ applyGeometry(g = JSON.parse(localStorage.getItem(STORE_GEOMETRY) ?? 'null')) {
387
+ const style = this.el.panel.style;
388
+ if (!g) {
389
+ for (const k of ['left', 'top', 'width', 'height', 'right', 'bottom']) style[k] = '';
390
+ return;
391
+ }
392
+ const w = Math.min(Math.max(MIN_W, g.w), innerWidth - 16);
393
+ const h = Math.min(Math.max(MIN_H, g.h), innerHeight - 16);
394
+ const x = Math.min(Math.max(8, g.x), innerWidth - w - 8);
395
+ const y = Math.min(Math.max(8, g.y), innerHeight - h - 8);
396
+ Object.assign(style, { left: `${x}px`, top: `${y}px`, width: `${w}px`, height: `${h}px`, right: 'auto', bottom: 'auto' });
397
+ }
398
+
399
+ // ---------- settings ----------
400
+
401
+ toggleSettings() {
402
+ this.showSettings(this.el.settings.hidden);
403
+ }
404
+
405
+ async showSettings(show) {
406
+ this.el.settings.hidden = !show;
407
+ this.el.log.hidden = show;
408
+ this.el.form.hidden = show;
409
+ this.el.gear.classList.toggle('active', show);
410
+ this.el.target.hidden = show || !this.target;
411
+ if (show) await this.renderSettings();
412
+ }
413
+
414
+ async renderSettings() {
415
+ const box = this.el.settings;
416
+ let state;
417
+ try {
418
+ state = await this.api('GET', '/state');
419
+ } catch (err) {
420
+ box.textContent = err.message;
421
+ return;
422
+ }
423
+ this.el.agent.textContent = state.agent;
424
+ const current = state.agents.find((a) => a.name === state.settings.agent);
425
+ const mine = state.settings[current.name] ?? {};
426
+ // Choices with a `group` go into <optgroup>s, in the order the groups first appear.
427
+ const options = (choices, value) => {
428
+ const option = (c) => `<option value="${escapeHtml(c.value)}"${c.value === value ? ' selected' : ''}${c.disabled ? ' disabled' : ''}>${escapeHtml(c.label)}</option>`;
429
+ return [...new Set(choices.map((c) => c.group ?? ''))]
430
+ .map((g) => {
431
+ const inner = choices.filter((c) => (c.group ?? '') === g).map(option).join('');
432
+ return g ? `<optgroup label="${escapeHtml(g)}">${inner}</optgroup>` : inner;
433
+ })
434
+ .join('');
435
+ };
436
+ const select = (key, label, choices, value, hint = '') => `
437
+ <label>${escapeHtml(label)}<select data-key="${escapeHtml(key)}">${options(choices, value)}</select>${hint ? `<small>${escapeHtml(hint)}</small>` : ''}</label>`;
438
+ const triggers = this.triggers;
439
+ box.innerHTML = `
440
+ <h3>Agent</h3>
441
+ ${state.agents.length < 2 ? '' : select('agent', 'CLI', state.agents.map((a) => ({
442
+ value: a.name,
443
+ label: a.version ? `${a.label} (${a.version})` : `${a.label}: not installed`,
444
+ disabled: !a.version,
445
+ })), current.name, 'Each agent has its own conversation. Switching back to an agent resumes its context.')}
446
+ ${Object.entries(current.settings).map(([key, spec]) => Array.isArray(spec)
447
+ ? select(key, SETTING_LABELS[key] ?? key, spec, mine[key] ?? '', SETTING_HINTS[key])
448
+ : spec.type === 'action'
449
+ ? `<div class="action"><button type="button" data-action="${escapeHtml(spec.action)}">${escapeHtml(spec.label)}</button>${spec.hint ? `<small>${escapeHtml(spec.hint)}</small>` : ''}</div>`
450
+ : `<label>${escapeHtml(spec.label ?? key)}<input type="${spec.secret ? 'password' : 'text'}" data-text="${escapeHtml(key)}" value="${escapeHtml((!spec.readonly && mine[key]) || spec.default || '')}" placeholder="${escapeHtml(spec.placeholder ?? '')}" spellcheck="false"${spec.readonly ? ' disabled' : ''}>${spec.hint ? `<small>${escapeHtml(spec.hint)}</small>` : ''}</label>`).join('')}
451
+ <h3>Element picking</h3>
452
+ ${TRIGGERS.map(([value, label]) => `<label class="check"><input type="checkbox" data-trigger="${value}"${triggers.includes(value) ? ' checked' : ''}> ${label}</label>`).join('')}
453
+ <h3>Panel</h3>
454
+ ${select('side', 'Position', [{ value: 'right', label: 'Right' }, { value: 'left', label: 'Left' }], localStorage.getItem(STORE_SIDE) ?? 'right')}
455
+ <h3>Conversation</h3>
456
+ <p class="meta">${escapeHtml(current.label)} · ${state.session.started ? `session <code>${escapeHtml(String(state.session.id).slice(0, 8))}</code>` : 'not started yet'}${state.session.totalCostUsd ? ` · total $${state.session.totalCostUsd.toFixed(3)}` : ''}</p>`;
457
+
458
+ for (const el of box.querySelectorAll('select[data-key]')) {
459
+ el.onchange = () => this.changeSetting(el.dataset.key, el.value, current.name);
460
+ }
461
+ for (const el of box.querySelectorAll('input[data-text]')) {
462
+ // Saved on blur or Enter, not on every keystroke.
463
+ el.onchange = () => this.changeSetting(el.dataset.text, el.value, current.name);
464
+ el.onkeydown = (e) => e.key === 'Enter' && el.blur();
465
+ }
466
+ // Buttons the agent offers (e.g. signing in to a provider in the browser editor).
467
+ for (const el of box.querySelectorAll('button[data-action]')) {
468
+ el.onclick = async () => {
469
+ try {
470
+ await this.api('POST', '/action', { agent: current.name, action: el.dataset.action });
471
+ } catch (err) {
472
+ return this.flashSettingsError(err.message);
473
+ }
474
+ await this.renderSettings();
475
+ };
476
+ }
477
+ for (const el of box.querySelectorAll('input[data-trigger]')) {
478
+ el.onchange = () => {
479
+ const picked = [...box.querySelectorAll('input[data-trigger]:checked')].map((i) => i.dataset.trigger);
480
+ localStorage.setItem(STORE_TRIGGERS, JSON.stringify(picked));
481
+ this._triggers = picked;
482
+ this.updateHint();
483
+ };
484
+ }
485
+ }
486
+
487
+ async changeSetting(key, value, agentName) {
488
+ if (key === 'side') {
489
+ localStorage.setItem(STORE_SIDE, value);
490
+ localStorage.removeItem(STORE_GEOMETRY); // choosing a side docks the panel there
491
+ this.applySide();
492
+ this.applyGeometry();
493
+ return;
494
+ }
495
+ try {
496
+ await this.api('POST', '/settings', key === 'agent' ? { agent: value } : { [agentName]: { [key]: value } });
497
+ } catch (err) {
498
+ this.flashSettingsError(err.message);
499
+ }
500
+ await this.renderSettings();
501
+ }
502
+
503
+ flashSettingsError(text) {
504
+ const p = document.createElement('p');
505
+ p.className = 'msg error';
506
+ p.textContent = text;
507
+ this.el.settings.prepend(p);
508
+ }
509
+
510
+ updateHint() {
511
+ const labels = TRIGGERS.filter(([v]) => this.triggers.includes(v)).map(([, l]) => l.split(' (')[0]);
512
+ this.el.hint.textContent = labels.length ? `${labels.join(' / ')} selects an element on the page` : 'Element picking is off (⚙)';
513
+ }
514
+
515
+ connect() {
516
+ this.el.log.textContent = '';
517
+ this.live = null;
518
+ this.unsubscribe = this.transport.subscribe({
519
+ onEvent: (ev) => (this.lastEventAt = Date.now(), this.lastPingAt = Date.now(), this.handle(ev)),
520
+ onPing: () => (this.lastPingAt = Date.now()),
521
+ onCommand: (cmd) => this.command(cmd),
522
+ tab: this.tab,
523
+ onReady: ({ busy }) => {
524
+ this.caughtUp = true; // events from here on are new, not the replayed history
525
+ this.setBusy(busy);
526
+ this.scroll(true);
527
+ },
528
+ onLost: (text) => {
529
+ this.line('error', text);
530
+ this.unsubscribe = null;
531
+ },
532
+ });
533
+ this.api('GET', '/state').then((s) => (this.el.agent.textContent = s.agent)).catch(() => {});
534
+ this.loadHistory();
535
+ }
536
+
537
+ // ---------- versions ----------
538
+
539
+ loadHistory() {
540
+ this.api('GET', '/history').then((h) => this.showHistory(h)).catch(() => {});
541
+ }
542
+
543
+ showHistory(h) {
544
+ this.history = h;
545
+ const { versions, current } = h;
546
+ this.el.versions.hidden = !h.enabled || versions.length < 2;
547
+ this.el.vnum.textContent = `v${current + 1}/${versions.length}`;
548
+ const v = versions[current];
549
+ this.el.vnum.title = v ? `${v.label} · ${new Date(v.ts).toLocaleString()}` : '';
550
+ this.el.back.disabled = this.busy || current <= 0;
551
+ this.el.fwd.disabled = this.busy || current >= versions.length - 1;
552
+ const tip = (i) => (versions[i] ? `: ${versions[i].label}` : '');
553
+ this.el.back.title = `Previous version${tip(current - 1)}`;
554
+ this.el.fwd.title = `Next version${tip(current + 1)}`;
555
+ }
556
+
557
+ async restoreVersion(index) {
558
+ try {
559
+ this.showHistory(await this.api('POST', '/history/restore', { index }));
560
+ } catch (err) {
561
+ this.line('error', err.message);
562
+ }
563
+ }
564
+
565
+ api(method, path, body) {
566
+ return this.transport.request(method, path, body);
567
+ }
568
+
569
+ async send() {
570
+ const message = this.el.input.value.trim();
571
+ if (!message) return;
572
+ // After an edit and reload the element may have moved or disappeared: describe it again.
573
+ if (this.target && this.targetEl?.isConnected) this.target = describe(this.targetEl, this.cfg.srcAttr);
574
+ this.setBusy(true);
575
+ try {
576
+ await this.api('POST', '/send', {
577
+ message,
578
+ element: this.target,
579
+ page: { url: location.pathname + location.search, title: document.title },
580
+ });
581
+ this.el.input.value = '';
582
+ sessionStorage.removeItem(STORE_DRAFT);
583
+ } catch (err) {
584
+ this.setBusy(false);
585
+ this.line('error', err.message);
586
+ }
587
+ }
588
+
589
+ stop() {
590
+ this.api('POST', '/stop').catch((err) => this.line('error', err.message));
591
+ }
592
+
593
+ reset() {
594
+ if (this.el.log.childElementCount && !confirmReset()) {
595
+ this.line('status', 'Click "New" again to discard the context and start a new conversation.');
596
+ this.scroll(true);
597
+ return;
598
+ }
599
+ this.api('POST', '/reset').catch((err) => this.line('error', err.message));
600
+ }
601
+
602
+ setBusy(busy) {
603
+ this.busy = busy;
604
+ this.el.send.textContent = busy ? 'Stop' : 'Send';
605
+ this.el.send.classList.toggle('stop', busy);
606
+ this.el.panel.classList.toggle('busy', busy);
607
+ this.el.fab.classList.toggle('busy', busy);
608
+ this.trackActivity(busy);
609
+ if (this.history) this.showHistory(this.history);
610
+ }
611
+
612
+ // ---------- link to the server (MCP tools) ----------
613
+
614
+ startLink(capture) {
615
+ // The same tab keeps its id across reloads, so its console buffer on the server stays one history.
616
+ let tab = sessionStorage.getItem(STORE_TAB);
617
+ if (!tab) sessionStorage.setItem(STORE_TAB, (tab = Math.random().toString(36).slice(2, 12)));
618
+ const nav = Number(sessionStorage.getItem(STORE_NAV) ?? 0) + 1;
619
+ sessionStorage.setItem(STORE_NAV, String(nav));
620
+ this.tab = tab;
621
+ capture.nav = nav;
622
+ const post = (path, body) => this.api('POST', path, { tab, ...body }).catch(() => {}); // a missed report is not an error to show
623
+ this.post = post;
624
+ const hello = () => post('/page/hello', {
625
+ url: location.href, title: document.title, nav, origin: location.origin,
626
+ viewport: { width: innerWidth, height: innerHeight }, visible: document.visibilityState === 'visible',
627
+ });
628
+ hello();
629
+ addEventListener('focus', () => post('/page/focus'));
630
+ document.addEventListener('visibilitychange', () => document.visibilityState === 'visible' && post('/page/focus'));
631
+ setInterval(() => {
632
+ const entries = capture.drain();
633
+ if (entries.length) post('/page/log', { entries });
634
+ }, 1000);
635
+ this.connect();
636
+ }
637
+
638
+ reportSelection() {
639
+ if (!this.post) return;
640
+ const page = { url: location.pathname + location.search, title: document.title };
641
+ this.post('/page/selection', { element: this.target, page });
642
+ }
643
+
644
+ /** A read-only command from an MCP tool; the answer goes back over POST. */
645
+ async command({ id, cmd, args }) {
646
+ let out;
647
+ try {
648
+ out = { ok: true, data: runCommand(cmd, args ?? {}, this.cfg.srcAttr) };
649
+ } catch (err) {
650
+ out = { ok: false, error: err.message };
651
+ }
652
+ this.post('/page/result', { id, ...out });
653
+ }
654
+
655
+ // ---------- activity ----------
656
+
657
+ /** While the agent works: elapsed time, time since its last output, and whether the connection is alive. */
658
+ trackActivity(busy) {
659
+ clearInterval(this.activityTimer);
660
+ this.el.activity.hidden = !busy;
661
+ if (!busy) return;
662
+ this.busySince = Date.now();
663
+ this.lastTool = null;
664
+ this.lastEventAt = this.lastPingAt = Date.now();
665
+ this.activityTimer = setInterval(() => this.drawActivity(), 1000);
666
+ this.drawActivity();
667
+ }
668
+
669
+ drawActivity() {
670
+ const now = Date.now();
671
+ const lost = this.unsubscribe && now - this.lastPingAt > 2.5 * PING_MS;
672
+ const quiet = now - this.lastEventAt;
673
+ const parts = [`Working ${duration(now - this.busySince)}`];
674
+ parts.push(quiet < 3000 ? 'receiving output' : `no output for ${duration(quiet)}`);
675
+ if (this.lastTool) parts.push(`last: ${this.lastTool}`);
676
+ this.el.activity.textContent = lost
677
+ ? 'No sign of life from the dev server for a while: it may have restarted. Reload the page.'
678
+ : parts.join(' · ') + (quiet > 60000 ? ' (the model or a tool may just be slow; Stop ends it)' : '');
679
+ this.el.activity.classList.toggle('lost', !!lost);
680
+ }
681
+
682
+ // ---------- agent events ----------
683
+
684
+ handle(ev) {
685
+ const stick = this.atBottom();
686
+ switch (ev.type) {
687
+ case 'reset':
688
+ this.el.log.textContent = '';
689
+ this.live = null;
690
+ this.setBusy(false);
691
+ break;
692
+ case 'user': {
693
+ const div = this.line('user', '');
694
+ div.textContent = ev.text;
695
+ const where = ev.element?.src ?? ev.element?.selector;
696
+ const how = [ev.agent, ev.settings?.model, ev.settings?.effort].filter(Boolean).join(' · ');
697
+ if (where || how) {
698
+ const chip = document.createElement('code');
699
+ chip.textContent = [where, how].filter(Boolean).join(' · ');
700
+ div.prepend(chip);
701
+ }
702
+ this.live = null;
703
+ break;
704
+ }
705
+ case 'status':
706
+ if (ev.busy) this.setBusy(true);
707
+ else this.line('status', ev.text);
708
+ break;
709
+ case 'delta':
710
+ this.live ??= this.line('assistant live', '');
711
+ this.live.dataset.raw = (this.live.dataset.raw ?? '') + ev.text;
712
+ this.live.innerHTML = render(this.live.dataset.raw, ev.plain);
713
+ break;
714
+ case 'text':
715
+ if (this.live) {
716
+ this.live.classList.remove('live');
717
+ this.live.innerHTML = render(ev.text, ev.plain);
718
+ this.live = null;
719
+ } else {
720
+ this.line('assistant', '').innerHTML = render(ev.text, ev.plain);
721
+ }
722
+ break;
723
+ case 'tool':
724
+ this.live = null;
725
+ this.line('tool', `${TOOL_ICONS[ev.name] ?? '•'} ${ev.name} ${ev.summary ?? ''}`);
726
+ this.lastTool = `${ev.name} ${ev.summary ?? ''}`.trim().slice(0, 60);
727
+ break;
728
+ case 'tool-error':
729
+ this.line('tool error', ev.text);
730
+ break;
731
+ case 'permission': {
732
+ const div = this.line('permission', '');
733
+ div.dataset.id = ev.id;
734
+ const ask = document.createElement('span');
735
+ ask.textContent = `${ev.name} ${ev.summary ?? ''}`.trim();
736
+ const allow = document.createElement('button');
737
+ allow.textContent = 'Allow';
738
+ const deny = document.createElement('button');
739
+ deny.textContent = 'Deny';
740
+ deny.className = 'deny';
741
+ for (const [button, ok] of [[allow, true], [deny, false]]) {
742
+ button.onclick = () => {
743
+ allow.disabled = deny.disabled = true;
744
+ this.api('POST', '/permission', { id: ev.id, allow: ok }).catch((err) => {
745
+ allow.disabled = deny.disabled = false;
746
+ this.line('error', err.message);
747
+ });
748
+ };
749
+ }
750
+ const label = document.createElement('b');
751
+ label.textContent = 'Allow this? ';
752
+ div.append(label, ask, allow, deny);
753
+ break;
754
+ }
755
+ case 'permission-answer': {
756
+ const div = [...this.el.log.querySelectorAll('.msg.permission')].find((d) => d.dataset.id === ev.id);
757
+ if (!div) break;
758
+ div.querySelector('b').textContent = ev.cancelled ? 'Not answered: ' : ev.allow ? 'Allowed: ' : 'Denied: ';
759
+ div.classList.add(ev.allow ? 'allowed' : 'answered');
760
+ div.querySelectorAll('button').forEach((b) => b.remove());
761
+ break;
762
+ }
763
+ case 'denied':
764
+ this.line('denied', `Denied: ${ev.name} ${ev.summary ?? ''}. Allow it in options.claude.allowedTools.`);
765
+ break;
766
+ case 'history':
767
+ // Without hot reload (CLI, Next.js wrapper) the page shows the new files after a reload.
768
+ // A moment first: a dev server behind the proxy may not have noticed the change yet.
769
+ if (this.cfg.reload && ev.reload && this.caughtUp) setTimeout(() => location.reload(), 400);
770
+ else this.loadHistory();
771
+ break;
772
+ case 'done': {
773
+ this.live = null;
774
+ this.setBusy(false);
775
+ if (!ev.ok) this.line('error', ev.error ?? 'The agent finished with an error.');
776
+ const meta = [ev.durationMs && `${Math.round(ev.durationMs / 1000)} s`, ev.costUsd != null && `$${ev.costUsd.toFixed(3)}`]
777
+ .filter(Boolean).join(' · ');
778
+ if (ev.ok) this.line('meta', meta ? `done · ${meta}` : 'done');
779
+ break;
780
+ }
781
+ }
782
+ this.scroll(stick);
783
+ }
784
+
785
+ line(kind, text) {
786
+ const div = document.createElement('div');
787
+ div.className = `msg ${kind}`;
788
+ div.textContent = text;
789
+ this.el.log.appendChild(div);
790
+ return div;
791
+ }
792
+
793
+ atBottom() {
794
+ const l = this.el.log;
795
+ return l.scrollHeight - l.scrollTop - l.clientHeight < 40;
796
+ }
797
+
798
+ scroll(stick) {
799
+ if (stick) this.el.log.scrollTop = this.el.log.scrollHeight;
800
+ }
801
+ }
802
+
803
+ // ---------- element description for the agent ----------
804
+
805
+ function describe(el, srcAttr) {
806
+ const annotated = el.closest(`[${srcAttr}]`);
807
+ const src = annotated?.getAttribute(srcAttr);
808
+
809
+ // Where the component is used: nearest ancestors from other files.
810
+ const chain = [];
811
+ let file = src?.split(':')[0];
812
+ for (let p = annotated?.parentElement?.closest(`[${srcAttr}]`); p && chain.length < 4; p = p.parentElement?.closest(`[${srcAttr}]`)) {
813
+ const s = p.getAttribute(srcAttr);
814
+ const f = s.split(':')[0];
815
+ if (f !== file) {
816
+ chain.push(s);
817
+ file = f;
818
+ }
819
+ }
820
+
821
+ const testEl = el.closest('[data-testid],[data-test-id],[data-test]');
822
+ return {
823
+ src,
824
+ exact: annotated === el,
825
+ chain,
826
+ tag: openTag(el),
827
+ testId: testEl?.getAttribute('data-testid') ?? testEl?.getAttribute('data-test-id') ?? testEl?.getAttribute('data-test') ?? undefined,
828
+ selector: selectorOf(el),
829
+ text: (el.innerText ?? el.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 200) || undefined,
830
+ html: cleanHtml(el.outerHTML, srcAttr).slice(0, 1500),
831
+ };
832
+ }
833
+
834
+ const DEFAULT_STYLES = ['display', 'position', 'width', 'height', 'color', 'background-color', 'font-size', 'font-weight', 'margin', 'padding', 'overflow', 'visibility'];
835
+
836
+ /** The commands MCP tools may run in the page: all of them only read. */
837
+ function runCommand(cmd, args, srcAttr) {
838
+ if (cmd === 'info') {
839
+ const d = document.documentElement;
840
+ return {
841
+ url: location.href, title: document.title, readyState: document.readyState,
842
+ viewport: { width: innerWidth, height: innerHeight, devicePixelRatio },
843
+ scroll: { x: Math.round(scrollX), y: Math.round(scrollY) },
844
+ document: { width: d.scrollWidth, height: d.scrollHeight },
845
+ lang: d.lang || undefined, visible: document.visibilityState === 'visible',
846
+ };
847
+ }
848
+ if (cmd === 'query') {
849
+ let found;
850
+ try {
851
+ found = document.querySelectorAll(args.selector);
852
+ } catch {
853
+ throw new Error(`"${args.selector}" is not a valid CSS selector.`);
854
+ }
855
+ const styles = args.styles?.length ? args.styles : DEFAULT_STYLES;
856
+ return {
857
+ count: found.length,
858
+ elements: [...found].slice(0, args.limit ?? 3).map((el) => {
859
+ const cs = getComputedStyle(el);
860
+ const r = el.getBoundingClientRect();
861
+ return {
862
+ ...describe(el, srcAttr),
863
+ rect: { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) },
864
+ visible: r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none',
865
+ styles: Object.fromEntries(styles.map((p) => [p, cs.getPropertyValue(p)])),
866
+ };
867
+ }),
868
+ };
869
+ }
870
+ throw new Error(`Unknown command ${cmd}.`);
871
+ }
872
+
873
+ const LEVELS = ['debug', 'log', 'info', 'warn', 'error'];
874
+
875
+ /**
876
+ * Collects console output, uncaught errors, rejected promises and failed requests
877
+ * in a queue the overlay sends to the server. WebAI's own requests are left out.
878
+ */
879
+ function installCapture(base) {
880
+ const queue = [];
881
+ const cap = {
882
+ nav: 0,
883
+ drain: () => queue.splice(0),
884
+ add(level, kind, text, stack) {
885
+ queue.push({ level, kind, text: String(text).slice(0, 4000), stack: stack && String(stack).slice(0, 4000), nav: cap.nav });
886
+ if (queue.length > 300) queue.shift();
887
+ },
888
+ };
889
+ for (const level of LEVELS) {
890
+ const orig = console[level];
891
+ console[level] = function (...args) {
892
+ try {
893
+ cap.add(level, 'console', args.map(formatArg).join(' '), args.find((a) => a instanceof Error)?.stack);
894
+ } catch {} // capturing must never break the page's own logging
895
+ return orig.apply(this, args);
896
+ };
897
+ }
898
+ addEventListener('error', (e) => {
899
+ if (e.target && e.target !== window) {
900
+ // A resource that failed to load (the error event doesn't bubble, so only the capture phase sees it).
901
+ const t = e.target;
902
+ cap.add('error', 'network', `Failed to load <${t.tagName?.toLowerCase()}> ${t.src || t.href || ''}`);
903
+ } else {
904
+ cap.add('error', 'error', `${e.message} (${e.filename}:${e.lineno}:${e.colno})`, e.error?.stack);
905
+ }
906
+ }, true);
907
+ addEventListener('unhandledrejection', (e) => cap.add('error', 'error', `Unhandled promise rejection: ${formatArg(e.reason)}`, e.reason?.stack));
908
+ const realFetch = window.fetch;
909
+ window.fetch = async function (input, init) {
910
+ const url = typeof input === 'string' ? input : input?.url ?? String(input);
911
+ const method = (init?.method ?? input?.method ?? 'GET').toUpperCase();
912
+ if (url.includes(base)) return realFetch.call(this, input, init);
913
+ try {
914
+ const res = await realFetch.call(this, input, init);
915
+ if (!res.ok) cap.add('error', 'network', `${method} ${url} → ${res.status} ${res.statusText}`.trim());
916
+ return res;
917
+ } catch (err) {
918
+ if (err?.name !== 'AbortError') cap.add('error', 'network', `${method} ${url} failed: ${err?.message ?? err}`);
919
+ throw err;
920
+ }
921
+ };
922
+ return cap;
923
+ }
924
+
925
+ function formatArg(a) {
926
+ if (typeof a === 'string') return a;
927
+ if (a instanceof Error) return a.stack || `${a.name}: ${a.message}`;
928
+ if (a instanceof Element) return openTag(a);
929
+ if (a && typeof a === 'object') {
930
+ const seen = new WeakSet();
931
+ try {
932
+ return JSON.stringify(a, (k, v) => {
933
+ if (typeof v === 'bigint') return `${v}n`;
934
+ if (v && typeof v === 'object') {
935
+ if (seen.has(v)) return '[circular]';
936
+ seen.add(v);
937
+ }
938
+ return v;
939
+ }).slice(0, 1000);
940
+ } catch {
941
+ return Object.prototype.toString.call(a);
942
+ }
943
+ }
944
+ return String(a);
945
+ }
946
+
947
+ function duration(ms) {
948
+ const s = Math.floor(ms / 1000);
949
+ return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;
950
+ }
951
+
952
+ function findElement(info, srcAttr) {
953
+ if (info.src) {
954
+ const els = document.querySelectorAll(`[${srcAttr}="${CSS.escape(info.src)}"]`);
955
+ if (els.length === 1) return els[0];
956
+ }
957
+ try {
958
+ return document.querySelector(info.selector);
959
+ } catch {
960
+ return null;
961
+ }
962
+ }
963
+
964
+ function openTag(el) {
965
+ const attrs = [...el.attributes]
966
+ .filter((a) => !noise(a.name))
967
+ .map((a) => (a.value ? `${a.name}="${a.value.slice(0, 80)}"` : a.name));
968
+ return `<${el.tagName.toLowerCase()}${attrs.length ? ' ' + attrs.join(' ') : ''}>`;
969
+ }
970
+
971
+ function noise(name) {
972
+ return name.startsWith('data-webai-') || name.startsWith('data-astro-cid') || name === 'data-astro-source-file' || name === 'data-astro-source-loc';
973
+ }
974
+
975
+ function cleanHtml(html, srcAttr) {
976
+ return html
977
+ .replace(new RegExp(`\\s${srcAttr}="[^"]*"`, 'g'), '')
978
+ .replace(/\sdata-astro-cid-[\w-]+(="[^"]*")?/g, '');
979
+ }
980
+
981
+ function selectorOf(el) {
982
+ const parts = [];
983
+ for (let n = el; n && n.nodeType === 1 && n !== document.documentElement && parts.length < 6; n = n.parentElement) {
984
+ if (n.id) {
985
+ parts.unshift(`#${CSS.escape(n.id)}`);
986
+ break;
987
+ }
988
+ let part = n.tagName.toLowerCase();
989
+ const classes = [...n.classList].filter((c) => !c.startsWith('astro-')).slice(0, 2);
990
+ if (classes.length) part += classes.map((c) => `.${CSS.escape(c)}`).join('');
991
+ const same = n.parentElement ? [...n.parentElement.children].filter((c) => c.tagName === n.tagName) : [];
992
+ if (same.length > 1) part += `:nth-of-type(${same.indexOf(n) + 1})`;
993
+ parts.unshift(part);
994
+ }
995
+ return parts.join(' > ');
996
+ }
997
+
998
+ // ---------- helpers ----------
999
+
1000
+ function box(r) {
1001
+ return { top: `${r.top}px`, left: `${r.left}px`, width: `${r.width}px`, height: `${r.height}px` };
1002
+ }
1003
+
1004
+ function readJson(s) {
1005
+ try {
1006
+ return s ? JSON.parse(s) : null;
1007
+ } catch {
1008
+ return null;
1009
+ }
1010
+ }
1011
+
1012
+ function confirmReset() {
1013
+ // No window.confirm: it blocks the page. A second click within 3 s confirms.
1014
+ const now = Date.now();
1015
+ const ok = now - (confirmReset.at ?? 0) < 3000;
1016
+ confirmReset.at = now;
1017
+ return ok;
1018
+ }
1019
+
1020
+ function escapeHtml(s) {
1021
+ return String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
1022
+ }
1023
+
1024
+ /** Custom command output is plain text; agent replies are Markdown. */
1025
+ function render(text, plain) {
1026
+ return plain ? `<pre class="plain">${escapeHtml(text)}</pre>` : markdown(text);
1027
+ }
1028
+
1029
+ function markdown(src) {
1030
+ const blocks = escapeHtml(src).split(/```(?:[\w-]*)\n?/);
1031
+ return blocks
1032
+ .map((b, i) =>
1033
+ i % 2
1034
+ ? `<pre>${b}</pre>`
1035
+ : b
1036
+ .replace(/`([^`\n]+)`/g, '<code>$1</code>')
1037
+ .replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
1038
+ .replace(/\n/g, '<br>'),
1039
+ )
1040
+ .join('');
1041
+ }
1042
+
1043
+ const SETTING_LABELS = { model: 'Model', effort: 'Effort', thinking: 'Thinking', provider: 'Provider' };
1044
+ const SETTING_HINTS = {
1045
+ model: 'Switching models mid-conversation makes the next message more expensive once, because the new model has to write the whole context to the cache again.',
1046
+ };
1047
+
1048
+ const GEAR_ICON = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>`;
1049
+
1050
+ const STYLES = `
1051
+ :host { all: initial; }
1052
+ * { box-sizing: border-box; }
1053
+ .hover, .pick {
1054
+ position: fixed; pointer-events: none; z-index: 2147483646;
1055
+ outline: 2px solid #7c5cff; background: rgba(124, 92, 255, .12); border-radius: 2px;
1056
+ }
1057
+ .pick { outline: 2px dashed #ffb020; background: transparent; }
1058
+ .label {
1059
+ position: absolute; left: -2px; bottom: 100%; margin-bottom: 4px; white-space: nowrap;
1060
+ font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; color: #fff;
1061
+ background: #7c5cff; padding: 2px 6px; border-radius: 3px;
1062
+ }
1063
+ .label.below { bottom: auto; top: 100%; margin: 4px 0 0; }
1064
+ [hidden] { display: none !important; }
1065
+ .panel {
1066
+ position: fixed; right: 16px; bottom: 16px; z-index: 2147483647;
1067
+ width: min(400px, calc(100vw - 32px)); height: min(560px, calc(100vh - 32px));
1068
+ display: flex; flex-direction: column;
1069
+ font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1070
+ color: #e7e7ee; background: #17171f; border: 1px solid #33334a; border-radius: 10px;
1071
+ box-shadow: 0 12px 40px rgba(0,0,0,.45); overflow: hidden;
1072
+ }
1073
+ .panel.left { right: auto; left: 16px; }
1074
+ .panel header { cursor: move; user-select: none; touch-action: none; }
1075
+ .panel header button { cursor: pointer; }
1076
+ .panel.dragging { user-select: none; opacity: .97; }
1077
+ .grip { position: absolute; width: 14px; height: 14px; z-index: 2; touch-action: none; }
1078
+ .grip.nw { top: 0; left: 0; cursor: nwse-resize; }
1079
+ .grip.ne { top: 0; right: 0; cursor: nesw-resize; }
1080
+ .grip.sw { bottom: 0; left: 0; cursor: nesw-resize; }
1081
+ .grip.se { bottom: 0; right: 0; cursor: nwse-resize; }
1082
+ .grip.se::after { content: ""; position: absolute; right: 3px; bottom: 3px; width: 7px; height: 7px;
1083
+ border-right: 2px solid #4a4a66; border-bottom: 2px solid #4a4a66; }
1084
+ .fab {
1085
+ position: fixed; right: 16px; bottom: 16px; z-index: 2147483647;
1086
+ width: 44px; height: 44px; border-radius: 50%; padding: 0;
1087
+ font: 20px/1 -apple-system, BlinkMacSystemFont, sans-serif; color: #fff;
1088
+ background: #7c5cff; border: 0; box-shadow: 0 6px 20px rgba(0,0,0,.4); opacity: .85;
1089
+ }
1090
+ .fab:hover { background: #8d71ff; opacity: 1; }
1091
+ .fab.left { right: auto; left: 16px; }
1092
+ .activity { margin: 0 10px; color: #8f8fa8; font: 11.5px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }
1093
+ .activity.lost { color: #ff7a7a; }
1094
+ .fab.busy { animation: pulse 1s infinite; }
1095
+ .gear { display: inline-flex; align-items: center; justify-content: center; padding: 3px 6px; }
1096
+ .gear svg { width: 18px; height: 18px; }
1097
+ header button.active { background: #7c5cff; border-color: #7c5cff; }
1098
+ .settings { flex: 1; overflow-y: auto; padding: 4px 12px 12px; }
1099
+ .settings h3 { margin: 12px 0 6px; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: #8f8fa8; }
1100
+ .settings label { display: block; margin-bottom: 8px; }
1101
+ .settings select {
1102
+ display: block; width: 100%; margin-top: 3px; font: inherit; color: inherit;
1103
+ background: #101018; border: 1px solid #33334a; border-radius: 6px; padding: 4px 6px;
1104
+ }
1105
+ .settings input[data-text] {
1106
+ display: block; width: 100%; margin-top: 3px; color: inherit; background: #101018;
1107
+ border: 1px solid #33334a; border-radius: 6px; padding: 5px 7px;
1108
+ font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
1109
+ }
1110
+ .settings input[data-text]:focus { border-color: #7c5cff; outline: none; }
1111
+ .settings input[data-text]:disabled { opacity: .6; cursor: not-allowed; }
1112
+ .settings small { display: block; margin-top: 3px; color: #8f8fa8; font-size: 11px; }
1113
+ .settings .action { margin-bottom: 10px; }
1114
+ .settings .action button { width: 100%; padding: 6px 8px; background: #7c5cff; border-color: #7c5cff; }
1115
+ .settings label.check { display: flex; gap: 6px; align-items: center; margin-bottom: 4px; }
1116
+ .settings .meta { color: #8f8fa8; font-size: 12px; }
1117
+ header { display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid #2a2a3c; }
1118
+ header .agent { color: #8f8fa8; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
1119
+ .versions { display: flex; align-items: center; gap: 2px; font-size: 12px; color: #8f8fa8; }
1120
+ .versions button { padding: 1px 6px; font-size: 10px; }
1121
+ .versions button:disabled { opacity: .4; cursor: default; }
1122
+ .vnum { min-width: 38px; text-align: center; cursor: help; }
1123
+ .spacer { flex: 1; }
1124
+ button {
1125
+ font: inherit; color: #e7e7ee; background: #2a2a3c; border: 1px solid #3a3a52;
1126
+ border-radius: 6px; padding: 3px 8px; cursor: pointer;
1127
+ }
1128
+ button:hover { background: #34344a; }
1129
+ .log { flex: 1; overflow-y: auto; padding: 10px; display: flex; flex-direction: column; gap: 8px; }
1130
+ .msg { white-space: normal; overflow-wrap: anywhere; }
1131
+ .msg.user {
1132
+ align-self: flex-end; max-width: 90%; background: #3b2f86; padding: 6px 10px;
1133
+ border-radius: 10px 10px 2px 10px; white-space: pre-wrap;
1134
+ }
1135
+ .msg.user code { display: block; font-size: 11px; color: #c9bfff; margin-bottom: 2px; }
1136
+ .msg.assistant { background: #22222f; padding: 6px 10px; border-radius: 10px 10px 10px 2px; }
1137
+ .msg.assistant.live::after { content: "▍"; color: #7c5cff; }
1138
+ .msg.tool, .msg.status, .msg.meta { color: #8f8fa8; font: 11.5px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }
1139
+ .msg.meta { text-align: right; }
1140
+ .msg.error, .msg.tool.error { color: #ff7a7a; }
1141
+ .msg.denied { color: #ffb020; font-size: 12px; }
1142
+ .msg.permission { background: #2a2418; border: 1px solid #5c4a1e; border-radius: 8px; padding: 6px 10px; font-size: 12px; color: #ffd37a; }
1143
+ .msg.permission span { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; word-break: break-all; }
1144
+ .msg.permission button { margin: 6px 6px 0 0; font: inherit; padding: 2px 12px; border: 0; border-radius: 6px; background: #7c5cff; color: #fff; cursor: pointer; }
1145
+ .msg.permission button.deny { background: #3a3a50; }
1146
+ .msg.permission button:disabled { opacity: 0.5; cursor: default; }
1147
+ .msg.permission.allowed, .msg.permission.answered { background: none; border-color: transparent; padding: 0; color: #8f8fa8; }
1148
+ code, pre { font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }
1149
+ .msg code { background: #2d2d40; padding: 0 3px; border-radius: 3px; }
1150
+ pre.plain { margin: 0; background: transparent; padding: 0; white-space: pre-wrap; }
1151
+ pre { background: #101018; padding: 8px; border-radius: 6px; overflow-x: auto; white-space: pre; }
1152
+ .target {
1153
+ display: flex; align-items: center; gap: 6px; margin: 0 10px; padding: 4px 6px 4px 8px;
1154
+ background: #2b2414; border: 1px solid #5c4a1c; border-radius: 6px; color: #ffcf70;
1155
+ }
1156
+ .target code { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1157
+ .target button { padding: 0 6px; background: transparent; border: 0; color: inherit; }
1158
+ form { display: flex; gap: 6px; padding: 8px 10px; }
1159
+ textarea {
1160
+ flex: 1; resize: none; font: inherit; color: inherit; background: #101018;
1161
+ border: 1px solid #33334a; border-radius: 6px; padding: 6px 8px; outline: none;
1162
+ }
1163
+ textarea:focus { border-color: #7c5cff; }
1164
+ .send { background: #7c5cff; border-color: #7c5cff; color: #fff; }
1165
+ .send.stop { background: #b33a3a; border-color: #b33a3a; }
1166
+ .panel.busy header strong::after { content: " ●"; color: #7c5cff; animation: pulse 1s infinite; }
1167
+ @keyframes pulse { 50% { opacity: .2; } }
1168
+ footer { padding: 0 10px 8px; color: #6f6f88; font-size: 11px; }
1169
+ `;