@extension-use/host 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1019 @@
1
+ import {
2
+ OPT_IN_GROUPS,
3
+ allBuiltinGroups,
4
+ builtinGroups,
5
+ configureTabCapture,
6
+ waitForLoad
7
+ } from "../chunk-QYMPEWZP.js";
8
+ import {
9
+ CONTENT_CANCEL,
10
+ CONTENT_EVENT,
11
+ CONTENT_MESSAGE,
12
+ FRAME_PORT,
13
+ UI_PORT
14
+ } from "../chunk-5X4QMMKA.js";
15
+
16
+ // src/background/index.ts
17
+ import { ExtensionUseError as ExtensionUseError2, matchAny as matchAny3, matchPattern } from "@extension-use/protocol";
18
+ import { envelope as envelope2, randomId as newId } from "@extension-use/protocol";
19
+
20
+ // src/background/remote.ts
21
+ import { matchAny } from "@extension-use/protocol";
22
+
23
+ // src/background/remote-link.ts
24
+ import { REMOTE_PING_MS, agentKeyId, agentNonce, agentProof, isDeviceFrame, sameProof } from "@extension-use/protocol/remote";
25
+ function wsUrl(relay) {
26
+ return `${relay.replace(/^http/, "ws").replace(/\/+$/, "")}/v1/device`;
27
+ }
28
+ function createRemoteLink(opts) {
29
+ const WS = opts.WebSocket ?? globalThis.WebSocket;
30
+ const backoff = opts.backoff ?? [1e3, 2e3, 5e3, 1e4, 3e4];
31
+ const log = opts.log ?? (() => {
32
+ });
33
+ const sessions = /* @__PURE__ */ new Map();
34
+ let ws;
35
+ let ping;
36
+ let retry;
37
+ let attempt = 0;
38
+ let stopped = true;
39
+ let state = { status: "disconnected", relay: opts.relay, sessions: [] };
40
+ const setState = (patch) => {
41
+ state = { ...state, ...patch, sessions: [...sessions.entries()].map(([id, s]) => ({ id, origin: s.origin, ...s.label ? { label: s.label } : {} })) };
42
+ opts.onState?.(state);
43
+ };
44
+ const send = (frame) => {
45
+ if (ws?.readyState === 1) ws.send(JSON.stringify(frame));
46
+ };
47
+ function closeSessions() {
48
+ for (const s of sessions.values()) s.conn.close();
49
+ sessions.clear();
50
+ }
51
+ function onFrame(frame) {
52
+ switch (frame.t) {
53
+ case "ready":
54
+ attempt = 0;
55
+ setState({ status: "connected", deviceId: frame.deviceId, name: frame.name, error: void 0 });
56
+ log("relay connected", frame.deviceId);
57
+ break;
58
+ case "open": {
59
+ const conn = opts.router.connect({
60
+ transport: opts.transport ?? "remote",
61
+ origin: frame.origin,
62
+ grants: opts.grants,
63
+ send: (env) => send({ t: "msg", s: frame.s, env })
64
+ });
65
+ sessions.set(frame.s, { conn, origin: frame.origin, ...frame.label ? { label: frame.label } : {} });
66
+ setState({});
67
+ break;
68
+ }
69
+ case "msg":
70
+ sessions.get(frame.s)?.conn.receive(frame.env);
71
+ break;
72
+ case "close": {
73
+ const s = sessions.get(frame.s);
74
+ sessions.delete(frame.s);
75
+ s?.conn.close();
76
+ setState({});
77
+ break;
78
+ }
79
+ case "error":
80
+ log("relay error", frame.code, frame.message);
81
+ if (frame.code === "UNAUTHORIZED") {
82
+ stopped = true;
83
+ setState({ status: "unauthorized", error: frame.message });
84
+ } else setState({ error: frame.message });
85
+ break;
86
+ case "pong":
87
+ break;
88
+ }
89
+ }
90
+ function open() {
91
+ if (stopped || ws && ws.readyState <= 1) return;
92
+ clearTimeout(retry);
93
+ setState({ status: "connecting" });
94
+ let socket;
95
+ try {
96
+ socket = new WS(opts.url ?? wsUrl(opts.relay));
97
+ } catch (e) {
98
+ setState({ status: "disconnected", error: String(e) });
99
+ schedule();
100
+ return;
101
+ }
102
+ ws = socket;
103
+ const key = opts.agentKey;
104
+ let trusted = !key;
105
+ let ourNonce;
106
+ socket.addEventListener("open", () => {
107
+ if (key) {
108
+ ourNonce = agentNonce();
109
+ socket.send(JSON.stringify({ t: "agent-hello", nonce: ourNonce }));
110
+ } else {
111
+ socket.send(JSON.stringify({ t: "auth", token: opts.deviceToken ?? "", client: { name: "extension" } }));
112
+ }
113
+ clearInterval(ping);
114
+ ping = setInterval(() => send({ t: "ping" }), REMOTE_PING_MS);
115
+ });
116
+ const verify = async (frame) => {
117
+ if (frame.t !== "agent-challenge" || !key || !ourNonce || typeof frame.nonce !== "string" || frame.nonce.length < 16) return socket.close();
118
+ const ok = frame.keyId === await agentKeyId(key) && sameProof(frame.proof, await agentProof(key, "mcp", ourNonce, frame.nonce));
119
+ if (!ok) {
120
+ setState({ error: "An agent on this computer uses a different key" });
121
+ return socket.close();
122
+ }
123
+ trusted = true;
124
+ if (socket.readyState === 1) socket.send(JSON.stringify({ t: "agent-proof", proof: await agentProof(key, "extension", frame.nonce, ourNonce) }));
125
+ };
126
+ let pending = Promise.resolve();
127
+ socket.addEventListener("message", (e) => {
128
+ let frame;
129
+ try {
130
+ frame = JSON.parse(String(e.data));
131
+ } catch {
132
+ return;
133
+ }
134
+ if (!isDeviceFrame(frame)) return;
135
+ const f = frame;
136
+ pending = pending.then(() => {
137
+ if (ws !== socket) return;
138
+ if (trusted) return onFrame(f);
139
+ if (f.t === "agent-challenge") return verify(f);
140
+ socket.close();
141
+ }).catch(() => socket.close());
142
+ });
143
+ socket.addEventListener("close", () => {
144
+ if (ws !== socket) return;
145
+ clearInterval(ping);
146
+ ws = void 0;
147
+ closeSessions();
148
+ if (state.status !== "unauthorized") {
149
+ setState({ status: "disconnected" });
150
+ schedule();
151
+ }
152
+ });
153
+ socket.addEventListener("error", () => {
154
+ });
155
+ }
156
+ function schedule() {
157
+ if (stopped) return;
158
+ const delay = backoff[Math.min(attempt, backoff.length - 1)];
159
+ attempt++;
160
+ retry = setTimeout(open, delay);
161
+ }
162
+ return {
163
+ start() {
164
+ stopped = false;
165
+ open();
166
+ },
167
+ /** Reconnect now (for example when an alarm wakes the service worker). */
168
+ poke() {
169
+ if (stopped) return;
170
+ attempt = 0;
171
+ if (!ws) open();
172
+ },
173
+ stop() {
174
+ stopped = true;
175
+ clearTimeout(retry);
176
+ clearInterval(ping);
177
+ const s = ws;
178
+ ws = void 0;
179
+ s?.close();
180
+ closeSessions();
181
+ setState({ status: "disconnected" });
182
+ },
183
+ get state() {
184
+ return state;
185
+ }
186
+ };
187
+ }
188
+
189
+ // src/background/remote.ts
190
+ var STORAGE_KEY = "extensionUse.remote";
191
+ var ALARM = "extension-use-remote";
192
+ var DEFAULT_RELAYS = ["http://127.0.0.1:*", "http://localhost:*", "https://*"];
193
+ function setupRemote(router, config, onChange, log) {
194
+ const grants = config.grants === void 0 || config.grants === "all" ? ["*"] : config.grants;
195
+ const relays = config.relays ?? DEFAULT_RELAYS;
196
+ const defaultRelay = config.defaultRelay ?? "http://127.0.0.1:7777";
197
+ let link;
198
+ let saved;
199
+ let pairing;
200
+ let poll;
201
+ function startLink(s) {
202
+ link?.stop();
203
+ link = createRemoteLink({ relay: s.relay, deviceToken: s.deviceToken, router, grants, onState: onChange, log });
204
+ link.start();
205
+ }
206
+ const ready = chrome.storage.local.get(STORAGE_KEY).then((r) => {
207
+ saved = r[STORAGE_KEY];
208
+ if (saved) startLink(saved);
209
+ onChange();
210
+ });
211
+ chrome.alarms?.create(ALARM, { periodInMinutes: 1 });
212
+ chrome.alarms?.onAlarm.addListener((alarm) => {
213
+ if (alarm.name === ALARM) void ready.then(() => link?.poke());
214
+ });
215
+ function normalize(relay) {
216
+ const url = new URL(relay);
217
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("Use an http(s) relay URL");
218
+ const base = url.origin;
219
+ if (!matchAny(relays, `${base}/`) && !matchAny(relays, base)) throw new Error(`This extension doesn't allow the relay ${base}`);
220
+ return base;
221
+ }
222
+ async function pair(relayInput, name) {
223
+ stopPolling();
224
+ const relay = normalize(relayInput);
225
+ const res = await fetch(`${relay}/v1/pairings`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: name || "Browser" }) });
226
+ if (!res.ok) throw new Error(`The relay answered ${res.status}`);
227
+ const start = await res.json();
228
+ pairing = { relay, ...start, status: "pending" };
229
+ onChange();
230
+ poll = setInterval(() => void checkPairing(), 1500);
231
+ }
232
+ async function checkPairing() {
233
+ if (!pairing || pairing.status !== "pending") return stopPolling();
234
+ try {
235
+ const res = await fetch(`${pairing.relay}/v1/pairings/${pairing.pairingId}`);
236
+ const status = await res.json();
237
+ if (status.status === "approved") {
238
+ saved = { relay: pairing.relay, deviceToken: status.deviceToken, deviceId: status.deviceId, name: status.name };
239
+ await chrome.storage.local.set({ [STORAGE_KEY]: saved });
240
+ pairing = void 0;
241
+ stopPolling();
242
+ startLink(saved);
243
+ } else if (status.status !== "pending") {
244
+ pairing = { ...pairing, status: status.status };
245
+ stopPolling();
246
+ } else if (Date.now() > pairing.expiresAt) {
247
+ pairing = { ...pairing, status: "expired" };
248
+ stopPolling();
249
+ }
250
+ } catch (e) {
251
+ if (pairing) pairing = { ...pairing, status: "error", error: String(e.message ?? e) };
252
+ stopPolling();
253
+ }
254
+ onChange();
255
+ }
256
+ function stopPolling() {
257
+ clearInterval(poll);
258
+ poll = void 0;
259
+ }
260
+ return {
261
+ ready,
262
+ pair,
263
+ cancelPairing() {
264
+ stopPolling();
265
+ pairing = void 0;
266
+ onChange();
267
+ },
268
+ async unpair() {
269
+ link?.stop();
270
+ link = void 0;
271
+ saved = void 0;
272
+ await chrome.storage.local.remove(STORAGE_KEY);
273
+ onChange();
274
+ },
275
+ reconnect() {
276
+ link?.poke();
277
+ },
278
+ state() {
279
+ return {
280
+ paired: Boolean(saved),
281
+ ...link ? { link: link.state } : {},
282
+ ...pairing ? { pairing } : {},
283
+ defaultRelay
284
+ };
285
+ }
286
+ };
287
+ }
288
+
289
+ // src/background/agent.ts
290
+ import { AGENT_PATH, AGENT_PORTS, isAgentKey, newAgentKey } from "@extension-use/protocol/remote";
291
+ var STORAGE_KEY2 = "extensionUse.agent";
292
+ var ALARM2 = "extension-use-agent";
293
+ function agentInstructions(key, opts = {}) {
294
+ const name = opts.serverName ?? "browser";
295
+ const config = JSON.stringify(
296
+ { mcpServers: { [name]: { command: "npx", args: ["-y", "@extension-use/mcp"], env: { EXTENSION_USE_AGENT_KEY: key } } } },
297
+ null,
298
+ 2
299
+ );
300
+ return `Connect to my browser${opts.hostName ? ` through the "${opts.hostName}" extension` : ""}. Add this MCP server to your MCP configuration, then use its tools to read and act in my browser:
301
+
302
+ ${config}
303
+
304
+ For Claude Code, run:
305
+ claude mcp add ${name} -e EXTENSION_USE_AGENT_KEY=${key} -- npx -y @extension-use/mcp
306
+
307
+ The server listens on 127.0.0.1 only, and my browser connects to it by itself within about 30 seconds. If the tools say the browser isn't connected yet, wait a little and try again.
308
+ Start with tabs_list or dom_snapshot. It's my real browser, signed in as me: don't close tabs or submit forms I didn't ask for. If a tool says control is paused, stop and ask me.`;
309
+ }
310
+ function setupAgent(router, config, hostName, onChange, log) {
311
+ const grants = config.grants === void 0 || config.grants === "all" ? ["*"] : config.grants;
312
+ const ports = config.ports ?? AGENT_PORTS;
313
+ let key;
314
+ let links = [];
315
+ function stopLinks() {
316
+ for (const l of links) l.stop();
317
+ links = [];
318
+ }
319
+ function startLinks(k) {
320
+ stopLinks();
321
+ links = ports.map((port) => {
322
+ const link = createRemoteLink({
323
+ relay: `http://127.0.0.1:${port}`,
324
+ url: `ws://127.0.0.1:${port}${AGENT_PATH}`,
325
+ agentKey: k,
326
+ transport: "agent",
327
+ router,
328
+ grants,
329
+ // Nobody may be listening yet: keep checking, gently.
330
+ backoff: [2e3, 5e3, 15e3, 3e4],
331
+ onState: onChange,
332
+ log
333
+ });
334
+ link.start();
335
+ return link;
336
+ });
337
+ }
338
+ const ready = chrome.storage.local.get(STORAGE_KEY2).then((r) => {
339
+ const saved = r[STORAGE_KEY2];
340
+ if (saved?.key && isAgentKey(saved.key)) {
341
+ key = saved.key;
342
+ startLinks(key);
343
+ }
344
+ onChange();
345
+ });
346
+ chrome.alarms?.create(ALARM2, { periodInMinutes: 0.5 });
347
+ chrome.alarms?.onAlarm.addListener((alarm) => {
348
+ if (alarm.name === ALARM2) void ready.then(() => links.forEach((l) => l.poke()));
349
+ });
350
+ async function setKey(k) {
351
+ await ready;
352
+ key = k;
353
+ if (k) {
354
+ await chrome.storage.local.set({ [STORAGE_KEY2]: { key: k } });
355
+ startLinks(k);
356
+ } else {
357
+ await chrome.storage.local.remove(STORAGE_KEY2);
358
+ stopLinks();
359
+ }
360
+ onChange();
361
+ }
362
+ return {
363
+ ready,
364
+ /** Turn on with a new key. Agents holding an older key are disconnected. */
365
+ enable: () => setKey(newAgentKey()),
366
+ disable: () => setKey(void 0),
367
+ state() {
368
+ const agents = router.sessions().filter((s) => s.transport === "agent").map((s) => s.origin.replace(/^agent:/, ""));
369
+ return {
370
+ enabled: Boolean(key),
371
+ ...key ? { key, instructions: agentInstructions(key, { ...hostName ? { hostName } : {}, ...config.serverName ? { serverName: config.serverName } : {} }) } : {},
372
+ agents
373
+ };
374
+ }
375
+ };
376
+ }
377
+
378
+ // src/background/router.ts
379
+ import {
380
+ ExtensionUseError,
381
+ PROTOCOL_VERSION,
382
+ envelope,
383
+ isEnvelope,
384
+ matchAny as matchAny2,
385
+ randomId
386
+ } from "@extension-use/protocol";
387
+ var SDK_VERSION = "0.1.0";
388
+ var ALWAYS_BLOCKED = [
389
+ "chrome://*",
390
+ "chrome-untrusted://*",
391
+ "edge://*",
392
+ "about:*",
393
+ "chrome-extension://*",
394
+ "moz-extension://*",
395
+ "https://chromewebstore.google.com/*",
396
+ "https://chrome.google.com/webstore*",
397
+ "https://microsoftedge.microsoft.com/addons*"
398
+ ];
399
+ function createRouter(opts) {
400
+ const actions = /* @__PURE__ */ new Map();
401
+ for (const def of opts.actions) {
402
+ if (actions.has(def.name)) throw new Error(`Duplicate action "${def.name}"`);
403
+ if (def.schema.where === "background" && !def.handler) throw new Error(`Background action "${def.name}" has no handler`);
404
+ actions.set(def.name, def);
405
+ }
406
+ const policy = {
407
+ blockedSites: [...ALWAYS_BLOCKED, ...opts.policy?.blockedSites ?? []],
408
+ sensitiveFields: opts.policy?.sensitiveFields ?? "refuse"
409
+ };
410
+ const sessions = /* @__PURE__ */ new Map();
411
+ const auditLog = [];
412
+ const auditSize = opts.auditSize ?? 500;
413
+ let paused = false;
414
+ const hostInfo = {
415
+ id: opts.host.id,
416
+ sdkVersion: SDK_VERSION,
417
+ protocol: PROTOCOL_VERSION,
418
+ ...opts.host.name ? { name: opts.host.name } : {},
419
+ ...opts.host.version ? { version: opts.host.version } : {}
420
+ };
421
+ const capabilities = [...actions.values()].map((d) => ({
422
+ action: d.name,
423
+ version: d.schema.version,
424
+ where: d.schema.where
425
+ }));
426
+ const log = (...args) => {
427
+ if (opts.debug) console.debug("[extension-use]", ...args);
428
+ };
429
+ function assertAllowedUrl(url) {
430
+ if (matchAny2(policy.blockedSites, url)) {
431
+ throw new ExtensionUseError("BLOCKED_BY_POLICY", `Controllers may not act on ${url}`);
432
+ }
433
+ }
434
+ function audit(entry) {
435
+ auditLog.push(entry);
436
+ if (auditLog.length > auditSize) auditLog.shift();
437
+ opts.onAudit?.(entry);
438
+ }
439
+ function emit(name, payload, tabId) {
440
+ const env = envelope({ kind: "event", name, payload, ts: Date.now(), ...tabId !== void 0 ? { tabId } : {} });
441
+ for (const s of sessions.values()) {
442
+ if (matchAny2([...s.subscriptions], name)) s.channel.send(env);
443
+ }
444
+ }
445
+ async function execute(state, call) {
446
+ const started = Date.now();
447
+ const def = actions.get(call.action);
448
+ let tabId;
449
+ const abort = new AbortController();
450
+ const onParentAbort = () => abort.abort(call.parentSignal?.reason);
451
+ if (call.depth === 0) state.pending.set(call.id, abort);
452
+ call.parentSignal?.addEventListener("abort", onParentAbort, { once: true });
453
+ try {
454
+ if (paused) throw new ExtensionUseError("BLOCKED_BY_POLICY", "Control is paused by the person using this browser");
455
+ if (!def) throw new ExtensionUseError("UNKNOWN_ACTION", `Unknown action "${call.action}"`);
456
+ if (!matchAny2(state.info.granted, call.action)) {
457
+ throw new ExtensionUseError("NOT_GRANTED", `This controller may not call "${call.action}"`);
458
+ }
459
+ if (call.depth > 0 && def.schema.nestable === false) {
460
+ throw new ExtensionUseError("INVALID_INPUT", `"${call.action}" can't be used inside another action`);
461
+ }
462
+ const parsed = def.schema.input.safeParse(call.input ?? {});
463
+ if (!parsed.success) {
464
+ throw new ExtensionUseError("INVALID_INPUT", parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; "), {
465
+ issues: parsed.error.issues
466
+ });
467
+ }
468
+ const timeoutMs = call.timeoutMs ?? def.schema.timeoutMs ?? opts.defaultTimeoutMs ?? 1e4;
469
+ const frameTarget = call.target?.frame;
470
+ const frameFor = async (tab) => {
471
+ if (typeof frameTarget === "number") return frameTarget;
472
+ if (frameTarget && typeof frameTarget === "object") {
473
+ if (!opts.env.resolveFrame) throw new ExtensionUseError("TARGET_NOT_FOUND", "This host can't look up frames by URL");
474
+ return opts.env.resolveFrame(tab, frameTarget);
475
+ }
476
+ return 0;
477
+ };
478
+ let tabPromise;
479
+ const resolveTab2 = () => {
480
+ tabPromise ??= opts.env.resolveTab(call.target, state.info).then((t) => {
481
+ assertAllowedUrl(t.url);
482
+ tabId = t.tabId;
483
+ return t;
484
+ });
485
+ return tabPromise;
486
+ };
487
+ const sendContent = async (action, input, callId) => {
488
+ const tab = await resolveTab2();
489
+ const frameId = await frameFor(tab);
490
+ const onAbort = () => opts.env.cancelContent?.(tab, frameId, callId);
491
+ abort.signal.addEventListener("abort", onAbort, { once: true });
492
+ try {
493
+ return await opts.env.sendToContent(tab, frameId, {
494
+ callId,
495
+ action,
496
+ input,
497
+ timeoutMs: Math.max(0, timeoutMs - (Date.now() - started) - 50),
498
+ policy: { sensitiveFields: policy.sensitiveFields },
499
+ ...call.target ? { target: call.target } : {},
500
+ controller: { transport: state.info.transport, origin: state.info.origin }
501
+ });
502
+ } finally {
503
+ abort.signal.removeEventListener("abort", onAbort);
504
+ }
505
+ };
506
+ const ctx = {
507
+ session: state.info,
508
+ host: opts.host,
509
+ target: call.target,
510
+ signal: abort.signal,
511
+ timeoutMs,
512
+ tab: resolveTab2,
513
+ callContent: async (action, input) => {
514
+ const inner = actions.get(action);
515
+ if (!inner || inner.schema.where !== "content") throw new ExtensionUseError("UNKNOWN_ACTION", `No content action "${action}"`);
516
+ const p = inner.schema.input.parse(input ?? {});
517
+ return await sendContent(action, p, randomId());
518
+ },
519
+ call: (action, input, options = {}) => execute(state, {
520
+ id: randomId(),
521
+ action,
522
+ input,
523
+ depth: call.depth + 1,
524
+ parentSignal: abort.signal,
525
+ ...options.target ?? call.target ? { target: options.target ?? call.target } : {},
526
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
527
+ }),
528
+ listActions: () => [...actions.values()].filter((d) => matchAny2(state.info.granted, d.name)),
529
+ assertAllowedUrl,
530
+ emit
531
+ };
532
+ const work = def.schema.where === "content" ? sendContent(def.name, parsed.data, call.id) : Promise.resolve().then(() => def.handler(parsed.data, ctx));
533
+ const output = await withTimeout(work, timeoutMs, abort) ?? {};
534
+ audit({ ts: started, session: state.info.id, transport: state.info.transport, origin: state.info.origin, action: call.action, ...tabId !== void 0 ? { tabId } : {}, ok: true, ms: Date.now() - started });
535
+ return output;
536
+ } catch (err) {
537
+ const e = ExtensionUseError.from(err);
538
+ log("call failed", call.action, e.code, e.message);
539
+ audit({ ts: started, session: state.info.id, transport: state.info.transport, origin: state.info.origin, action: call.action, ...tabId !== void 0 ? { tabId } : {}, ok: false, code: e.code, ms: Date.now() - started });
540
+ throw e;
541
+ } finally {
542
+ call.parentSignal?.removeEventListener("abort", onParentAbort);
543
+ if (call.depth === 0) state.pending.delete(call.id);
544
+ }
545
+ }
546
+ async function runCall(state, call) {
547
+ try {
548
+ const output = await execute(state, {
549
+ id: call.id,
550
+ action: call.action,
551
+ input: call.input,
552
+ depth: 0,
553
+ ...call.target ? { target: call.target } : {},
554
+ ...call.timeoutMs !== void 0 ? { timeoutMs: call.timeoutMs } : {}
555
+ });
556
+ state.channel.send(envelope({ kind: "result", id: call.id, ok: true, output }));
557
+ } catch (err) {
558
+ state.channel.send(envelope({ kind: "result", id: call.id, ok: false, error: ExtensionUseError.from(err).toPayload() }));
559
+ }
560
+ }
561
+ function connect(channel) {
562
+ let state;
563
+ const conn = {
564
+ get session() {
565
+ return state?.info;
566
+ },
567
+ receive(message) {
568
+ if (!isEnvelope(message)) {
569
+ log("dropped non-envelope message", message);
570
+ return;
571
+ }
572
+ const msg = message;
573
+ if (msg.kind === "hello") {
574
+ if (!msg.client?.protocols?.includes(PROTOCOL_VERSION)) {
575
+ channel.send(envelope({ kind: "bye", reason: `UNSUPPORTED_VERSION: host speaks protocol ${PROTOCOL_VERSION}` }));
576
+ return;
577
+ }
578
+ if (state) closeSession(state);
579
+ const granted = channel.grants.length ? channel.grants : [];
580
+ state = {
581
+ info: {
582
+ id: randomId(),
583
+ transport: channel.transport,
584
+ origin: channel.origin,
585
+ granted,
586
+ ...channel.windowId !== void 0 ? { windowId: channel.windowId } : {}
587
+ },
588
+ channel,
589
+ subscriptions: /* @__PURE__ */ new Set(),
590
+ pending: /* @__PURE__ */ new Map()
591
+ };
592
+ sessions.set(state.info.id, state);
593
+ opts.onSessionsChange?.([...sessions.values()].map((s) => s.info));
594
+ log("session opened", state.info);
595
+ channel.send(
596
+ envelope({
597
+ kind: "welcome",
598
+ session: state.info.id,
599
+ host: hostInfo,
600
+ capabilities: capabilities.filter((c) => matchAny2(granted, c.action)),
601
+ granted
602
+ })
603
+ );
604
+ return;
605
+ }
606
+ if (!state) {
607
+ if (msg.kind === "call") {
608
+ channel.send(envelope({ kind: "result", id: msg.id, ok: false, error: { code: "NOT_CONNECTED", message: "Send hello first" } }));
609
+ }
610
+ return;
611
+ }
612
+ switch (msg.kind) {
613
+ case "call":
614
+ void runCall(state, msg);
615
+ break;
616
+ case "cancel":
617
+ state.pending.get(msg.id)?.abort(new ExtensionUseError("CANCELLED", "Cancelled by controller"));
618
+ break;
619
+ case "subscribe":
620
+ for (const e of msg.events) state.subscriptions.add(e);
621
+ break;
622
+ case "unsubscribe":
623
+ for (const e of msg.events) state.subscriptions.delete(e);
624
+ break;
625
+ case "bye":
626
+ closeSession(state);
627
+ state = void 0;
628
+ break;
629
+ default:
630
+ log("ignored envelope", msg.kind);
631
+ }
632
+ },
633
+ close() {
634
+ if (state) closeSession(state);
635
+ state = void 0;
636
+ }
637
+ };
638
+ return conn;
639
+ }
640
+ function closeSession(state) {
641
+ for (const a of state.pending.values()) a.abort(new ExtensionUseError("CANCELLED", "Session closed"));
642
+ sessions.delete(state.info.id);
643
+ opts.onSessionsChange?.([...sessions.values()].map((s) => s.info));
644
+ log("session closed", state.info.id);
645
+ }
646
+ return {
647
+ connect,
648
+ emit,
649
+ capabilities: () => capabilities,
650
+ sessions: () => [...sessions.values()].map((s) => s.info),
651
+ audit: () => [...auditLog],
652
+ /** Kill switch: reject every call until resumed. */
653
+ pause() {
654
+ paused = true;
655
+ for (const s of sessions.values()) for (const a of s.pending.values()) a.abort(new ExtensionUseError("BLOCKED_BY_POLICY", "Control was paused"));
656
+ },
657
+ resume() {
658
+ paused = false;
659
+ },
660
+ get paused() {
661
+ return paused;
662
+ },
663
+ assertAllowedUrl
664
+ };
665
+ }
666
+ function withTimeout(work, ms, abort) {
667
+ return new Promise((resolve, reject) => {
668
+ const timer = setTimeout(() => {
669
+ const e = new ExtensionUseError("TIMEOUT", `Timed out after ${ms} ms`);
670
+ abort.abort(e);
671
+ reject(e);
672
+ }, ms);
673
+ abort.signal.addEventListener(
674
+ "abort",
675
+ () => {
676
+ clearTimeout(timer);
677
+ reject(abort.signal.reason ?? new ExtensionUseError("CANCELLED", "Cancelled"));
678
+ },
679
+ { once: true }
680
+ );
681
+ work.then(
682
+ (v) => {
683
+ clearTimeout(timer);
684
+ resolve(v);
685
+ },
686
+ (e) => {
687
+ clearTimeout(timer);
688
+ reject(e);
689
+ }
690
+ );
691
+ });
692
+ }
693
+
694
+ // src/background/index.ts
695
+ import { ExtensionUseError as ExtensionUseError3 } from "@extension-use/protocol";
696
+
697
+ // src/registry.ts
698
+ function defineAction(name, schema, handler) {
699
+ if (schema.where === "background" && !handler) {
700
+ throw new Error(`Background action "${name}" needs a handler`);
701
+ }
702
+ return handler ? { name, schema, handler } : { name, schema };
703
+ }
704
+
705
+ // src/background/index.ts
706
+ function defineHost(options) {
707
+ const groups = options.groups ?? allBuiltinGroups;
708
+ configureTabCapture(options.offscreen);
709
+ const actions = [...groups.flatMap((g) => g.actions), ...options.actions ?? []];
710
+ const router = createRouter({
711
+ host: {
712
+ id: options.id,
713
+ ...options.name ? { name: options.name } : {},
714
+ version: options.version ?? chrome.runtime.getManifest().version
715
+ },
716
+ actions,
717
+ ...options.policy ? { policy: options.policy } : {},
718
+ ...options.defaultTimeoutMs ? { defaultTimeoutMs: options.defaultTimeoutMs } : {},
719
+ ...options.debug ? { debug: options.debug } : {},
720
+ onSessionsChange: () => refresh(),
721
+ onAudit: (entry) => {
722
+ options.onAudit?.(entry);
723
+ refresh();
724
+ },
725
+ env: {
726
+ resolveTab,
727
+ async sendToContent(tab, frameId, req) {
728
+ const message = { [CONTENT_MESSAGE]: req };
729
+ const NO_RECEIVER = /* @__PURE__ */ Symbol();
730
+ const send = () => chrome.tabs.sendMessage(tab.tabId, message, { frameId }).catch((err) => {
731
+ if (isNoReceiver(err)) return NO_RECEIVER;
732
+ throw toContentError(err);
733
+ });
734
+ let response = await send();
735
+ if (response === NO_RECEIVER && (await chrome.tabs.get(tab.tabId).catch(() => void 0))?.discarded) {
736
+ await chrome.tabs.reload(tab.tabId);
737
+ await waitForLoad(tab.tabId, AbortSignal.timeout(3e4));
738
+ response = await send();
739
+ }
740
+ if (response === NO_RECEIVER && options.contentScript) {
741
+ await chrome.scripting.executeScript({ target: { tabId: tab.tabId, frameIds: [frameId] }, files: [options.contentScript] });
742
+ response = await send();
743
+ }
744
+ if (response === NO_RECEIVER) throw toContentError(new Error("Receiving end does not exist"));
745
+ const r = response;
746
+ if (!r) throw new ExtensionUseError2("INTERNAL", "The content runtime did not answer");
747
+ if (!r.ok) throw ExtensionUseError2.from(r.error);
748
+ return r.output;
749
+ },
750
+ cancelContent(tab, frameId, callId) {
751
+ chrome.tabs.sendMessage(tab.tabId, { [CONTENT_CANCEL]: callId }, { frameId }).catch(() => {
752
+ });
753
+ },
754
+ async resolveFrame(tab, frame) {
755
+ if (!chrome.webNavigation?.getAllFrames) {
756
+ throw new ExtensionUseError2("NEEDS_PERMISSION", 'Finding frames by URL needs the "webNavigation" permission (the frames group)');
757
+ }
758
+ const frames = await chrome.webNavigation.getAllFrames({ tabId: tab.tabId }) ?? [];
759
+ const match = frames.find((f) => matchPattern(frame.urlMatch, f.url));
760
+ if (!match) throw new ExtensionUseError2("TARGET_NOT_FOUND", `No frame in the tab matches ${frame.urlMatch}`);
761
+ ctxAssertFrame(match.url);
762
+ return match.frameId;
763
+ }
764
+ }
765
+ });
766
+ const grantsOf = (c) => c.grants === void 0 || c.grants === "all" ? ["*"] : c.grants;
767
+ chrome.runtime.onConnect.addListener((port) => {
768
+ if (port.name !== FRAME_PORT) return;
769
+ const cfg = options.controllers.frame;
770
+ const sender = port.sender;
771
+ if (!cfg || sender?.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(""))) {
772
+ port.disconnect();
773
+ return;
774
+ }
775
+ let conn;
776
+ port.onMessage.addListener((msg) => {
777
+ if (!conn) {
778
+ const hello = msg;
779
+ if (hello?.type !== "bridge-hello" || typeof hello.origin !== "string" || !matchAny3(cfg.origins, hello.origin)) {
780
+ port.disconnect();
781
+ return;
782
+ }
783
+ conn = router.connect({
784
+ transport: "frame",
785
+ origin: hello.origin,
786
+ grants: grantsOf(cfg),
787
+ ...typeof hello.windowId === "number" ? { windowId: hello.windowId } : {},
788
+ send: (env) => safePost(port, env)
789
+ });
790
+ return;
791
+ }
792
+ conn.receive(msg);
793
+ });
794
+ port.onDisconnect.addListener(() => conn?.close());
795
+ });
796
+ chrome.runtime.onConnectExternal.addListener((port) => {
797
+ const cfg = options.controllers.page;
798
+ const origin = port.sender?.origin ?? (port.sender?.url ? new URL(port.sender.url).origin : "");
799
+ if (!cfg || !origin || !matchAny3(cfg.origins, origin)) {
800
+ port.disconnect();
801
+ return;
802
+ }
803
+ const windowId = port.sender?.tab?.windowId;
804
+ const conn = router.connect({
805
+ transport: "page",
806
+ origin,
807
+ grants: grantsOf(cfg),
808
+ ...windowId !== void 0 ? { windowId } : {},
809
+ send: (env) => safePost(port, env)
810
+ });
811
+ port.onMessage.addListener((msg) => conn.receive(msg));
812
+ port.onDisconnect.addListener(() => conn.close());
813
+ });
814
+ chrome.runtime.onMessage.addListener((msg, sender) => {
815
+ const ev = msg?.[CONTENT_EVENT];
816
+ if (ev && sender.id === chrome.runtime.id && typeof ev.name === "string") {
817
+ router.emit(ev.name, ev.payload, sender.tab?.id);
818
+ }
819
+ return false;
820
+ });
821
+ chrome.tabs.onUpdated.addListener((_id, changes, tab) => {
822
+ if (!("status" in changes || "url" in changes || "title" in changes)) return;
823
+ router.emit(
824
+ "tab.updated",
825
+ {
826
+ tab: { id: tab.id ?? -1, windowId: tab.windowId, url: tab.url ?? "", title: tab.title ?? "", active: tab.active, status: tab.status ?? "unknown" },
827
+ changes
828
+ },
829
+ tab.id
830
+ );
831
+ });
832
+ chrome.tabs.onActivated.addListener(({ tabId, windowId }) => router.emit("tab.activated", { tabId, windowId }, tabId));
833
+ chrome.tabs.onRemoved.addListener((tabId) => router.emit("tab.removed", { tabId }, tabId));
834
+ const log = (...a) => options.debug && console.debug("[extension-use]", ...a);
835
+ const remote = options.controllers.remote ? setupRemote(router, options.controllers.remote, () => refresh(), log) : void 0;
836
+ const agent = options.controllers.agent ? setupAgent(router, options.controllers.agent, options.name, () => refresh(), log) : void 0;
837
+ const uiPorts = /* @__PURE__ */ new Set();
838
+ let refreshQueued = false;
839
+ const PAUSED_KEY = "extensionUse.paused";
840
+ chrome.storage?.local.get(PAUSED_KEY).then((r) => {
841
+ if (r[PAUSED_KEY]) router.pause();
842
+ refresh();
843
+ }, () => {
844
+ });
845
+ const setPaused = (paused) => {
846
+ if (paused) router.pause();
847
+ else router.resume();
848
+ chrome.storage?.local.set({ [PAUSED_KEY]: paused }).catch(() => {
849
+ });
850
+ refresh();
851
+ };
852
+ function uiState() {
853
+ return {
854
+ host: { id: options.id, ...options.name ? { name: options.name } : {}, version: options.version ?? chrome.runtime.getManifest().version },
855
+ paused: router.paused,
856
+ sessions: router.sessions().map((s) => ({ id: s.id, transport: s.transport, origin: s.origin })),
857
+ audit: router.audit().slice(-30).reverse(),
858
+ ...remote ? { remote: remote.state() } : {},
859
+ ...agent ? { agent: agent.state() } : {}
860
+ };
861
+ }
862
+ function refresh() {
863
+ if (refreshQueued) return;
864
+ refreshQueued = true;
865
+ queueMicrotask(() => {
866
+ refreshQueued = false;
867
+ const state = uiState();
868
+ for (const p of uiPorts) safePost(p, state);
869
+ updateBadge(state);
870
+ });
871
+ }
872
+ function updateBadge(state) {
873
+ if (options.badge === false || !chrome.action?.setBadgeText) return;
874
+ const external = state.sessions.filter((s) => s.transport === "remote" || s.transport === "agent" || s.transport === "page");
875
+ const [text, color, title] = state.paused ? ["II", "#6b7280", "Control paused"] : external.length ? ["ON", "#dc2626", `Controlled by ${[...new Set(external.map((s) => s.origin))].join(", ")}`] : ["", "#6b7280", ""];
876
+ chrome.action.setBadgeText({ text }).catch(() => {
877
+ });
878
+ chrome.action.setBadgeBackgroundColor({ color }).catch(() => {
879
+ });
880
+ if (title) chrome.action.setTitle({ title: `${options.name ?? options.id}: ${title}` }).catch(() => {
881
+ });
882
+ }
883
+ const pendingUi = /* @__PURE__ */ new Map();
884
+ let uiConn;
885
+ function uiCall(action, input, target) {
886
+ if (!uiConn) {
887
+ uiConn = router.connect({
888
+ transport: "ui",
889
+ origin: "control-panel",
890
+ grants: ["*"],
891
+ send: (env) => {
892
+ if (env.kind === "result") {
893
+ pendingUi.get(env.id)?.(env);
894
+ pendingUi.delete(env.id);
895
+ }
896
+ }
897
+ });
898
+ uiConn.receive(envelope2({ kind: "hello", client: { name: "control-panel", protocols: [1] } }));
899
+ }
900
+ const id = newId();
901
+ return new Promise((resolve) => {
902
+ pendingUi.set(id, resolve);
903
+ uiConn.receive(envelope2({ kind: "call", id, action, input, ...target ? { target } : {} }));
904
+ });
905
+ }
906
+ chrome.runtime.onConnect.addListener((port) => {
907
+ if (port.name !== UI_PORT) return;
908
+ if (port.sender?.id !== chrome.runtime.id || !port.sender.url?.startsWith(chrome.runtime.getURL(""))) {
909
+ port.disconnect();
910
+ return;
911
+ }
912
+ uiPorts.add(port);
913
+ port.onDisconnect.addListener(() => uiPorts.delete(port));
914
+ port.onMessage.addListener(async (msg) => {
915
+ try {
916
+ switch (msg?.cmd) {
917
+ case "pause":
918
+ setPaused(true);
919
+ break;
920
+ case "resume":
921
+ setPaused(false);
922
+ break;
923
+ case "pair":
924
+ if (!remote) throw new Error("Remote control is not enabled in this extension");
925
+ await remote.pair(msg.relay, msg.name);
926
+ break;
927
+ case "cancel-pairing":
928
+ remote?.cancelPairing();
929
+ break;
930
+ case "unpair":
931
+ await remote?.unpair();
932
+ break;
933
+ case "reconnect":
934
+ remote?.reconnect();
935
+ break;
936
+ case "agent-enable":
937
+ if (!agent) throw new Error("Agents are not enabled in this extension");
938
+ await agent.enable();
939
+ break;
940
+ case "agent-disable":
941
+ await agent?.disable();
942
+ break;
943
+ case "describe": {
944
+ const r = await uiCall("runtime.describe", {});
945
+ const actions2 = r.ok ? r.output.actions : [];
946
+ safePost(port, { kind: "describe", actions: actions2.map(({ name, description, where, input }) => ({ name, description, where, input })) });
947
+ return;
948
+ }
949
+ case "call": {
950
+ const started = Date.now();
951
+ const r = await uiCall(msg.action, msg.input, msg.target);
952
+ safePost(port, r.ok ? { kind: "call-result", id: msg.id, ok: true, output: r.output, ms: Date.now() - started } : { kind: "call-result", id: msg.id, ok: false, error: r.error, ms: Date.now() - started });
953
+ return;
954
+ }
955
+ }
956
+ safePost(port, uiState());
957
+ } catch (e) {
958
+ safePost(port, { ...uiState(), error: String(e?.message ?? e) });
959
+ }
960
+ });
961
+ safePost(port, uiState());
962
+ });
963
+ chrome.commands?.onCommand.addListener((command) => {
964
+ if (command === "extension-use-toggle-pause") setPaused(!router.paused);
965
+ });
966
+ return router;
967
+ }
968
+ function ctxAssertFrame(url) {
969
+ if (matchAny3(ALWAYS_BLOCKED_FRAMES, url)) throw new ExtensionUseError2("BLOCKED_BY_POLICY", `Controllers may not act on ${url}`);
970
+ }
971
+ var ALWAYS_BLOCKED_FRAMES = ["chrome://*", "chrome-extension://*", "https://chromewebstore.google.com/*"];
972
+ async function resolveTab(target, session) {
973
+ const t = target?.tab ?? "active";
974
+ let tab;
975
+ if (typeof t === "number") {
976
+ tab = await chrome.tabs.get(t).catch(() => void 0);
977
+ } else if (t === "active") {
978
+ const q = { active: true };
979
+ if (session.windowId !== void 0) q.windowId = session.windowId;
980
+ else q.lastFocusedWindow = true;
981
+ [tab] = await chrome.tabs.query(q);
982
+ } else if (typeof t === "object" && typeof t.urlMatch === "string") {
983
+ const all = await chrome.tabs.query({});
984
+ const matches = all.filter((x) => matchPattern(t.urlMatch, x.url ?? ""));
985
+ matches.sort((a, b) => Number(b.active) - Number(a.active) || (b.lastAccessed ?? 0) - (a.lastAccessed ?? 0));
986
+ tab = matches[0];
987
+ }
988
+ if (!tab || tab.id === void 0) throw new ExtensionUseError2("TARGET_NOT_FOUND", `No tab matches ${JSON.stringify(t)}`);
989
+ return { tabId: tab.id, windowId: tab.windowId, url: tab.url ?? tab.pendingUrl ?? "" };
990
+ }
991
+ function isNoReceiver(err) {
992
+ return /Receiving end does not exist|Could not establish connection/i.test(String(err?.message ?? err));
993
+ }
994
+ function toContentError(err) {
995
+ if (isNoReceiver(err)) {
996
+ return new ExtensionUseError2("TARGET_NOT_FOUND", "The page has no Extension-use content runtime (reload the tab, or set `contentScript` in defineHost)");
997
+ }
998
+ if (/No tab with id/i.test(String(err?.message ?? err))) return new ExtensionUseError2("TAB_CLOSED", "The tab was closed");
999
+ return ExtensionUseError2.from(err);
1000
+ }
1001
+ function safePost(port, message) {
1002
+ try {
1003
+ port.postMessage(message);
1004
+ } catch {
1005
+ }
1006
+ }
1007
+ export {
1008
+ ALWAYS_BLOCKED,
1009
+ ExtensionUseError3 as ExtensionUseError,
1010
+ OPT_IN_GROUPS,
1011
+ SDK_VERSION,
1012
+ agentInstructions,
1013
+ allBuiltinGroups,
1014
+ builtinGroups,
1015
+ createRemoteLink,
1016
+ createRouter,
1017
+ defineAction,
1018
+ defineHost
1019
+ };