@jackwener/browsermcp 0.0.0-stage → 0.0.32
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.
- package/CHANGELOG.md +317 -0
- package/LICENSE +202 -0
- package/README.md +177 -2
- package/adapter-sdk/index.d.ts +94 -0
- package/adapter-sdk/index.js +30 -0
- package/adapters/bilibili/_shared.js +254 -0
- package/adapters/bilibili/comment.js +55 -0
- package/adapters/bilibili/comments.js +47 -0
- package/adapters/bilibili/download.js +73 -0
- package/adapters/bilibili/dynamic.js +29 -0
- package/adapters/bilibili/favorite.js +39 -0
- package/adapters/bilibili/feed-detail.js +66 -0
- package/adapters/bilibili/feed.js +95 -0
- package/adapters/bilibili/follow.js +36 -0
- package/adapters/bilibili/following.js +29 -0
- package/adapters/bilibili/history.js +27 -0
- package/adapters/bilibili/hot.js +25 -0
- package/adapters/bilibili/me.js +24 -0
- package/adapters/bilibili/popular.js +26 -0
- package/adapters/bilibili/ranking.js +24 -0
- package/adapters/bilibili/search.js +37 -0
- package/adapters/bilibili/site.json +3 -0
- package/adapters/bilibili/subtitle.js +49 -0
- package/adapters/bilibili/summary.js +59 -0
- package/adapters/bilibili/unfollow.js +35 -0
- package/adapters/bilibili/user-videos.js +32 -0
- package/adapters/bilibili/video.js +70 -0
- package/adapters/discord/_shared.js +112 -0
- package/adapters/discord/channels.js +22 -0
- package/adapters/discord/delete.js +22 -0
- package/adapters/discord/goto.js +23 -0
- package/adapters/discord/members.js +28 -0
- package/adapters/discord/read.js +24 -0
- package/adapters/discord/search.js +28 -0
- package/adapters/discord/send.js +22 -0
- package/adapters/discord/servers.js +14 -0
- package/adapters/discord/site.json +1 -0
- package/adapters/discord/status.js +13 -0
- package/adapters/discord/thread-read.js +25 -0
- package/adapters/discord/threads.js +42 -0
- package/adapters/facebook/_friending.js +64 -0
- package/adapters/facebook/_graphql.js +51 -0
- package/adapters/facebook/_marketplace.js +31 -0
- package/adapters/facebook/_shared.js +148 -0
- package/adapters/facebook/add-friend.js +14 -0
- package/adapters/facebook/cancel-friend-request.js +14 -0
- package/adapters/facebook/events.js +77 -0
- package/adapters/facebook/feed.js +146 -0
- package/adapters/facebook/friends.js +72 -0
- package/adapters/facebook/groups.js +69 -0
- package/adapters/facebook/join-group.js +68 -0
- package/adapters/facebook/marketplace-inbox.js +71 -0
- package/adapters/facebook/marketplace-listings.js +68 -0
- package/adapters/facebook/memories.js +38 -0
- package/adapters/facebook/notifications.js +82 -0
- package/adapters/facebook/posts.js +19 -0
- package/adapters/facebook/profile.js +66 -0
- package/adapters/facebook/search.js +20 -0
- package/adapters/facebook/site.json +1 -0
- package/adapters/gmail/_query.js +19 -0
- package/adapters/gmail/_shared.js +241 -0
- package/adapters/gmail/attachments.js +17 -0
- package/adapters/gmail/create-draft.js +13 -0
- package/adapters/gmail/delete.js +30 -0
- package/adapters/gmail/drafts.js +2 -0
- package/adapters/gmail/forward.js +30 -0
- package/adapters/gmail/important.js +2 -0
- package/adapters/gmail/inbox.js +2 -0
- package/adapters/gmail/labels.js +10 -0
- package/adapters/gmail/modify.js +44 -0
- package/adapters/gmail/reply.js +28 -0
- package/adapters/gmail/search.js +21 -0
- package/adapters/gmail/send.js +84 -0
- package/adapters/gmail/sent.js +2 -0
- package/adapters/gmail/site.json +1 -0
- package/adapters/gmail/snoozed.js +2 -0
- package/adapters/gmail/spam.js +2 -0
- package/adapters/gmail/starred.js +2 -0
- package/adapters/gmail/thread.js +16 -0
- package/adapters/gmail/trash.js +2 -0
- package/adapters/gmail/unread.js +2 -0
- package/adapters/linkedin/_profile-card.js +42 -0
- package/adapters/linkedin/_profile-sections.js +76 -0
- package/adapters/linkedin/_profile.js +112 -0
- package/adapters/linkedin/_shared.js +50 -0
- package/adapters/linkedin/company.js +56 -0
- package/adapters/linkedin/connect.js +53 -0
- package/adapters/linkedin/connections.js +45 -0
- package/adapters/linkedin/inbox.js +102 -0
- package/adapters/linkedin/job-detail.js +49 -0
- package/adapters/linkedin/jobs-preferences.js +33 -0
- package/adapters/linkedin/jobs.js +98 -0
- package/adapters/linkedin/people-search.js +52 -0
- package/adapters/linkedin/post-analytics.js +38 -0
- package/adapters/linkedin/posts.js +21 -0
- package/adapters/linkedin/profile-analytics.js +43 -0
- package/adapters/linkedin/profile-experience.js +18 -0
- package/adapters/linkedin/profile-projects.js +18 -0
- package/adapters/linkedin/profile-read.js +32 -0
- package/adapters/linkedin/salesnav-inbox.js +52 -0
- package/adapters/linkedin/salesnav-message.js +126 -0
- package/adapters/linkedin/salesnav-search.js +56 -0
- package/adapters/linkedin/salesnav-thread.js +106 -0
- package/adapters/linkedin/sent-invitations.js +40 -0
- package/adapters/linkedin/services-read.js +81 -0
- package/adapters/linkedin/site.json +3 -0
- package/adapters/linkedin/timeline.js +45 -0
- package/adapters/reddit/_shared.js +115 -0
- package/adapters/reddit/comment.js +26 -0
- package/adapters/reddit/frontpage.js +22 -0
- package/adapters/reddit/home.js +25 -0
- package/adapters/reddit/hot.js +25 -0
- package/adapters/reddit/popular.js +22 -0
- package/adapters/reddit/read.js +156 -0
- package/adapters/reddit/reply.js +26 -0
- package/adapters/reddit/save.js +21 -0
- package/adapters/reddit/saved.js +23 -0
- package/adapters/reddit/search.js +31 -0
- package/adapters/reddit/site.json +3 -0
- package/adapters/reddit/subreddit-info.js +39 -0
- package/adapters/reddit/subreddit.js +27 -0
- package/adapters/reddit/subscribe.js +20 -0
- package/adapters/reddit/subscribed.js +43 -0
- package/adapters/reddit/upvote.js +23 -0
- package/adapters/reddit/upvoted.js +23 -0
- package/adapters/reddit/user-comments.js +25 -0
- package/adapters/reddit/user-posts.js +25 -0
- package/adapters/reddit/user.js +36 -0
- package/adapters/reddit/whoami.js +29 -0
- package/adapters/twitter/_shared.js +345 -0
- package/adapters/twitter/accept.js +16 -0
- package/adapters/twitter/article.js +104 -0
- package/adapters/twitter/block.js +16 -0
- package/adapters/twitter/bookmark-folder.js +39 -0
- package/adapters/twitter/bookmark-folders.js +46 -0
- package/adapters/twitter/bookmark.js +14 -0
- package/adapters/twitter/bookmarks.js +33 -0
- package/adapters/twitter/collection.js +135 -0
- package/adapters/twitter/delete.js +14 -0
- package/adapters/twitter/device-follow.js +60 -0
- package/adapters/twitter/download.js +87 -0
- package/adapters/twitter/follow-batch.js +28 -0
- package/adapters/twitter/follow.js +16 -0
- package/adapters/twitter/followers.js +60 -0
- package/adapters/twitter/following.js +65 -0
- package/adapters/twitter/hide-reply.js +19 -0
- package/adapters/twitter/like.js +14 -0
- package/adapters/twitter/likes.js +41 -0
- package/adapters/twitter/list-add-batch.js +30 -0
- package/adapters/twitter/list-add.js +53 -0
- package/adapters/twitter/list-create.js +45 -0
- package/adapters/twitter/list-delete.js +15 -0
- package/adapters/twitter/list-remove-batch.js +30 -0
- package/adapters/twitter/list-remove.js +28 -0
- package/adapters/twitter/list-tweets.js +38 -0
- package/adapters/twitter/lists.js +18 -0
- package/adapters/twitter/mute-word.js +15 -0
- package/adapters/twitter/notifications.js +90 -0
- package/adapters/twitter/post.js +18 -0
- package/adapters/twitter/profile.js +43 -0
- package/adapters/twitter/quote.js +23 -0
- package/adapters/twitter/reply-dm.js +49 -0
- package/adapters/twitter/reply.js +23 -0
- package/adapters/twitter/retweet.js +16 -0
- package/adapters/twitter/search.js +150 -0
- package/adapters/twitter/site.json +3 -0
- package/adapters/twitter/thread.js +56 -0
- package/adapters/twitter/timeline.js +62 -0
- package/adapters/twitter/trending.js +32 -0
- package/adapters/twitter/tweets.js +46 -0
- package/adapters/twitter/unblock.js +16 -0
- package/adapters/twitter/unbookmark.js +14 -0
- package/adapters/twitter/unfollow.js +16 -0
- package/adapters/twitter/unlike.js +14 -0
- package/adapters/twitter/unretweet.js +15 -0
- package/cordis.patch.yml +15 -0
- package/dist/docs/api-reference.md +288 -0
- package/dist/docs/api-use.md +72 -0
- package/dist/docs/capabilities/cdp.md +7 -0
- package/dist/docs/capabilities/chrome.md +60 -0
- package/dist/docs/capabilities/visibility.md +2 -0
- package/dist/docs/capabilities/webmcp.md +2 -0
- package/dist/docs/define-tools.md +25 -0
- package/dist/docs/errors.md +28 -0
- package/dist/docs/instructions.md +14 -0
- package/dist/docs/js-tool.md +34 -0
- package/dist/docs/recon.md +5 -0
- package/dist/docs/repl-session.md +23 -0
- package/dist/docs/safety.md +8 -0
- package/dist/docs/sites.md +22 -0
- package/dist/docs/tab-lifecycle.md +15 -0
- package/dist/docs/troubleshooting.md +7 -0
- package/dist/src/api/action-input.js +165 -0
- package/dist/src/api/action-input.js.map +1 -0
- package/dist/src/api/agent.js +11 -0
- package/dist/src/api/agent.js.map +1 -0
- package/dist/src/api/api.js +69 -0
- package/dist/src/api/api.js.map +1 -0
- package/dist/src/api/browser.js +135 -0
- package/dist/src/api/browser.js.map +1 -0
- package/dist/src/api/context.js +2 -0
- package/dist/src/api/context.js.map +1 -0
- package/dist/src/api/diff.js +65 -0
- package/dist/src/api/diff.js.map +1 -0
- package/dist/src/api/errors.js +24 -0
- package/dist/src/api/errors.js.map +1 -0
- package/dist/src/api/network.js +33 -0
- package/dist/src/api/network.js.map +1 -0
- package/dist/src/api/observation.js +95 -0
- package/dist/src/api/observation.js.map +1 -0
- package/dist/src/api/streams.js +33 -0
- package/dist/src/api/streams.js.map +1 -0
- package/dist/src/api/tab.js +416 -0
- package/dist/src/api/tab.js.map +1 -0
- package/dist/src/backends/browser-helpers.js +76 -0
- package/dist/src/backends/browser-helpers.js.map +1 -0
- package/dist/src/backends/extension-page.js +305 -0
- package/dist/src/backends/extension-page.js.map +1 -0
- package/dist/src/backends/page-types.js +2 -0
- package/dist/src/backends/page-types.js.map +1 -0
- package/dist/src/docs/manifest.js +92 -0
- package/dist/src/docs/manifest.js.map +1 -0
- package/dist/src/docs/surface.js +95 -0
- package/dist/src/docs/surface.js.map +1 -0
- package/dist/src/host/bridge.js +126 -0
- package/dist/src/host/bridge.js.map +1 -0
- package/dist/src/host/doctor.js +92 -0
- package/dist/src/host/doctor.js.map +1 -0
- package/dist/src/host/extension.js +4 -0
- package/dist/src/host/extension.js.map +1 -0
- package/dist/src/host/host.js +77 -0
- package/dist/src/host/host.js.map +1 -0
- package/dist/src/host/ipc.js +80 -0
- package/dist/src/host/ipc.js.map +1 -0
- package/dist/src/host/jsonc-config.js +33 -0
- package/dist/src/host/jsonc-config.js.map +1 -0
- package/dist/src/host/launch.js +103 -0
- package/dist/src/host/launch.js.map +1 -0
- package/dist/src/host/native-messaging.js +81 -0
- package/dist/src/host/native-messaging.js.map +1 -0
- package/dist/src/host/opencode.js +14 -0
- package/dist/src/host/opencode.js.map +1 -0
- package/dist/src/host/pi.js +11 -0
- package/dist/src/host/pi.js.map +1 -0
- package/dist/src/host/registration.js +121 -0
- package/dist/src/host/registration.js.map +1 -0
- package/dist/src/host/setup.js +204 -0
- package/dist/src/host/setup.js.map +1 -0
- package/dist/src/host/socket.js +99 -0
- package/dist/src/host/socket.js.map +1 -0
- package/dist/src/host/state.js +124 -0
- package/dist/src/host/state.js.map +1 -0
- package/dist/src/launcher/stdio.js +153 -0
- package/dist/src/launcher/stdio.js.map +1 -0
- package/dist/src/lib/sources.js +27 -0
- package/dist/src/lib/sources.js.map +1 -0
- package/dist/src/main.js +131 -0
- package/dist/src/main.js.map +1 -0
- package/dist/src/mcp/catalog.js +28 -0
- package/dist/src/mcp/catalog.js.map +1 -0
- package/dist/src/mcp/js-evaluator.mjs +65 -0
- package/dist/src/mcp/js-session.js +292 -0
- package/dist/src/mcp/js-session.js.map +1 -0
- package/dist/src/mcp/js-worker.mjs +135 -0
- package/dist/src/mcp/server.js +221 -0
- package/dist/src/mcp/server.js.map +1 -0
- package/dist/src/protocol.js +18 -0
- package/dist/src/protocol.js.map +1 -0
- package/dist/src/recon/analyzer.js +366 -0
- package/dist/src/recon/analyzer.js.map +1 -0
- package/dist/src/recon/discover.js +130 -0
- package/dist/src/recon/discover.js.map +1 -0
- package/dist/src/runtime/runtime.js +221 -0
- package/dist/src/runtime/runtime.js.map +1 -0
- package/dist/src/shared/aria-tree.js +16 -0
- package/dist/src/shared/aria-tree.js.map +1 -0
- package/dist/src/shared/element-ref.js +7 -0
- package/dist/src/shared/element-ref.js.map +1 -0
- package/dist/src/shared/engine.js +426 -0
- package/dist/src/shared/engine.js.map +1 -0
- package/dist/src/shared/injected-source.js +5 -0
- package/dist/src/shared/injected-source.js.map +1 -0
- package/dist/src/shared/page-contract.js +8 -0
- package/dist/src/shared/page-contract.js.map +1 -0
- package/dist/src/sites/define.js +110 -0
- package/dist/src/sites/define.js.map +1 -0
- package/dist/src/sites/drafts.js +134 -0
- package/dist/src/sites/drafts.js.map +1 -0
- package/dist/src/sites/executor.js +75 -0
- package/dist/src/sites/executor.js.map +1 -0
- package/dist/src/sites/loader.js +234 -0
- package/dist/src/sites/loader.js.map +1 -0
- package/dist/src/sites/schema.js +169 -0
- package/dist/src/sites/schema.js.map +1 -0
- package/docs/api-reference.md +288 -0
- package/docs/api-use.md +72 -0
- package/docs/capabilities/cdp.md +7 -0
- package/docs/capabilities/chrome.md +60 -0
- package/docs/capabilities/visibility.md +2 -0
- package/docs/capabilities/webmcp.md +2 -0
- package/docs/define-tools.md +25 -0
- package/docs/errors.md +28 -0
- package/docs/guide.zh-CN.md +49 -0
- package/docs/instructions.md +14 -0
- package/docs/js-tool.md +34 -0
- package/docs/observation-design.md +43 -0
- package/docs/recon.md +5 -0
- package/docs/releasing.md +26 -0
- package/docs/repl-session.md +23 -0
- package/docs/safety.md +8 -0
- package/docs/setup.md +241 -0
- package/docs/sites.md +22 -0
- package/docs/tab-lifecycle.md +15 -0
- package/docs/troubleshooting.md +7 -0
- package/extension/dist/background.js +5263 -0
- package/extension/dist/chrome-reference.LICENSE.txt +21 -0
- package/extension/dist/content/cursor.js +156 -0
- package/extension/dist/cursor.svg +4 -0
- package/extension/dist/icons/icon-128.png +0 -0
- package/extension/dist/icons/icon-16.png +0 -0
- package/extension/dist/icons/icon-32.png +0 -0
- package/extension/dist/icons/icon-48.png +0 -0
- package/extension/dist/manifest.json +48 -0
- package/extension/dist/page.js +801 -0
- package/package.json +76 -4
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/** One adapter argument contract drives discovery, MCP schemas, and runtime validation. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { ActionError } from '../api/errors.js';
|
|
4
|
+
export function argSpec(args = []) {
|
|
5
|
+
return args.map((a) => ({ ...a, type: a.type ?? 'string', required: a.required === true }));
|
|
6
|
+
}
|
|
7
|
+
function valueToZod(value, depth = 0) {
|
|
8
|
+
if (depth > 8)
|
|
9
|
+
throw new Error('adapter argument schema is too deeply nested');
|
|
10
|
+
let t;
|
|
11
|
+
switch (value.type ?? 'string') {
|
|
12
|
+
case 'string':
|
|
13
|
+
t = z.string();
|
|
14
|
+
if (value.minLength !== undefined)
|
|
15
|
+
t = t.min(value.minLength);
|
|
16
|
+
if (value.maxLength !== undefined)
|
|
17
|
+
t = t.max(value.maxLength);
|
|
18
|
+
break;
|
|
19
|
+
case 'int':
|
|
20
|
+
t = z.number().int();
|
|
21
|
+
if (value.min !== undefined)
|
|
22
|
+
t = t.min(value.min);
|
|
23
|
+
if (value.max !== undefined)
|
|
24
|
+
t = t.max(value.max);
|
|
25
|
+
break;
|
|
26
|
+
case 'number':
|
|
27
|
+
t = z.number();
|
|
28
|
+
if (value.min !== undefined)
|
|
29
|
+
t = t.min(value.min);
|
|
30
|
+
if (value.max !== undefined)
|
|
31
|
+
t = t.max(value.max);
|
|
32
|
+
break;
|
|
33
|
+
case 'boolean':
|
|
34
|
+
t = z.boolean();
|
|
35
|
+
break;
|
|
36
|
+
case 'array':
|
|
37
|
+
t = z.array(valueToZod(value.items ?? { type: 'string' }, depth + 1));
|
|
38
|
+
if (value.min !== undefined)
|
|
39
|
+
t = t.min(value.min);
|
|
40
|
+
if (value.max !== undefined)
|
|
41
|
+
t = t.max(value.max);
|
|
42
|
+
break;
|
|
43
|
+
case 'object': {
|
|
44
|
+
const shape = {};
|
|
45
|
+
for (const [key, field] of Object.entries(value.properties ?? {})) {
|
|
46
|
+
let fieldType = valueToZod(field, depth + 1);
|
|
47
|
+
if (field.help)
|
|
48
|
+
fieldType = fieldType.describe(field.help);
|
|
49
|
+
shape[key] = field.required ? fieldType : fieldType.optional();
|
|
50
|
+
}
|
|
51
|
+
t = z.object(shape).strict();
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
default: throw new Error(`unknown adapter argument type: ${String(value.type)}`);
|
|
55
|
+
}
|
|
56
|
+
if (value.choices?.length) {
|
|
57
|
+
const literals = value.choices.map((choice) => z.literal(choice));
|
|
58
|
+
t = z.union(literals).and(t);
|
|
59
|
+
}
|
|
60
|
+
if (value.nullable)
|
|
61
|
+
t = t.nullable();
|
|
62
|
+
const desc = value.example !== undefined ? `example: ${JSON.stringify(value.example)}` : '';
|
|
63
|
+
return desc ? t.describe(desc) : t;
|
|
64
|
+
}
|
|
65
|
+
export function argToZod(arg) {
|
|
66
|
+
let t = valueToZod(arg);
|
|
67
|
+
const desc = [arg.help, arg.default !== undefined ? `default: ${JSON.stringify(arg.default)}` : ''].filter(Boolean).join(' · ');
|
|
68
|
+
if (desc)
|
|
69
|
+
t = t.describe(desc);
|
|
70
|
+
return arg.required ? t : t.optional();
|
|
71
|
+
}
|
|
72
|
+
export function argsToShape(args = [], extra = {}) {
|
|
73
|
+
const shape = {};
|
|
74
|
+
for (const a of args)
|
|
75
|
+
shape[a.name] = argToZod(a);
|
|
76
|
+
for (const [k, v] of Object.entries(extra))
|
|
77
|
+
if (!(k in shape))
|
|
78
|
+
shape[k] = v;
|
|
79
|
+
return shape;
|
|
80
|
+
}
|
|
81
|
+
function invalidArgs(message, args) {
|
|
82
|
+
throw new ActionError('invalid_args', message, 'Call again with the fields in details.expected. Do not guess.', { details: { expected: argSpec(args) } });
|
|
83
|
+
}
|
|
84
|
+
export function validateArgDefinitions(args = []) {
|
|
85
|
+
const names = new Set();
|
|
86
|
+
for (const arg of args) {
|
|
87
|
+
if (!/^[a-z][a-z0-9_]*$/.test(arg.name) || names.has(arg.name))
|
|
88
|
+
throw new Error(`invalid or duplicate argument name: ${arg.name}`);
|
|
89
|
+
names.add(arg.name);
|
|
90
|
+
validateValueDefinition(arg, arg.name);
|
|
91
|
+
const schema = valueToZod(arg);
|
|
92
|
+
if (arg.default !== undefined && !schema.safeParse(arg.default).success)
|
|
93
|
+
throw new Error(`invalid default for argument ${arg.name}`);
|
|
94
|
+
if (arg.required && arg.default !== undefined)
|
|
95
|
+
throw new Error(`argument ${arg.name} cannot be required and have a default`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function validateValueDefinition(value, location, depth = 0) {
|
|
99
|
+
if (depth > 8)
|
|
100
|
+
throw new Error(`argument ${location} is too deeply nested`);
|
|
101
|
+
const type = value.type ?? 'string';
|
|
102
|
+
if (value.min !== undefined && value.max !== undefined && value.min > value.max)
|
|
103
|
+
throw new Error(`argument ${location} has min > max`);
|
|
104
|
+
if (value.minLength !== undefined && value.maxLength !== undefined && value.minLength > value.maxLength)
|
|
105
|
+
throw new Error(`argument ${location} has minLength > maxLength`);
|
|
106
|
+
if (value.min !== undefined || value.max !== undefined)
|
|
107
|
+
if (!['int', 'number', 'array'].includes(type))
|
|
108
|
+
throw new Error(`argument ${location}: min/max require a number or array`);
|
|
109
|
+
if (value.minLength !== undefined || value.maxLength !== undefined)
|
|
110
|
+
if (type !== 'string')
|
|
111
|
+
throw new Error(`argument ${location}: minLength/maxLength require a string`);
|
|
112
|
+
if (type === 'array') {
|
|
113
|
+
if (!value.items)
|
|
114
|
+
throw new Error(`array argument ${location} needs items`);
|
|
115
|
+
validateValueDefinition(value.items, `${location}[]`, depth + 1);
|
|
116
|
+
}
|
|
117
|
+
else if (value.items)
|
|
118
|
+
throw new Error(`argument ${location}: items require an array`);
|
|
119
|
+
if (type === 'object') {
|
|
120
|
+
if (!value.properties)
|
|
121
|
+
throw new Error(`object argument ${location} needs properties`);
|
|
122
|
+
for (const [name, field] of Object.entries(value.properties)) {
|
|
123
|
+
if (!/^[a-z][a-z0-9_]*$/.test(name))
|
|
124
|
+
throw new Error(`invalid object property ${location}.${name}`);
|
|
125
|
+
validateValueDefinition(field, `${location}.${name}`, depth + 1);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
else if (value.properties)
|
|
129
|
+
throw new Error(`argument ${location}: properties require an object`);
|
|
130
|
+
if (value.choices !== undefined) {
|
|
131
|
+
if (!value.choices.length || !['string', 'int', 'number', 'boolean'].includes(type))
|
|
132
|
+
throw new Error(`argument ${location}: choices require a nonempty scalar list`);
|
|
133
|
+
const withoutChoices = { ...value, choices: undefined };
|
|
134
|
+
const base = valueToZod(withoutChoices, depth);
|
|
135
|
+
if (value.choices.some((choice) => !base.safeParse(choice).success))
|
|
136
|
+
throw new Error(`argument ${location}: choices do not match the declared type or bounds`);
|
|
137
|
+
}
|
|
138
|
+
if (value.example !== undefined && !valueToZod(value, depth).safeParse(value.example).success)
|
|
139
|
+
throw new Error(`argument ${location}: example does not match the declared type`);
|
|
140
|
+
}
|
|
141
|
+
/** Coerce CLI-like scalar input once, then validate the same schema exposed to MCP. */
|
|
142
|
+
export function coerceArgs(cmdArgs = [], kwargs) {
|
|
143
|
+
const names = new Set(cmdArgs.map((a) => a.name));
|
|
144
|
+
const unknown = Object.keys(kwargs).filter((name) => !names.has(name));
|
|
145
|
+
if (unknown.length)
|
|
146
|
+
invalidArgs(`Unknown argument${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`, cmdArgs);
|
|
147
|
+
const out = {};
|
|
148
|
+
for (const def of cmdArgs) {
|
|
149
|
+
let val = kwargs[def.name];
|
|
150
|
+
if (val === undefined && def.default !== undefined)
|
|
151
|
+
val = def.default;
|
|
152
|
+
if (def.required && (val === undefined || val === null && !def.nullable || val === ''))
|
|
153
|
+
invalidArgs(`Argument "${def.name}" is required. ${def.help ?? ''}`.trim(), cmdArgs);
|
|
154
|
+
if (val === undefined)
|
|
155
|
+
continue;
|
|
156
|
+
if ((def.type === 'int' || def.type === 'number') && typeof val === 'string' && val.trim())
|
|
157
|
+
val = Number(val);
|
|
158
|
+
if (def.type === 'boolean' && typeof val === 'string' && ['true', 'false', '1', '0'].includes(val.toLowerCase()))
|
|
159
|
+
val = ['true', '1'].includes(val.toLowerCase());
|
|
160
|
+
const parsed = valueToZod(def).safeParse(val);
|
|
161
|
+
if (!parsed.success) {
|
|
162
|
+
const message = def.type === 'boolean' ? 'must be a boolean' : def.choices?.length ? `must be one of ${def.choices.join(', ')}` : parsed.error.issues.map((i) => i.message).join('; ');
|
|
163
|
+
invalidArgs(`Argument "${def.name}" ${message}`, cmdArgs);
|
|
164
|
+
}
|
|
165
|
+
out[def.name] = parsed.data;
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/sites/schema.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,OAAO,EAAE,CAAC,EAAmB,MAAM,KAAK,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAM/C,MAAM,UAAU,OAAO,CAAC,OAAc,EAAE;IACtC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,IAAI,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC;AAC9F,CAAC;AAED,SAAS,UAAU,CAAC,KAAe,EAAE,KAAK,GAAG,CAAC;IAC5C,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAC/E,IAAI,CAAa,CAAC;IAClB,QAAQ,KAAK,CAAC,IAAI,IAAI,QAAQ,EAAE,CAAC;QAC/B,KAAK,QAAQ;YAAE,CAAC,GAAG,CAAC,CAA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,aAAa,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;QAC5D,CAAC;QACD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC;IAC9B,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
## API reference (generated from the public TypeScript declarations — do not edit)
|
|
2
|
+
|
|
3
|
+
In `js` the globals are `browser`, `agent`, `sites`, `recon`, `tools`, `session` and `nodeRepl`. Await API methods; returned Tab and Browser handles persist across calls. Use docs_get with name:"api-reference" and member:"Tab.act" (or another class/member) for a focused reference. Site adapter definitions are documented in `define-tools`.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
interface AgentApi {
|
|
7
|
+
agent: { browsers: { getDefault(): Promise<Browser>; }; browser: Browser; documentation: { get(name: string): Promise<string | null>; }; };
|
|
8
|
+
sites: Record<string, unknown> & { search(q: string, limit?: number): Promise<unknown>; list(): Promise<unknown>; enable(site: string, opts?: { write?: boolean; }): Promise<{ site: string; tools: Array<string>; }>; disable(site: string): Promise<boolean>; run(site: string, name: string, args?: Record<string, unknown>): Promise<unknown>; };
|
|
9
|
+
recon: {
|
|
10
|
+
discover(tab: Tab, opts?: { maxScripts?: number; includeStatic?: boolean; includeAssets?: boolean; includeInline?: boolean; fetchTimeoutMs?: number; network?: Array<Record<string, unknown>>; }): Promise<DiscoverResult>;
|
|
11
|
+
};
|
|
12
|
+
tools: {
|
|
13
|
+
define(def: ToolDefinition | (Omit<ToolDefinition, "func"> & { func?: string | ((ctx: Record<string, unknown>) => unknown); })): Promise<{ draftId: string; site: string; name: string; args: Array<Arg>; }>;
|
|
14
|
+
try(draftId: string, args: Record<string, unknown>, expect: DraftExpectation): Promise<{ result: CommandRunResult | CommandRunError; verification: { passed: boolean; checks: Array<{ check: string; passed: boolean; actual?: unknown; }>; }; }>;
|
|
15
|
+
activate(draftId: string): Promise<{ site: string; name: string; file: string; verifiedAt: string; }>;
|
|
16
|
+
discard(draftId: string): Promise<{ draftId: string; discarded: true; }>;
|
|
17
|
+
list(): Promise<Array<{ site: string; name: string; file: string; }>>;
|
|
18
|
+
remove(site: string, name: string): Promise<boolean>;
|
|
19
|
+
};
|
|
20
|
+
session: { id: string; };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
class Browser {
|
|
24
|
+
id: "chrome";
|
|
25
|
+
type: "extension";
|
|
26
|
+
chrome: { // Native Chrome APIs in the extension service worker. Positional JSON arguments, native return values.
|
|
27
|
+
call(method: string, args?: Array<unknown>): Promise<unknown>;
|
|
28
|
+
describe(member: string): Promise<unknown>;
|
|
29
|
+
watch(event: string, options?: StreamOptions): Promise<EventStream>;
|
|
30
|
+
};
|
|
31
|
+
logs: { // This extension's own service-worker logs; not logs of other installed extensions.
|
|
32
|
+
watch(options?: StreamOptions): Promise<EventStream>;
|
|
33
|
+
read(options?: StreamReadOptions): Promise<StreamBatch>;
|
|
34
|
+
};
|
|
35
|
+
tabs: {
|
|
36
|
+
new(url?: string): Promise<Tab>;
|
|
37
|
+
list(): Promise<Array<{ id?: string; tabId: number; pending?: true; url?: string; title?: string; active: boolean; selected: boolean; origin: "agent" | "user"; state: "active" | "handoff"; }>>;
|
|
38
|
+
get(id: string): Promise<Tab>;
|
|
39
|
+
selected(): Promise<Tab | undefined>;
|
|
40
|
+
finalize(opts?: { keep?: Array<{ tab: string | Tab; status: "handoff" | "deliverable"; }>; }): Promise<{ closed: Array<string>; kept: Array<string>; failed: Array<{ page: string; reason: string; }>; }>;
|
|
41
|
+
};
|
|
42
|
+
user: {
|
|
43
|
+
openTabs(options?: { query?: string; limit?: number; }): Promise<Array<UserTabInfo>>;
|
|
44
|
+
claimTab(tab: { tabId?: number; active?: boolean; title?: string; url?: string; expectedUrl?: string; expectedTitle?: string; }): Promise<Tab>; // Claim by foreground, id, or unique url/title lookup; expected fields verify the tab's current identity.
|
|
45
|
+
closeTabs(tabIds: Array<number>): Promise<CloseUserTabsResult>; // Close user tabs by Chrome id without claiming or loading their pages.
|
|
46
|
+
};
|
|
47
|
+
nameSession(name: string): Promise<void>;
|
|
48
|
+
capabilities: {
|
|
49
|
+
list(): Promise<Array<{ id: string; description: string; }>>;
|
|
50
|
+
get(id: string): Promise<Record<string, unknown>>;
|
|
51
|
+
};
|
|
52
|
+
documentation(): Promise<string>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
class Tab {
|
|
56
|
+
tabId?: number; // `id` is the Chrome tab id as a string; `tabId` is the numeric id when claimed from a user tab.
|
|
57
|
+
id: string;
|
|
58
|
+
goto(url: string, opts?: { waitUntil?: "load" | "none"; settleMs?: number; }): Promise<{ url: string | null; title: string | null; }>;
|
|
59
|
+
url(): Promise<string | null>;
|
|
60
|
+
title(): Promise<string | null>;
|
|
61
|
+
back(): Promise<void>;
|
|
62
|
+
forward(): Promise<void>;
|
|
63
|
+
reload(): Promise<void>;
|
|
64
|
+
close(): Promise<void>; // Close this tab, whether it was opened or claimed by this session.
|
|
65
|
+
release(): Promise<void>; // Keep this tab open and give up this session's control of it.
|
|
66
|
+
observe(opts?: ObserveOptions): Promise<ObserveResult>; // ARIA overview by default; format:'dom' reveals visible controls and live attributes. Child-frame refs must be used with their returned frame path.
|
|
67
|
+
screenshot(opts?: { fullPage?: boolean; annotate?: boolean; format?: "png" | "jpeg"; quality?: number; }): Promise<ImageValue>;
|
|
68
|
+
find(target: (Target & { limit?: number; }) | { query: string; limit?: number; frame?: FrameStep | Array<FrameStep>; }): Promise<FindResult | ElementAtResult | QueryFindResult>;
|
|
69
|
+
read(opts: ReadElementOptions): Promise<ElementDetails>; // With target: exact current element text, attributes and live values, without scrolling. Otherwise: bounded document text scan (including open shadow roots), restores scroll; readId/nextStart continue the same capture. A growing feed returns reason `unbounded`; the scan stops rather than chasing an endless bottom.
|
|
70
|
+
read(opts?: ReadOptions): Promise<ReadTextResult>; // With target: exact current element text, attributes and live values, without scrolling. Otherwise: bounded document text scan (including open shadow roots), restores scroll; readId/nextStart continue the same capture. A growing feed returns reason `unbounded`; the scan stops rather than chasing an endless bottom.
|
|
71
|
+
act(opts: ActOptions): Promise<ActionOutcome>; // wait + act in one call at the runtime edge: locate → wait actionable → hit-test → real input → settle. `method:'dom'` skips the mouse event.
|
|
72
|
+
webmcp: { // WebMCP: tools the page itself registers via navigator.modelContext (page-provided tool source).
|
|
73
|
+
list(): Promise<Array<{ name: string; description?: string; inputSchema?: unknown; }>>;
|
|
74
|
+
call(name: string, input?: Record<string, unknown>): Promise<unknown>;
|
|
75
|
+
};
|
|
76
|
+
expect(what: Expectation, opts?: { timeoutMs?: number; }): Promise<CheckResult>; // Assert what the page must show now (polled up to timeoutMs).
|
|
77
|
+
evaluate(script: string | ((arg: any) => any), opts?: { arg?: unknown; frame?: number; timeoutMs?: number; }): Promise<unknown>; // Main World page code; functions receive only opts.arg, never host closures. Dispatched scripts are never replayed.
|
|
78
|
+
cdp: { // Native CDP on this Tab's shared debugger attachment. Parameters are not rewritten.
|
|
79
|
+
send(method: string, params?: Record<string, unknown>, target?: { frameId: string; }): Promise<unknown>;
|
|
80
|
+
watch(event: string, options?: StreamOptions): Promise<EventStream>;
|
|
81
|
+
};
|
|
82
|
+
dialog: { // Native alert/confirm/prompt dialogs block the page; commands fail with `dialog_open` until answered.
|
|
83
|
+
get(): Promise<DialogInfo | null>;
|
|
84
|
+
accept(text?: string): Promise<DialogInfo | null>;
|
|
85
|
+
dismiss(): Promise<DialogInfo | null>;
|
|
86
|
+
};
|
|
87
|
+
console: { // Console messages and uncaught exceptions since the tab was attached (the plugin's tab.dev.logs); cursor-paged like network.read.
|
|
88
|
+
read(opts?: StreamReadOptions): Promise<StreamBatch>;
|
|
89
|
+
watch(options?: StreamOptions): Promise<EventStream>;
|
|
90
|
+
};
|
|
91
|
+
network: {
|
|
92
|
+
start(pattern?: string): Promise<boolean>;
|
|
93
|
+
list(opts?: { filter?: string; limit?: number; afterSequence?: number; }): Promise<{ cursor: number; entries: Array<Record<string, unknown>>; hasMore: boolean; }>;
|
|
94
|
+
detail(opts: { seq?: number; requestId?: string; part?: "request" | "response"; start?: number; maxChars?: number; }): Promise<Record<string, unknown>>;
|
|
95
|
+
read(opts?: { pattern?: string; limit?: number; includeStatic?: boolean; afterSequence?: number; }): Promise<{ cursor: number; entries: Array<unknown>; hasMore: boolean; }>; // Cursor-paged read: pass `afterSequence` from the previous result to get only new requests. Returns network rows only; endpoint candidates come from the explicit `recon.discover(tab)` (not a hidden side effect of reading).
|
|
96
|
+
};
|
|
97
|
+
cookies(domain: string): Promise<Array<unknown>>;
|
|
98
|
+
cookie(name: string, opts?: { domain?: string; }): Promise<string | undefined>; // Read one cookie's value at run time — useful for per-request tokens an adapter needs (csrf/ct0/ csrftoken/XSRF-TOKEN). Defaults to the current page's host. Returns undefined when the cookie is absent.
|
|
99
|
+
fetchJson(url: string, opts?: Record<string, unknown>): Promise<unknown>; // Fetch JSON through the page (its cookies and origin) after verifying the endpoint.
|
|
100
|
+
frames(): Promise<Array<{ index: number; frameId: string; url: string; name: string; crossOrigin?: boolean; oopif?: boolean; }>>;
|
|
101
|
+
download(afterSequence: number, timeoutMs?: number): Promise<DownloadWaitResult>; // Wait for the page download begun after a tab.act cursor, then check Chrome's file state.
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
type Target = ({ frame?: FrameStep | FrameStep[]; within?: string }) & (
|
|
105
|
+
| { ref: number | string }
|
|
106
|
+
| { selector: string; nth?: number }
|
|
107
|
+
| { role?: string; name?: string; label?: string; text?: string; testid?: string; nth?: number }
|
|
108
|
+
| { x: number; y: number });
|
|
109
|
+
|
|
110
|
+
type FrameStep = string | number;
|
|
111
|
+
|
|
112
|
+
type ActAction = 'click' | 'dblclick' | 'hover' | 'focus' | 'fill' | 'type' | 'press' | 'select' | 'check' | 'uncheck' | 'upload' | 'drag' | 'scroll' | 'back' | 'forward' | 'reload';
|
|
113
|
+
|
|
114
|
+
interface ActOptions { target?: Target; action: ActAction; value?: string; files?: string[]; to?: Target; direction?: 'up' | 'down' | 'left' | 'right'; amount?: number; timeoutMs?: number; settleMs?: number; method?: 'cdp' | 'dom' }
|
|
115
|
+
|
|
116
|
+
interface ActionOutcome {
|
|
117
|
+
action: ActAction;
|
|
118
|
+
delivery: 'applied' | 'received' | 'dispatched';
|
|
119
|
+
controlState: 'verified' | 'unverified';
|
|
120
|
+
network?: { afterSequence: number; cursor: number };
|
|
121
|
+
matches_n?: number;
|
|
122
|
+
navigated?: boolean; url?: string; title?: string; timedOut?: boolean;
|
|
123
|
+
ref?: string; filled?: boolean; verified?: boolean; actual?: string;
|
|
124
|
+
checked?: boolean; changed?: boolean; selected?: string[]; files?: number;
|
|
125
|
+
openedTabs?: Array<{ tab?: string; tabId: number; url?: string; title?: string; pending?: true }>;
|
|
126
|
+
download?: { afterSequence: number; started: Array<{ seq: number; guid?: string; url: string; suggestedFilename: string }> }; method?: 'dom';
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface ObserveOptions { cursor?: string;
|
|
130
|
+
mode?: 'state' | 'screenshot' | 'both'; format?: 'aria' | 'dom'; frame?: FrameStep | FrameStep[]; since?: string; viewport?: boolean; ref?: string; target?: Target; start?: number;
|
|
131
|
+
limit?: number; includeFrames?: boolean; annotate?: boolean;
|
|
132
|
+
fullPage?: boolean;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
interface ReadOptions { maxChars?: number; start?: number; readId?: string; frame?: FrameStep | FrameStep[] }
|
|
136
|
+
|
|
137
|
+
interface ImageValue { __image: true; mimeType: string; base64: string }
|
|
138
|
+
|
|
139
|
+
interface Box { x: number; y: number; w: number; h: number }
|
|
140
|
+
|
|
141
|
+
interface FindEntry {
|
|
142
|
+
nth: number;
|
|
143
|
+
ref: string | null;
|
|
144
|
+
selector: string | null;
|
|
145
|
+
tag: string; role: string; name: string; text: string;
|
|
146
|
+
attrs: Record<string, string>;
|
|
147
|
+
visible: boolean; enabled: boolean | null; editable: boolean | null;
|
|
148
|
+
box: Box;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
interface FindResult { matches_n: number; visible_n: number; selector: string; entries: FindEntry[] }
|
|
152
|
+
|
|
153
|
+
interface QueryFindResult { matches_n: number; entries: Array<FindEntry & { path: string[]; interactiveAncestorRef: string | null }> }
|
|
154
|
+
|
|
155
|
+
interface ElementAtResult { matches_n: number; entries: FindEntry[] }
|
|
156
|
+
|
|
157
|
+
interface ReadTextResult { readId: string; text: string; complete: boolean; reason?: 'budget' | 'scan_limit' | 'unbounded' | 'stale'; chars: number; start: number; nextStart?: number }
|
|
158
|
+
|
|
159
|
+
interface Expectation { text?: string; notText?: string; selector?: string; ref?: string; url?: string; title?: string; visible?: boolean }
|
|
160
|
+
|
|
161
|
+
interface CheckResult { ok: boolean; failed: string[]; url: string; title: string }
|
|
162
|
+
|
|
163
|
+
interface DialogInfo { type: 'alert' | 'confirm' | 'prompt' | 'beforeunload'; message: string; defaultPrompt?: string; url?: string; openedAt: number }
|
|
164
|
+
|
|
165
|
+
interface ConsoleEntry { seq: number; level: 'debug' | 'info' | 'log' | 'warn' | 'error'; message: string; timestamp: string; url?: string; line?: number }
|
|
166
|
+
|
|
167
|
+
interface UserTabInfo { tabId: number; title?: string; url?: string; windowId: number; active: boolean; groupId?: number; lastAccessed?: number }
|
|
168
|
+
|
|
169
|
+
interface CloseUserTabsResult {
|
|
170
|
+
complete: boolean;
|
|
171
|
+
closed: number[];
|
|
172
|
+
failed: Array<{ tabId: number; reason: string }>;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
interface DownloadWaitResult {
|
|
176
|
+
downloaded: boolean;
|
|
177
|
+
started: boolean;
|
|
178
|
+
sequence?: number;
|
|
179
|
+
suggestedFilename?: string; association?: 'url+event';
|
|
180
|
+
candidates?: number;
|
|
181
|
+
id?: number;
|
|
182
|
+
filename?: string;
|
|
183
|
+
url?: string;
|
|
184
|
+
finalUrl?: string;
|
|
185
|
+
mime?: string;
|
|
186
|
+
totalBytes?: number;
|
|
187
|
+
state?: string;
|
|
188
|
+
danger?: string;
|
|
189
|
+
error?: string;
|
|
190
|
+
elapsedMs: number;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
interface EventStream { read(options?: StreamReadOptions): Promise<StreamBatch>; close(): Promise<void>;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
interface ObservedContent { metadataTruncated?: boolean; stateContinued?: boolean; stateContinues?: boolean; state?: string; dom?: DomSnapshot; warnings?: string[]; diff?: boolean; changed?: { added: number; removed: number; changed?: number } }
|
|
197
|
+
|
|
198
|
+
interface ObservedFrame extends ObservedContent { frame: FrameStep[]; owner: FrameOwner; unavailable?: string }
|
|
199
|
+
|
|
200
|
+
interface ObserveResult extends ObservedContent { complete?: boolean; nextCursor?: string;
|
|
201
|
+
url: string | null; title: string | null; snapshotId?: string; image?: ImageValue; frames?: ObservedFrame[]; framesComplete?: boolean;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
interface ReadElementOptions { target: Target }
|
|
205
|
+
|
|
206
|
+
interface DomEntry { ref: string; tag: string; text: string; attrs: Record<string, string>; truncated: boolean }
|
|
207
|
+
|
|
208
|
+
interface DomSnapshot { entries: DomEntry[]; total: number; start: number; nextStart?: number; scope: 'viewport' | 'document' }
|
|
209
|
+
|
|
210
|
+
interface FrameOwner { ref: string; id: string; name: string; src: string }
|
|
211
|
+
|
|
212
|
+
interface ElementDetails { ref: string; tag: string; name: string; text: string; attrs: Record<string, string> }
|
|
213
|
+
|
|
214
|
+
interface StreamReadOptions { cursor?: string; limit?: number; levels?: string[]; filter?: string }
|
|
215
|
+
|
|
216
|
+
interface StreamOptions { capacity?: number; args?: unknown[] }
|
|
217
|
+
|
|
218
|
+
interface StreamEntry { seq: number; timestamp: string; event?: string; args?: unknown[]; params?: unknown; level?: string; message?: string; url?: string; line?: number; truncated?: boolean }
|
|
219
|
+
|
|
220
|
+
interface StreamBatch { entries: StreamEntry[]; cursor: string; hasMore: boolean; dropped: number; reset: boolean; closed?: boolean; reason?: string }
|
|
221
|
+
|
|
222
|
+
interface ToolDefinition {
|
|
223
|
+
site: string;
|
|
224
|
+
name: string;
|
|
225
|
+
description: string;
|
|
226
|
+
access: 'read' | 'write';
|
|
227
|
+
domain?: string;
|
|
228
|
+
result?: { kind: 'rows' | 'value'; description: string; fields?: Record<string, string>; paginated?: boolean };
|
|
229
|
+
args?: Arg[]; func: string;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
interface DraftExpectation { path?: string; equals?: unknown; minRows?: number }
|
|
233
|
+
|
|
234
|
+
interface CommandRunResult { ok: true; site: string; name: string; rows?: unknown[]; value?: unknown; nextCursor?: string; elapsedMs: number }
|
|
235
|
+
|
|
236
|
+
interface CommandRunError { ok: false; site: string; name: string; error: { code: string; message: string; hint?: string; details?: Record<string, unknown> }; elapsedMs: number }
|
|
237
|
+
|
|
238
|
+
interface EndpointCandidate {
|
|
239
|
+
url: string;
|
|
240
|
+
method: string;
|
|
241
|
+
type: string;
|
|
242
|
+
kind: UrlMatch['kind'];
|
|
243
|
+
queryParams: string[];
|
|
244
|
+
bodyParams: string[];
|
|
245
|
+
evidence: 'network+static' | 'network' | 'static';
|
|
246
|
+
network?: { status?: number; contentType?: string; count: number; requestId?: string };
|
|
247
|
+
sources: Array<{ script: string; line: number; snippet: string }>;
|
|
248
|
+
score: number;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
interface DiscoverResult {
|
|
252
|
+
pageUrl: string | null;
|
|
253
|
+
scripts: Array<{ url: string; bytes: number; analyzed: boolean; error?: string }>;
|
|
254
|
+
endpoints: EndpointCandidate[];
|
|
255
|
+
networkEntries: number;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface UrlMatch {
|
|
259
|
+
url: string;
|
|
260
|
+
method: string;
|
|
261
|
+
type: string;
|
|
262
|
+
queryParams: string[];
|
|
263
|
+
bodyParams: string[];
|
|
264
|
+
headers?: Record<string, string>;
|
|
265
|
+
contentType?: string;
|
|
266
|
+
kind: 'api' | 'asset' | 'page' | 'unknown';
|
|
267
|
+
line: number;
|
|
268
|
+
source: string;
|
|
269
|
+
filename?: string;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
interface ArgValue {
|
|
273
|
+
type?: 'string' | 'int' | 'number' | 'boolean' | 'array' | 'object';
|
|
274
|
+
nullable?: boolean;
|
|
275
|
+
choices?: Array<string | number | boolean>;
|
|
276
|
+
items?: ArgValue;
|
|
277
|
+
properties?: Record<string, ArgValue & { required?: boolean; help?: string }>;
|
|
278
|
+
min?: number;
|
|
279
|
+
max?: number;
|
|
280
|
+
minLength?: number;
|
|
281
|
+
maxLength?: number; example?: unknown;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
interface Arg extends ArgValue { name: string;
|
|
285
|
+
required?: boolean;
|
|
286
|
+
default?: unknown; help?: string;
|
|
287
|
+
}
|
|
288
|
+
```
|
package/docs/api-use.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
## How to act on a page
|
|
2
|
+
|
|
3
|
+
The core loop and the discipline that makes it reliable. Use `js` and await every API method. Exact signatures are available through `docs_get {name:"api-reference",member:"Tab.act"}`; error families are in `errors`.
|
|
4
|
+
|
|
5
|
+
1. **Loop:** `browser.tabs.new` (or `browser.user.claimTab` a tab the user already has) → `tab.observe` → `tab.act` → `tab.observe`. One
|
|
6
|
+
`tab.act` call does everything (waits for actionable, scrolls, hit-tests, dispatches real input, settles).
|
|
7
|
+
2. **Locators come from the latest observe — never guess one.** Use a `{ref:"..."}` from the last observe, or a
|
|
8
|
+
role/name/label/text/testid you can read there. `tab.act` is strict: exactly one visible match acts; several fail
|
|
9
|
+
with `selector_ambiguous` (no `nth`/first shortcut through ambiguity). Scope generic labels (Close, Search, Add to
|
|
10
|
+
cart, S/M/L) with `within` (a container's selector or its observed ref). After a strict failure, observe or `find` again —
|
|
11
|
+
never retry the same target unchanged. `tab.find(target)` (in `js`) runs the same engine; pass an entry's `selector`
|
|
12
|
+
back to act on that exact element. Durability order: `testid` → stable `id`/`data-*` → stable `href` → `role`+`name`
|
|
13
|
+
→ `label` → `text` → structural css.
|
|
14
|
+
3. **Refs identify Elements in one document/frame.** Copy them unchanged. The same living Element keeps its ref across observations; replacement, navigation or engine reset invalidates it. On `stale_ref`, observe again in the intended frame. A ref never automatically resolves to a replacement Element.
|
|
15
|
+
4. **Branch on `error.code`, never message text.** Full families and what to do for each are in the `errors` doc.
|
|
16
|
+
5. **iframes:** add `frame` to the target — `{frame:"#checkout", role:"button", name:"Pay"}`, `frame:0`, or a chain
|
|
17
|
+
outermost-first `frame:["#checkout", 0]` / `"#checkout >> iframe.card"`. Same-origin, data:/srcdoc, and cross-origin
|
|
18
|
+
are entered the same way. `observe()` includes child observations in `frames`, each with a reusable `frame` path and local refs. Copy that path into `target.frame` for `find/read/act` or `frame` for `observe/read`. `framesComplete:false` and `unavailable` identify a failed or bounded child capture. Observe that frame directly to retry; `includeFrames:false` limits observation to the selected document. Observations never scroll iframe owners.
|
|
19
|
+
6. **Don't re-`goto` a URL the tab is already on** (it reloads and loses form state); use `await tab.act({action:"reload"})`
|
|
20
|
+
when a reload is intended.
|
|
21
|
+
7. **`tab.evaluate(script, {arg, frame, timeoutMs})` runs in page Main World and can read or modify it.** Functions receive only `arg`, not host closures. Results must be serializable data. Prefer `tab.act()` for ordinary input and its verification. Dispatched scripts are never replayed; a timeout does not cancel page code.
|
|
22
|
+
8. **Choose the data path for the task.** For a reusable adapter, start from the UI behavior and inspect the request that carried the data. Every session tab captures from attach: `tab.network.list()` returns compact request summaries; detail by `seq` returns headers and a bounded request or response body. Continue with `body.nextStart` when needed. In `js`, use `tab.network.list()` and `tab.network.detail({seq})`. `recon.discover(tab)` ranks captured requests, and `{includeStatic:true}` adds script analysis only when needed. Replay a candidate with `tab.fetchJson(url,{method,headers,body})` inside the logged-in page, then compare its result to the captured response. An adapter should handle changing tokens at run time. For a one-off UI task, complete it directly; there is no need to reverse-engineer every endpoint.
|
|
23
|
+
9. **Dialogs:** a native `alert`/`confirm`/`prompt` freezes the page (`dialog_open`, details in `error.dialog`). Read
|
|
24
|
+
with `tab.dialog.get()` and answer `tab.dialog.accept(text?)` / `tab.dialog.dismiss()` (in `js`), then retry — never
|
|
25
|
+
answer a dialog the user didn't ask you to.
|
|
26
|
+
10. **Observe discipline:** one observe to orient, then act on its refs. The snapshot is the action map, not the
|
|
27
|
+
document — read an article, doc, or chat log with `tab.read` (linear text, no refs; scroll is restored). If it returns
|
|
28
|
+
`nextStart`, pass it with `readId` as `start` and `readId` to continue that same capture. `reason:"unbounded"` means a growing feed stopped the scan; `scan_limit` means the scan ended before the page did. Observations are compact semantic trees, not full HTML. `observe()` pages the captured state across the main document and child frames within one output budget. When `nextCursor` is present, use `await tab.observe({cursor: result.nextCursor})` to continue the **same capture**; `complete` means the last output page, while `framesComplete` separately reports frame capture coverage. A fresh state observation replaces the previous cursor; release clears it. `metadataTruncated` marks abbreviated URL/title/frame metadata. Page changes do not rewrite captured pages: observe afresh before acting on potentially stale refs. `stateContinued` / `stateContinues` mark the rare single text line too large for one page; concatenate those fragments before interpreting it. Keep previous pages in a REPL variable when needed instead of returning them all at once.
|
|
29
|
+
Use `{ref:"..."}` to focus a branch, or `{target:{role:"dialog", name:"Settings"}}` / `{target:{selector:"#main"}}` to scope directly. Scoped observations exclude unrelated controls and frames. DOM mode retains `start/limit/nextStart` for requesting more controls from the live page; `nextCursor` only continues the already captured output. Pass `since` only when the preceding snapshot (including relevant pages) is still in your context for an exact diff; otherwise request fresh state. `viewport: true` is the
|
|
30
|
+
on-screen subtree, not a page of the full tree. `click` is a real mouse event and fails with `not_delivered` when
|
|
31
|
+
the page did not receive it, or the element has no box; only then, once, `method:"dom"`. Don't re-verify a fact an authoritative signal already shows
|
|
32
|
+
(checked state, selected option, success toast, URL parameter). No fixed sleeps — `tab.expect` waits for the state
|
|
33
|
+
you need. Credential field values read as `<redacted>`.
|
|
34
|
+
11. **WebMCP:** pages that register their own tools show them in `tab.webmcp.list()` (in `js`); prefer one over clicking
|
|
35
|
+
the DOM, but a page tool never authorizes a consequential action.
|
|
36
|
+
12. **Lookups:** one focused direct navigation to an obvious result or search URL is fine; don't iterate guessed URL
|
|
37
|
+
variants. On localhost apps, reload after a code/build change before verifying, and read `tab.console.read()` for
|
|
38
|
+
errors the page logged.
|
|
39
|
+
13. **Answers:** screenshots the user asked for go inline in your final answer (Markdown image), not as bare links. If
|
|
40
|
+
browser control is interrupted by the user or the extension, say so plainly ("browser use was stopped in Chrome")
|
|
41
|
+
without quoting runtime error text.
|
|
42
|
+
14. **Popup and download outcomes:** If an action returns `openedTabs`, get handles for its `tab` ids with `await browser.tabs.get(id)`; each is a child of the source tab observed while the action ran and already belongs to the session. A `pending:true` child has no page handle yet; call `browser.tabs.list()` and match its numeric `tabId` to obtain the handle when ready. For a download, keep `download.afterSequence` from the action, then call `await tab.download(afterSequence)` on the same tab. A `download.started` entry proves that page began a download, while `downloaded:true` means Chrome reports a completed file whose new start event was paired with the page event by URL. `not_started`, `unconfirmed`, `ambiguous`, and `cursor_expired` do not prove completion. Chrome's download event has no source-tab id, so a file match is reported with `association:"url+event"` rather than as exact provenance.
|
|
43
|
+
|
|
44
|
+
## Choose an observation, then read precisely
|
|
45
|
+
|
|
46
|
+
- Older extensions retain basic main-frame ARIA with a warning; DOM and frame-scoped reads require the new extension capability. Host and extension package versions need not match.
|
|
47
|
+
- `tab.observe()` is the ARIA action map, including child-frame observations. Each frame has its own ref space; never use a child's ref in the parent frame. `since` uses the returned `snapshotId` and diffs each captured frame independently.
|
|
48
|
+
- `tab.observe({format:'dom'})` independently reads visible controls and live attributes, including open shadow roots. It is viewport-scoped by default; `viewport:false` covers rendered controls in the selected document. It does not discover every delegated event handler or unrendered virtual row.
|
|
49
|
+
- DOM `total/start/nextStart` describe a live list per frame. Continue with `observe({format:'dom',frame,start:nextStart})`; page changes can change that list. `truncated:true` on an entry means some preview fields were shortened.
|
|
50
|
+
- `tab.read({target:{ref,frame}})` reads one element's full current text, accessible name, selected attributes and live form state without scrolling. This is the detail path for a clipped DOM preview or long ARIA label. It uses strict locator resolution, just like actions. For document text, `tab.read({frame})` performs the existing bounded scroll-and-read scan; its `readId/start` continuation is tied to that frame.
|
|
51
|
+
- `tab.find({query,frame})` searches DOM text, attributes and current values independently of ARIA. It returns locator candidates; it is not an exhaustive text export. Exact selector/role/label/ref lookup also accepts `frame`.
|
|
52
|
+
- Use `screenshot()` for visual relationships, charts and canvas. A snapshot is not evidence about data not yet rendered. Scroll a virtualized region or inspect an observed network response when the task requires more data.
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
let overview = await tab.observe();
|
|
56
|
+
// Choose a child based on its owner metadata and observed content.
|
|
57
|
+
let billing = overview.frames.find(f => f.owner.name === 'billing');
|
|
58
|
+
let controls = await tab.observe({format:'dom', frame:billing.frame});
|
|
59
|
+
// Choose a ref from that result, then use the same frame path throughout.
|
|
60
|
+
let amount = controls.dom.entries.find(e => e.attrs.placeholder === 'Amount');
|
|
61
|
+
await tab.read({target:{frame:billing.frame, ref:amount.ref}});
|
|
62
|
+
await tab.act({action:'fill', target:{frame:billing.frame, ref:amount.ref}, value:'42'});
|
|
63
|
+
await tab.read({target:{frame:billing.frame, ref:amount.ref}});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Input results
|
|
67
|
+
|
|
68
|
+
`fill` replaces the control's contents; `type` appends text using browser text insertion, not a sequence of key presses. Use `press` for individual keys and shortcuts. Native date/color/range controls and `select` use their control setters and report `method:"dom"`.
|
|
69
|
+
|
|
70
|
+
For `fill` and `type`, `filled:true` and `controlState:"verified"` mean the value matched after settling. If the page formats, rejects, or resets the input during settling, the result is `delivery:"dispatched"`, `filled:false`, `controlState:"unverified"`, with `actual` when the original control is still readable. An unavailable/replaced control is also unverified. Inspect the result before continuing; use `tab.expect` for application-specific success. The engine does not overwrite the page's result with a DOM fallback. `settleMs:0` requests an immediate check only.
|
|
71
|
+
|
|
72
|
+
Failure to focus a targeted control returns an error before sending input. Target `body` or `html` explicitly when a key should go to the page's current focus.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
## Capability: cdp
|
|
2
|
+
|
|
3
|
+
Use `await tab.cdp.send(method, params, target?)` on an explicit Tab. Native CDP method names and parameters pass through unchanged. `target:{frameId}` selects a frame target from `tab.frames()`; routing is separate from protocol parameters. Chrome decides method availability. Browser-wide and arbitrary extension/worker targets are not exposed.
|
|
4
|
+
|
|
5
|
+
The connection is shared with the runtime. `Runtime.disable`, `Page.disable`, `Network.disable`, `Target.setAutoAttach` and `Target.detachFromTarget` conflict with its internal observers and return `runtime_state_conflict`. Other methods are not restricted to a feature allowlist. State-changing calls are never automatically replayed.
|
|
6
|
+
|
|
7
|
+
`let events = await tab.cdp.watch('Network.requestWillBeSent')` registers a root-target listener before returning. Enable any required CDP domain with `tab.cdp.send`, then perform the action and `await events.read()`. Finish with `await events.close()`. Child-session events are not mixed in. See `capabilities/chrome` for cursor, loss and subscription lifecycle semantics.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
## Native browser capabilities
|
|
2
|
+
|
|
3
|
+
`js` is the host Node REPL. `browser.chrome` runs Chrome APIs in this extension's service worker. `tab.evaluate` runs JavaScript in page Main World. `tab.cdp` controls one explicit Tab's shared debugger. No imports or repository files are required.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
let tabs = await browser.chrome.call('tabs.query', [{}]);
|
|
7
|
+
let counts = {};
|
|
8
|
+
for (let t of tabs) counts[t.windowId] = (counts[t.windowId] ?? 0) + 1;
|
|
9
|
+
nodeRepl.write({total: tabs.length, byWindow: counts});
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`call(method, argsArray)` takes native positional JSON arguments and returns native data (`null` for no return value). Preserve large results in REPL bindings. Queries do not claim tabs or attach the debugger. `await browser.chrome.describe('tabs.query')` gives signatures generated from pinned `@types/chrome`, parameter fields, official documentation links, declared/granted permissions and runtime member presence. Presence is not proof a call will succeed: Chrome enforces actual permissions, context and arguments. Methods missing from the local reference can still be called. Callback-only methods in the reference are invoked once through an adapter; unknown callback-only APIs, functions, Ports and synchronous-response events are outside this JSON interface. Use `tab.evaluate` for page functions and `tab.cdp` for debugger operations.
|
|
13
|
+
|
|
14
|
+
Tabs created by `tabs.create`, `tabs.duplicate` and `windows.create` belong to this session. Their original Chrome IDs work with `await browser.tabs.get(String(created.id))`. Moving an existing tab into a window does not adopt it. Popups observed from a claimed tab during a Main World script or CDP command also enter its session. Raw calls preserve explicit focus/mute/window/group settings. Finalize closes agent-created tabs unless kept; claimed user tabs are released. Chrome methods can act directly on existing numeric tab IDs without claiming them.
|
|
15
|
+
|
|
16
|
+
### Organize tabs and groups
|
|
17
|
+
|
|
18
|
+
Use native numeric `tab.id`, `group.id`, and `windowId` from query results, not session handles. These operations do not require claiming tabs or observing pages. Keep full inventories in REPL variables and return only the summary needed for the next decision.
|
|
19
|
+
|
|
20
|
+
| Intent | Native call |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| List groups / read one | `tabGroups.query({})` / `tabGroups.get(groupId)` |
|
|
23
|
+
| Read group members | `tabs.query({groupId})` |
|
|
24
|
+
| Create a group / add members | `tabs.group({tabIds})` / `tabs.group({groupId, tabIds})` |
|
|
25
|
+
| Rename, recolor, collapse or expand | `tabGroups.update(groupId, {title, color, collapsed})` |
|
|
26
|
+
| Move a group | `tabGroups.move(groupId, {index, windowId})` |
|
|
27
|
+
| Dissolve a group, keeping tabs | Query members, then `tabs.ungroup(tabIds)` |
|
|
28
|
+
| Close a group's tabs | Query members, then `tabs.remove(tabIds)` |
|
|
29
|
+
|
|
30
|
+
There is no `tabGroups.create` or `tabGroups.remove`. Group existing tabs by `windowId` before grouping unless a window transfer is intended. For moves, omit `windowId` to reorder locally; use `index: -1` for the end of the window. Chrome only supports group transfers between normal windows. Saved-group reopening, saving and sharing are not exposed by these methods; a readable `shared` property is not a sharing operation.
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
let selectedTabs = await browser.chrome.call('tabs.query', [{windowId, url: 'https://docs.example.com/*'}]);
|
|
34
|
+
let tabIds = selectedTabs.map(t => t.id);
|
|
35
|
+
// windowId is from a prior query; only proceed with a non-empty selection.
|
|
36
|
+
let groupId = await browser.chrome.call('tabs.group', [{tabIds}]);
|
|
37
|
+
await browser.chrome.call('tabGroups.update', [groupId, {title: 'Research', color: 'blue'}]);
|
|
38
|
+
await browser.chrome.call('tabGroups.get', [groupId]);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Each call is a separate operation: if updating the title fails after creation, `groupId` still identifies the created group. Inspect it and retry the failed step; do not recreate the group or claim the entire task succeeded. `describe` includes `resultFields` for object results (or array items), alongside parameter fields.
|
|
42
|
+
|
|
43
|
+
Session groups are temporary workspaces. Successfully updating/moving a group, or explicitly grouping tabs into it, relinquishes any session's automatic management of that group: `nameSession` and subsequent new tabs will not change it. Release only ungroups tabs still in a managed workspace; user-arranged groups remain intact. This does **not** change tab ownership: agent-created tabs still need `release()` or a finalize `keep` entry to survive cleanup. Existing user tabs do not need a keep entry. Grouping, pinning and moving do not change the mute policy. Raw-created tabs keep their native mute state; on session-created tabs only an explicit `tabs.update` with `muted` overrides automatic unmuting.
|
|
44
|
+
|
|
45
|
+
### Events and logs
|
|
46
|
+
|
|
47
|
+
```js
|
|
48
|
+
let events = await browser.chrome.watch('tabs.onUpdated', {capacity: 500});
|
|
49
|
+
// listener is registered; now perform the operation
|
|
50
|
+
let result = await events.read({limit: 30});
|
|
51
|
+
await events.close();
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`watch(event, {capacity, args})` accepts optional Chrome addListener filter arguments after the listener. Notification events only: no response callback, Port or blocking listener. CDP event subscriptions use `tab.cdp.watch`; independent page console capture uses `tab.console.watch()`, and extension-log capture uses `browser.logs.watch()`. These handles share `read({cursor?,limit?,levels?,filter?})` and `close()`. A handle remembers its cursor; an explicit cursor can reread retained history. Filtering advances past nonmatching records. Start watching before the action; historical events cannot be recovered.
|
|
55
|
+
|
|
56
|
+
Results include `entries`, opaque `cursor`, `hasMore`, `dropped`, and `reset`. `dropped` counts lost raw records, not lost filter matches. Entries over the payload budget include `truncated:true`. Buffers are bounded by count and size. `closed/reason` signals a detached target or a lost subscription. A service-worker restart loses buffers/subscriptions: a missing subscription reports reset/closed and must be recreated. This is not durable logging.
|
|
57
|
+
|
|
58
|
+
`tab.console.read(options)` reads the automatic console buffer captured while attached. `browser.logs.read(options)` reads this extension's own service-worker logs, not arbitrary other extensions. Pass returned cursors explicitly for these direct reads. A generation change reports `reset:true`.
|
|
59
|
+
|
|
60
|
+
Explicit subscriptions survive ordinary MCP calls, but close on `close()`, `js_reset`, REPL termination or session finalization. Reset waits for already dispatched work before removing its subscriptions; inspect `doctor.javascript` for draining work or `cleanupError` if cleanup failed. Automatic console capture remains owned by the debugger runtime.
|