@nexum-hub/browser 0.0.0-stage → 0.0.1

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 (100) hide show
  1. package/README.md +22 -2
  2. package/browser-extension/assets.js +654 -0
  3. package/browser-extension/build.mjs +111 -0
  4. package/browser-extension/clipboard.js +397 -0
  5. package/browser-extension/connection.js +880 -0
  6. package/browser-extension/dist/development/assets.js +654 -0
  7. package/browser-extension/dist/development/clipboard.js +397 -0
  8. package/browser-extension/dist/development/connection.js +880 -0
  9. package/browser-extension/dist/development/errors.js +106 -0
  10. package/browser-extension/dist/development/evaluate.js +160 -0
  11. package/browser-extension/dist/development/frames.js +256 -0
  12. package/browser-extension/dist/development/keyboard.js +167 -0
  13. package/browser-extension/dist/development/manifest.json +35 -0
  14. package/browser-extension/dist/development/native-node.js +85 -0
  15. package/browser-extension/dist/development/page-data.js +497 -0
  16. package/browser-extension/dist/development/page.js +772 -0
  17. package/browser-extension/dist/development/profile.js +2 -0
  18. package/browser-extension/dist/development/router.js +5961 -0
  19. package/browser-extension/dist/development/site-source.js +149 -0
  20. package/browser-extension/dist/development/transport.js +405 -0
  21. package/browser-extension/dist/development/visual.js +976 -0
  22. package/browser-extension/dist/development/worker.js +24 -0
  23. package/browser-extension/dist/production/assets.js +654 -0
  24. package/browser-extension/dist/production/clipboard.js +397 -0
  25. package/browser-extension/dist/production/connection.js +880 -0
  26. package/browser-extension/dist/production/errors.js +106 -0
  27. package/browser-extension/dist/production/evaluate.js +160 -0
  28. package/browser-extension/dist/production/frames.js +256 -0
  29. package/browser-extension/dist/production/keyboard.js +167 -0
  30. package/browser-extension/dist/production/manifest.json +35 -0
  31. package/browser-extension/dist/production/native-node.js +85 -0
  32. package/browser-extension/dist/production/page-data.js +497 -0
  33. package/browser-extension/dist/production/page.js +772 -0
  34. package/browser-extension/dist/production/profile.js +2 -0
  35. package/browser-extension/dist/production/router.js +5961 -0
  36. package/browser-extension/dist/production/site-source.js +149 -0
  37. package/browser-extension/dist/production/transport.js +405 -0
  38. package/browser-extension/dist/production/visual.js +976 -0
  39. package/browser-extension/dist/production/worker.js +24 -0
  40. package/browser-extension/errors.js +106 -0
  41. package/browser-extension/evaluate.js +160 -0
  42. package/browser-extension/frames.js +256 -0
  43. package/browser-extension/keyboard.js +167 -0
  44. package/browser-extension/native-node.js +85 -0
  45. package/browser-extension/page-data.js +497 -0
  46. package/browser-extension/page.js +772 -0
  47. package/browser-extension/release-info.json +21 -0
  48. package/browser-extension/route-manifest.json +807 -0
  49. package/browser-extension/router.js +5961 -0
  50. package/browser-extension/site-source.js +149 -0
  51. package/browser-extension/transport.js +405 -0
  52. package/browser-extension/visual.js +976 -0
  53. package/browser-extension/worker.js +24 -0
  54. package/dist/client/index.d.ts +6 -0
  55. package/dist/client/index.js +894 -0
  56. package/dist/client/index.js.map +1 -0
  57. package/dist/client/routes.d.ts +6 -0
  58. package/dist/client/routes.js +777 -0
  59. package/dist/client/routes.js.map +1 -0
  60. package/dist/client/serialize.d.ts +16 -0
  61. package/dist/client/serialize.js +355 -0
  62. package/dist/client/serialize.js.map +1 -0
  63. package/dist/client/types.d.ts +1342 -0
  64. package/dist/client/types.js +2 -0
  65. package/dist/client/types.js.map +1 -0
  66. package/dist/extension/artifacts.d.ts +60 -0
  67. package/dist/extension/artifacts.js +493 -0
  68. package/dist/extension/artifacts.js.map +1 -0
  69. package/dist/extension/assets.d.ts +10 -0
  70. package/dist/extension/assets.js +90 -0
  71. package/dist/extension/assets.js.map +1 -0
  72. package/dist/extension/batch.d.ts +6 -0
  73. package/dist/extension/batch.js +138 -0
  74. package/dist/extension/batch.js.map +1 -0
  75. package/dist/extension/files.d.ts +16 -0
  76. package/dist/extension/files.js +594 -0
  77. package/dist/extension/files.js.map +1 -0
  78. package/dist/extension/index.d.ts +3 -0
  79. package/dist/extension/index.js +623 -0
  80. package/dist/extension/index.js.map +1 -0
  81. package/dist/extension/protocol.d.ts +81 -0
  82. package/dist/extension/protocol.js +475 -0
  83. package/dist/extension/protocol.js.map +1 -0
  84. package/dist/extension/scope.d.ts +55 -0
  85. package/dist/extension/scope.js +563 -0
  86. package/dist/extension/scope.js.map +1 -0
  87. package/dist/extension/service.d.ts +113 -0
  88. package/dist/extension/service.js +905 -0
  89. package/dist/extension/service.js.map +1 -0
  90. package/docs/README.md +10 -0
  91. package/docs/api.md +1375 -0
  92. package/docs/connection.md +9 -0
  93. package/docs/lifecycle.md +17 -0
  94. package/docs/usage.md +75 -0
  95. package/implementation.json +2352 -0
  96. package/instructions/README.md +8 -0
  97. package/package.json +80 -4
  98. package/scripts/discover.js +12 -0
  99. package/scripts/screenshot.js +9 -0
  100. package/skills/browser-control/SKILL.md +12 -0
@@ -0,0 +1,623 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { Marked } from "marked";
3
+ import TurndownService from "turndown";
4
+ import { browserRoutes } from "../client/routes.js";
5
+ import { normalizeBrowserValue, validateLocatorDescription, validateTarget, } from "../client/serialize.js";
6
+ import { BrowserService, } from "./service.js";
7
+ import { BrowserRuntime } from "./scope.js";
8
+ import { collectTabContent } from "./batch.js";
9
+ import { preparePlugin } from "./assets.js";
10
+ import { materializeDownload, prepareFiles } from "./files.js";
11
+ import { materializeArtifact, materializeAssetDownloads, materializeAssetBundle, } from "./artifacts.js";
12
+ import { check, data, failure, identifier, record, permissionDenied, } from "./protocol.js";
13
+ class BrowserInstallation {
14
+ closed;
15
+ #done = Promise.withResolvers();
16
+ #stop = new AbortController();
17
+ #flow;
18
+ #disposal;
19
+ #stopping = false;
20
+ service;
21
+ runtime;
22
+ build;
23
+ routes = [];
24
+ constructor() {
25
+ this.closed = this.#done.promise;
26
+ void this.closed.catch(() => { });
27
+ }
28
+ start(host, signal) {
29
+ check(!this.#stopping, "EXTENSION_OFFLINE", "The browser installation is stopping.");
30
+ if (this.#flow)
31
+ return this.#flow;
32
+ const combined = AbortSignal.any([signal, this.#stop.signal]);
33
+ const task = (async () => {
34
+ this.build = await preparePlugin(host, combined);
35
+ combined.throwIfAborted();
36
+ const paths = host.context.paths;
37
+ check(record(paths) && typeof paths.work === "string", "INVALID_ARGUMENT", "The Agent work directory is missing.");
38
+ const manifest = JSON.parse(await readFile(new URL("../../browser-extension/route-manifest.json", import.meta.url), "utf8"));
39
+ check(Array.isArray(manifest) &&
40
+ manifest.length <= 512 &&
41
+ manifest.every((value) => record(value) &&
42
+ identifier(value.method) &&
43
+ typeof value.needsTab === "boolean" &&
44
+ typeof value.mutating === "boolean"), "PROTOCOL_MISMATCH", "The plugin method manifest is invalid.");
45
+ this.routes = manifest;
46
+ combined.throwIfAborted();
47
+ host.authorize({
48
+ type: "connection",
49
+ value: `127.0.0.1:${this.build.port}`,
50
+ access: "listen",
51
+ });
52
+ this.service = new BrowserService({
53
+ ...this.build,
54
+ work: paths.work,
55
+ ...(typeof host.config.defaultBrowserId === "string"
56
+ ? { defaultBrowserId: host.config.defaultBrowserId }
57
+ : {}),
58
+ });
59
+ this.service.on("diagnostic", (entry) => {
60
+ try {
61
+ host.log({
62
+ level: entry.event === "closed" &&
63
+ [1000, 1001].includes(entry.closeCode ?? 0)
64
+ ? "debug"
65
+ : "warn",
66
+ message: "browser.connection",
67
+ data: { ...entry },
68
+ });
69
+ }
70
+ catch {
71
+ // A diagnostic write cannot prevent actual channel/resource cleanup.
72
+ }
73
+ });
74
+ this.service.on("visual-diagnostic", (entry) => {
75
+ try {
76
+ host.log({
77
+ level: "warn",
78
+ message: "browser.visual_degraded",
79
+ data: { ...entry },
80
+ });
81
+ }
82
+ catch {
83
+ // A diagnostic write cannot prevent actual channel/resource cleanup.
84
+ }
85
+ });
86
+ this.runtime = new BrowserRuntime(this.service);
87
+ await this.service.start(combined);
88
+ combined.throwIfAborted();
89
+ })();
90
+ this.#flow = task;
91
+ void task.catch(() => { });
92
+ return task;
93
+ }
94
+ dispose() {
95
+ if (this.#disposal)
96
+ return this.#disposal;
97
+ this.#stopping = true;
98
+ this.#stop.abort(failure("EXTENSION_OFFLINE", "The browser extension is stopping."));
99
+ const task = (async () => {
100
+ await this.#flow?.catch(() => { });
101
+ await this.runtime?.dispose();
102
+ await this.service?.dispose();
103
+ if (this.service)
104
+ await this.service.closed;
105
+ this.#done.resolve();
106
+ })();
107
+ this.#disposal = task;
108
+ void task.catch(() => {
109
+ if (this.#disposal === task)
110
+ this.#disposal = undefined;
111
+ });
112
+ return task;
113
+ }
114
+ }
115
+ const methodAliases = {
116
+ "tab.devLogs": "dev.logs",
117
+ "tab.dialogAccept": "dialogs.accept",
118
+ "tab.dialogDismiss": "dialogs.dismiss",
119
+ };
120
+ const markdown = new Marked({ gfm: true });
121
+ const artifactMethods = new Set([
122
+ "content.export",
123
+ "content.exportGsuite",
124
+ "content.exportYouTubeTranscript",
125
+ "tab.exportFile",
126
+ "cua.downloadMedia",
127
+ "dom.downloadMedia",
128
+ "locator.downloadMedia",
129
+ ]);
130
+ const networkArtifacts = new Set([
131
+ "pageAssets.download",
132
+ "pageAssets.bundle",
133
+ ...artifactMethods,
134
+ ]);
135
+ function authorizeUrl(call, value) {
136
+ check(typeof value === "string", "PROTOCOL_MISMATCH", "The browser did not return an exact source URL.");
137
+ const url = new URL(value);
138
+ check(["http:", "https:"].includes(url.protocol) &&
139
+ !url.username &&
140
+ !url.password, "INVALID_ARGUMENT", "Remote browser files require an HTTP(S) source without embedded credentials.");
141
+ call.authorize({ type: "url", value: url.href, access: "read" });
142
+ }
143
+ const fileInputs = new Set(["tab.setFiles", "fileChoosers.setFiles"]);
144
+ const localRoutes = new Set([
145
+ "browsers.list",
146
+ "browsers.get",
147
+ "browsers.getDefault",
148
+ "browsers.getForUrl",
149
+ "documentation.get",
150
+ "browsers.documentation",
151
+ "tabs.list",
152
+ "user.openTabs",
153
+ "user.claimTab",
154
+ ]);
155
+ function selected(service, id, call) {
156
+ check(identifier(id), "INVALID_TARGET", "Select a currently connected browser identity.");
157
+ call.authorize({ type: "connection", value: id, access: "read" });
158
+ return service.get(id);
159
+ }
160
+ function targetOf(input) {
161
+ const value = input.target ?? (record(input.locator) ? input.locator.target : undefined);
162
+ validateTarget(value);
163
+ return value;
164
+ }
165
+ function safeInfo(value) {
166
+ return value === null ? undefined : value;
167
+ }
168
+ function noteResult(service, target, value, method) {
169
+ let peer;
170
+ try {
171
+ peer = service.target({ ...target, tabId: undefined });
172
+ }
173
+ catch (cause) {
174
+ if (cause.code === "EXTENSION_OFFLINE")
175
+ return;
176
+ throw cause;
177
+ }
178
+ if (method === "tab.close" && target.tabId) {
179
+ peer.tabs.delete(target.tabId);
180
+ return;
181
+ }
182
+ if (!["tabs.get", "tabs.new", "tabs.selected", "user.claimTab"].includes(method))
183
+ return;
184
+ if (record(value) &&
185
+ record(value.target) &&
186
+ identifier(value.id) &&
187
+ value.target.browserId === peer.id &&
188
+ value.target.bootId === service.bootId &&
189
+ value.target.generation === peer.generation &&
190
+ value.target.browserSessionId === peer.browserSessionId) {
191
+ peer.tabs.set(value.id, data({
192
+ id: value.id,
193
+ title: value.title ?? "",
194
+ url: value.url ?? "",
195
+ pageVersion: value.target.pageVersion ?? 1,
196
+ active: false,
197
+ }, 16384));
198
+ }
199
+ }
200
+ async function local(pathName, input, call, service, runtime) {
201
+ if (pathName === "browsers.list") {
202
+ const allowed = [];
203
+ for (const info of service.list()) {
204
+ try {
205
+ call.authorize({ type: "connection", value: info.id, access: "read" });
206
+ allowed.push(info);
207
+ }
208
+ catch (cause) {
209
+ if (!permissionDenied(cause))
210
+ throw cause;
211
+ }
212
+ }
213
+ return allowed;
214
+ }
215
+ if (pathName === "browsers.get")
216
+ return selected(service, input.id, call).info;
217
+ if (pathName === "browsers.getDefault" || pathName === "browsers.getForUrl") {
218
+ const peers = (await local("browsers.list", {}, call, service, runtime));
219
+ check(peers.length, "EXTENSION_OFFLINE", "No approved browser extension is currently online.");
220
+ let chosen = peers.find((peer) => peer.id === service.options.defaultBrowserId)?.id ??
221
+ peers[0].id;
222
+ if (pathName === "browsers.getForUrl") {
223
+ check(typeof input.url === "string", "INVALID_ARGUMENT", "A URL is required.");
224
+ const url = new URL(input.url);
225
+ check(["http:", "https:"].includes(url.protocol), "INVALID_ARGUMENT", "Browser URL selection supports HTTP(S).");
226
+ url.username = "";
227
+ url.password = "";
228
+ url.search = "";
229
+ url.hash = "";
230
+ const candidates = peers.map((info) => service.get(info.id));
231
+ const exact = candidates.find((peer) => [...peer.tabs.values()].some((tab) => tab.url === url.href)), origin = candidates.find((peer) => [...peer.tabs.values()].some((tab) => {
232
+ try {
233
+ return new URL(String(tab.url)).origin === url.origin;
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ }));
239
+ chosen = (exact ?? origin)?.id ?? chosen;
240
+ }
241
+ return service.get(chosen).info;
242
+ }
243
+ if (pathName === "documentation.get" ||
244
+ pathName === "browsers.documentation") {
245
+ if (input.target)
246
+ service.target(targetOf(input));
247
+ const topic = pathName === "browsers.documentation" ? "README" : String(input.name);
248
+ check(["README", "usage", "connection", "lifecycle", "api"].includes(topic), "TOPIC_NOT_FOUND", "This package has no manual chapter with that name.");
249
+ return readFile(new URL(`../../docs/${topic}.md`, import.meta.url), "utf8");
250
+ }
251
+ const target = targetOf(input), peer = selected(service, target.browserId, call);
252
+ service.target({ ...target, tabId: undefined });
253
+ if (pathName === "tabs.list" || pathName === "user.openTabs") {
254
+ await service.waitSnapshot(peer, "tabs", call.signal, call.deadline - Date.now());
255
+ return [...peer.tabs.values()].map((tab) => ({
256
+ id: tab.id,
257
+ providerTabId: tab.id,
258
+ ...(typeof tab.title === "string" ? { title: tab.title } : {}),
259
+ ...(typeof tab.url === "string" ? { url: tab.url } : {}),
260
+ }));
261
+ }
262
+ if (pathName === "user.claimTab") {
263
+ const tab = typeof input.tab === "string"
264
+ ? input.tab
265
+ : record(input.tab)
266
+ ? input.tab.id
267
+ : undefined;
268
+ check(identifier(tab), "INVALID_TARGET", "Choose a currently observed tab.");
269
+ await service.waitSnapshot(peer, "tabs", call.signal, call.deadline - Date.now());
270
+ const selectedTarget = { ...target, tabId: tab };
271
+ const value = await runtime.action("tabs.get", { target: selectedTarget, id: tab }, selectedTarget, call, false);
272
+ noteResult(service, selectedTarget, value, "tabs.get");
273
+ return value;
274
+ }
275
+ throw failure("CAPABILITY_NOT_ALLOWED", "This package build has not implemented this local browser route.");
276
+ }
277
+ const createExtension = async (host) => {
278
+ check(Object.keys(host.config).every((key) => key === "defaultBrowserId") &&
279
+ (host.config.defaultBrowserId === undefined ||
280
+ identifier(host.config.defaultBrowserId)), "INVALID_ARGUMENT", "The browser extension config contains unsupported fields.");
281
+ const installation = new BrowserInstallation(), ref = await host.resources.register({
282
+ kind: "browser-service",
283
+ value: installation,
284
+ });
285
+ const abort = () => {
286
+ void installation.dispose().catch(() => { });
287
+ };
288
+ ref.signal.addEventListener("abort", abort, { once: true });
289
+ try {
290
+ ref.signal.throwIfAborted();
291
+ await installation.start(host, ref.signal);
292
+ ref.signal.throwIfAborted();
293
+ const service = installation.service, runtime = installation.runtime, remote = new Map(installation.routes.map((route) => [route.method, route]));
294
+ const methods = {};
295
+ for (const route of browserRoutes) {
296
+ const implemented = remote.get(route.path === "ax.write"
297
+ ? "ax.get"
298
+ : route.path === "tabs.content" &&
299
+ remote.has("tabs.createTemporary") &&
300
+ remote.has("tabs.closeTemporary")
301
+ ? "tabs.createTemporary"
302
+ : route.path === "tab.saveDownload"
303
+ ? "downloads.path"
304
+ : route.path === "tab.requestUserTakeover" &&
305
+ remote.has("tab.resumeUserControl")
306
+ ? "tab.markHandoff"
307
+ : (methodAliases[route.path] ?? route.path));
308
+ if (!implemented && !localRoutes.has(route.path))
309
+ continue;
310
+ const pathName = route.path;
311
+ methods[pathName] = {
312
+ description: `Nexum browser: ${pathName}`,
313
+ path: pathName.split("."),
314
+ permissions: pathName === "documentation.get"
315
+ ? []
316
+ : [
317
+ "connection",
318
+ ...(pathName === "downloads.path" ||
319
+ pathName === "tab.saveDownload" ||
320
+ fileInputs.has(pathName) ||
321
+ networkArtifacts.has(pathName)
322
+ ? ["path"]
323
+ : []),
324
+ ...(networkArtifacts.has(pathName) ||
325
+ pathName === "tabs.content"
326
+ ? ["url"]
327
+ : []),
328
+ ],
329
+ schemaDialect: "draft7",
330
+ inputSchema: route.inputSchema,
331
+ normalize(args) {
332
+ check(args.length === 1 && record(args[0]), "INVALID_ARGUMENT", "Browser data methods accept one explicit named input object.");
333
+ return normalizeBrowserValue(args[0]);
334
+ },
335
+ async handle(input, call) {
336
+ call.signal.throwIfAborted();
337
+ if (localRoutes.has(pathName))
338
+ return local(pathName, input, call, service, runtime);
339
+ const waiter = pathName === "waiters.get" || pathName === "waiters.cancel"
340
+ ? runtime.waiter(input.id, call)
341
+ : undefined;
342
+ const target = waiter?.target ?? targetOf(input);
343
+ if (input.locator)
344
+ validateLocatorDescription(input.locator);
345
+ if (pathName === "user.getTabContext") {
346
+ const id = typeof input.tab === "string"
347
+ ? input.tab
348
+ : record(input.tab)
349
+ ? input.tab.id
350
+ : undefined;
351
+ check(id === undefined || identifier(id), "INVALID_TARGET", "Choose an actual browser tab.");
352
+ const lookupTarget = id === undefined ? target : { ...target, tabId: id };
353
+ const observed = await runtime.action(id === undefined ? "tabs.selected" : "tabs.get", { target: lookupTarget, ...(id === undefined ? {} : { id }) }, lookupTarget, call, false);
354
+ check(record(observed) && record(observed.target), "INVALID_TARGET", "The browser has no current selected tab.");
355
+ const effective = validateTarget(observed.target, true);
356
+ check(effective.browserId === target.browserId &&
357
+ effective.bootId === target.bootId &&
358
+ effective.browserSessionId === target.browserSessionId &&
359
+ effective.generation === target.generation &&
360
+ (id === undefined || effective.tabId === id), "PROTOCOL_MISMATCH", "The observed context target does not belong to this browser request.");
361
+ noteResult(service, effective, observed, "tabs.get");
362
+ // Reserve the exact tab under the actual run before reading any document data.
363
+ return runtime.action(pathName, { target: effective, tab: effective.tabId }, effective, call, false);
364
+ }
365
+ if (pathName === "tabs.content")
366
+ return collectTabContent(input, target, call, runtime, (target, value, method) => noteResult(service, target, value, method));
367
+ const paths = host.context.paths;
368
+ check(record(paths) && typeof paths.work === "string", "INVALID_ARGUMENT", "The Agent work directory is missing.");
369
+ if (pathName === "tab.requestUserTakeover") {
370
+ await runtime.action("tab.markHandoff", { target }, target, call, true);
371
+ const reply = await call.requestInput({
372
+ message: input.reason === "authentication"
373
+ ? "请在浏览器中完成认证,然后明确确认是否继续。"
374
+ : input.reason === "captcha"
375
+ ? "请在浏览器中完成验证,然后明确确认是否继续。"
376
+ : "浏览器目标已交还给你;完成操作后,请明确确认是否继续。",
377
+ inputSchema: {
378
+ type: "object",
379
+ properties: { confirmed: { type: "boolean" } },
380
+ required: ["confirmed"],
381
+ additionalProperties: false,
382
+ },
383
+ timeoutMs: Math.max(1, Math.floor(call.deadline - Date.now())),
384
+ });
385
+ check(record(reply.input) && reply.input.confirmed === true, "USER_TAKEOVER", "The user did not confirm renewed browser control.");
386
+ await runtime.resume(target, call);
387
+ return undefined;
388
+ }
389
+ let prepared = waiter
390
+ ? {
391
+ ...input,
392
+ target,
393
+ ...(pathName === "waiters.get"
394
+ ? { timeoutMs: Math.max(1, waiter.expiresAt - Date.now()) }
395
+ : {}),
396
+ }
397
+ : input;
398
+ if (fileInputs.has(pathName)) {
399
+ service.target(target);
400
+ call.authorize({
401
+ type: "connection",
402
+ value: target.browserId,
403
+ access: "control",
404
+ });
405
+ prepared = {
406
+ ...prepared,
407
+ files: await prepareFiles(input.files, call, paths.work),
408
+ };
409
+ }
410
+ if (pathName === "tab.saveDownload")
411
+ prepared = { target, downloadId: input.id };
412
+ if (pathName === "tab.dialogAccept" ||
413
+ pathName === "tab.dialogDismiss") {
414
+ const dialog = await runtime.action("tab.getJsDialog", { target }, target, call, false);
415
+ check(record(dialog) &&
416
+ typeof dialog.dialogId === "string" &&
417
+ Number.isSafeInteger(dialog.pageVersion), "STALE_REF", "There is no current native dialog to control.");
418
+ prepared = {
419
+ target,
420
+ dialogId: dialog.dialogId,
421
+ pageVersion: dialog.pageVersion,
422
+ ...(input.text === undefined ? {} : { text: input.text }),
423
+ };
424
+ }
425
+ if ((pathName === "dev.logs" || pathName === "tab.devLogs") &&
426
+ record(input.options) &&
427
+ Array.isArray(input.options.levels))
428
+ prepared = {
429
+ ...prepared,
430
+ options: {
431
+ ...input.options,
432
+ levels: input.options.levels.map((level) => level === "warning" ? "warn" : level),
433
+ },
434
+ };
435
+ if (pathName === "ax.paste" &&
436
+ record(input.options) &&
437
+ input.options.format === "md") {
438
+ check(typeof input.text === "string", "INVALID_ARGUMENT", "Markdown paste requires text.");
439
+ const html = markdown.parse(input.text, { async: false });
440
+ check(typeof html === "string" &&
441
+ Buffer.byteLength(html) <= 128 * 1024 * 1024, "OUTPUT_TOO_LARGE", "Rendered Markdown exceeds the local byte budget.");
442
+ call.signal.throwIfAborted();
443
+ check(Date.now() < call.deadline, "TIMEOUT", "Markdown rendering exceeded the method deadline.");
444
+ prepared = { ...prepared, html };
445
+ }
446
+ if (pathName === "pageAssets.download") {
447
+ check(Array.isArray(input.urls), "INVALID_ARGUMENT", "Asset downloads require source URLs.");
448
+ for (const url of input.urls)
449
+ authorizeUrl(call, url);
450
+ }
451
+ if (pathName === "pageAssets.bundle") {
452
+ const plan = await runtime.action("pageAssets.plan", input, target, call, false);
453
+ check(record(plan) &&
454
+ record(input.options) &&
455
+ plan.inventoryId === input.options.inventoryId &&
456
+ Array.isArray(plan.assets) &&
457
+ plan.assets.length <= 10000, "STALE_REF", "The asset plan does not match the original inventory.");
458
+ check(record(plan.target) &&
459
+ [
460
+ "bootId",
461
+ "browserId",
462
+ "browserSessionId",
463
+ "generation",
464
+ "tabId",
465
+ "controlEpoch",
466
+ ].every((key) => plan.target[key] ===
467
+ target[key]), "STALE_REF", "The asset plan belongs to another target identity.");
468
+ authorizeUrl(call, plan.pageUrl);
469
+ for (const asset of plan.assets) {
470
+ check(record(asset) && typeof asset.url === "string", "PROTOCOL_MISMATCH", "The browser asset plan is invalid.");
471
+ const uri = new URL(asset.url);
472
+ if (uri.protocol === "blob:" || uri.protocol === "data:") {
473
+ check(asset.embedded === true &&
474
+ (uri.protocol !== "blob:" ||
475
+ uri.origin === new URL(String(plan.pageUrl)).origin), "PROTOCOL_MISMATCH", "An embedded asset is not owned by this document inventory.");
476
+ call.authorize({
477
+ type: "url",
478
+ value: asset.url,
479
+ access: "read",
480
+ });
481
+ }
482
+ else
483
+ authorizeUrl(call, asset.url);
484
+ }
485
+ prepared = {
486
+ ...prepared,
487
+ options: {
488
+ ...input.options,
489
+ assetIds: plan.assets.map((asset) => asset.id),
490
+ },
491
+ };
492
+ }
493
+ if (artifactMethods.has(pathName)) {
494
+ const page = await runtime.action("tab.url", { target }, target, call, false);
495
+ authorizeUrl(call, page);
496
+ if (remote.has("content.plan")) {
497
+ const plan = await runtime.action("content.plan", { target, method: pathName, ...input }, target, call, false);
498
+ check(record(plan) &&
499
+ Array.isArray(plan.urls) &&
500
+ plan.urls.length <= 128, "PROTOCOL_MISMATCH", "The browser content plan is invalid.");
501
+ for (const url of plan.urls)
502
+ authorizeUrl(call, url);
503
+ prepared = { ...prepared, planId: plan.id };
504
+ }
505
+ }
506
+ const remoteMethod = pathName === "ax.write"
507
+ ? "ax.get"
508
+ : pathName === "tab.saveDownload"
509
+ ? "downloads.path"
510
+ : (methodAliases[pathName] ?? pathName);
511
+ const value = await runtime.action(remoteMethod, prepared, target, call, implemented.mutating);
512
+ noteResult(service, target, value, pathName);
513
+ if ((pathName === "dev.logs" || pathName === "tab.devLogs") &&
514
+ record(input.options) &&
515
+ typeof input.options.since === "number") {
516
+ check(Array.isArray(value), "PROTOCOL_MISMATCH", "Native logs must be a bounded list.");
517
+ const since = input.options.since;
518
+ return value.filter((item) => record(item) &&
519
+ typeof item.timestamp === "string" &&
520
+ Date.parse(item.timestamp) >= since);
521
+ }
522
+ if (artifactMethods.has(pathName)) {
523
+ if (pathName === "tab.exportFile" &&
524
+ record(input.options) &&
525
+ input.options.format === "markdown" &&
526
+ record(value) &&
527
+ value.mimeType === "text/html") {
528
+ check(typeof value.text === "string", "PROTOCOL_MISMATCH", "Markdown conversion requires the actual serialized document HTML.");
529
+ const converter = new TurndownService({
530
+ headingStyle: "atx",
531
+ codeBlockStyle: "fenced",
532
+ });
533
+ converter.remove(["script", "style", "noscript"]);
534
+ const converted = converter.turndown(value.text);
535
+ call.signal.throwIfAborted();
536
+ check(Date.now() < call.deadline, "TIMEOUT", "Markdown conversion exceeded the method deadline.");
537
+ return materializeArtifact({
538
+ text: converted,
539
+ name: typeof value.name === "string"
540
+ ? value.name.replace(/\.html?$/i, "") + ".md"
541
+ : "page.md",
542
+ mimeType: "text/markdown",
543
+ ...(typeof value.sourceUrl === "string"
544
+ ? { sourceUrl: value.sourceUrl }
545
+ : {}),
546
+ }, call, paths.work);
547
+ }
548
+ return materializeArtifact(value, call, paths.work);
549
+ }
550
+ if (pathName === "pageAssets.download")
551
+ return materializeAssetDownloads(value, call, paths.work);
552
+ if (pathName === "pageAssets.bundle")
553
+ return materializeAssetBundle(value, call, paths.work);
554
+ if (pathName === "downloads.path" ||
555
+ pathName === "tab.saveDownload") {
556
+ if (value === null && pathName === "downloads.path")
557
+ return null;
558
+ check(record(value) &&
559
+ typeof value.path === "string" &&
560
+ (value.expectedSize === undefined ||
561
+ (Number.isSafeInteger(value.expectedSize) &&
562
+ value.expectedSize >= 0)), "PROTOCOL_MISMATCH", "A completed download did not return its actual browser-local file and size.");
563
+ const artifact = await materializeDownload({
564
+ path: value.path,
565
+ ...(value.expectedSize === undefined
566
+ ? {}
567
+ : { expectedSize: value.expectedSize }),
568
+ ...(typeof input.path === "string"
569
+ ? { destination: input.path }
570
+ : {}),
571
+ }, call, paths.work);
572
+ return pathName === "downloads.path" ? artifact.path : artifact;
573
+ }
574
+ if (pathName === "ax.write") {
575
+ const mode = input.mode ?? "state";
576
+ if (mode === "state") {
577
+ check(typeof value === "string", "PROTOCOL_MISMATCH", "The accessibility state is not text.");
578
+ return call.output.text(value);
579
+ }
580
+ if (mode === "screenshot") {
581
+ check(value instanceof Uint8Array, "PROTOCOL_MISMATCH", "The accessibility screenshot is not bytes.");
582
+ return call.output.image({ data: value, mimeType: "image/jpeg" });
583
+ }
584
+ check(record(value) &&
585
+ typeof value.state === "string" &&
586
+ value.screenshot instanceof Uint8Array, "PROTOCOL_MISMATCH", "The accessibility result is missing its real state or screenshot.");
587
+ return call.output.result({
588
+ content: [
589
+ call.output.text(value.state),
590
+ call.output.image({
591
+ data: value.screenshot,
592
+ mimeType: "image/jpeg",
593
+ }),
594
+ ],
595
+ });
596
+ }
597
+ return [
598
+ "tabs.selected",
599
+ "tab.getJsDialog",
600
+ "tab.title",
601
+ "tab.url",
602
+ ].includes(pathName)
603
+ ? safeInfo(value)
604
+ : value;
605
+ },
606
+ };
607
+ }
608
+ ref.report({
609
+ state: "listening",
610
+ profile: installation.build.profile,
611
+ port: installation.build.port,
612
+ pluginDirectory: installation.build.directory,
613
+ methodCount: Object.keys(methods).length,
614
+ });
615
+ return { methods, dispose: () => installation.dispose() };
616
+ }
617
+ catch (cause) {
618
+ await installation.dispose();
619
+ throw cause;
620
+ }
621
+ };
622
+ export default createExtension;
623
+ //# sourceMappingURL=index.js.map