dsh-browser-cdp 0.0.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +279 -9
  3. package/THIRD_PARTY_NOTICES.md +62 -0
  4. package/bin/cdp-cast-worker.mjs +6960 -0
  5. package/bin/cdp-chrome-wrapper.sh +53 -0
  6. package/bin/cdp-render-worker.mjs +610 -0
  7. package/bin/record-normalize.d.mts +32 -0
  8. package/bin/record-normalize.mjs +156 -0
  9. package/cordis.patch.yml +17 -0
  10. package/dsh-plugin.json +148 -0
  11. package/lib/client.js +3235 -0
  12. package/lib/index.js +8865 -0
  13. package/lib/launcher-CQyI8-By.js +3 -0
  14. package/lib/launcher-DBaxfIsF.js +269 -0
  15. package/package.json +89 -14
  16. package/runtime/PATCHES.md +30 -0
  17. package/runtime/ego-browser/dist/out/index.js +7206 -0
  18. package/runtime/ego-browser/screenshot-clip.d.mts +22 -0
  19. package/runtime/ego-browser/screenshot-clip.mjs +45 -0
  20. package/runtime/ego-linux/bin/ego-browser.mjs +399 -0
  21. package/runtime/ego-linux/src/agent-identity.mjs +65 -0
  22. package/runtime/ego-linux/src/chrome.mjs +867 -0
  23. package/runtime/ego-linux/src/cursor.mjs +1292 -0
  24. package/runtime/ego-linux/src/desktop.mjs +73 -0
  25. package/runtime/ego-linux/src/paths.mjs +35 -0
  26. package/runtime/ego-linux/src/session.mjs +37 -0
  27. package/runtime/ego-linux/src/shim.mjs +145 -0
  28. package/runtime/ego-linux/src/snapshot.mjs +424 -0
  29. package/runtime/ego-linux/src/spaces-server.mjs +355 -0
  30. package/runtime/ego-linux/src/spaces-ui.mjs +456 -0
  31. package/runtime/ego-linux/src/tabs.mjs +109 -0
  32. package/runtime/ego-linux/src/task-spaces.mjs +671 -0
  33. package/runtime/ego-linux/src/transport.mjs +321 -0
  34. package/runtime/ego-linux/src/window-fit.mjs +107 -0
  35. package/runtime/skills/ego-browser/SKILL.md +209 -0
  36. package/runtime/skills/ego-browser/agents/openai.yaml +7 -0
  37. package/runtime/skills/ego-browser/assets/composer-icon.png +0 -0
  38. package/runtime/skills/ego-browser/assets/logo.png +0 -0
  39. package/runtime/skills/ego-browser/learnings/google/browser-tools/autocomplete.js +11 -0
  40. package/runtime/skills/ego-browser/learnings/google/manifest.json +40 -0
  41. package/runtime/skills/ego-browser/learnings/google/notes/overview.md +23 -0
  42. package/runtime/skills/ego-browser/learnings/google/tools/search-extract.js +35 -0
  43. package/runtime/skills/ego-browser/learnings/x-com/browser-tools/extract-post.js +9 -0
  44. package/runtime/skills/ego-browser/learnings/x-com/manifest.json +51 -0
  45. package/runtime/skills/ego-browser/learnings/x-com/notes/overview.md +18 -0
  46. package/runtime/skills/ego-browser/learnings/x-com/notes/timeline.md +19 -0
  47. package/runtime/skills/ego-browser/learnings/x-com/tools/search-users.js +33 -0
  48. package/runtime/skills/ego-browser/learnings/x-com/tools/timeline.js +32 -0
  49. package/runtime/skills/ego-browser/references/install.md +131 -0
  50. package/runtime/skills/ego-browser/references/task-spaces.md +122 -0
  51. package/runtime/skills/ego-browser/references/video.md +17 -0
  52. package/runtime/skills/ego-browser/scripts/install.sh +309 -0
  53. package/index.js +0 -11
@@ -0,0 +1,424 @@
1
+ import { createSessionResolver } from "./session.mjs";
2
+
3
+ /**
4
+ * snapshot() — the semantic page view the agent reads.
5
+ *
6
+ * Contract (package/ego-browser/src/driver/observe.ts + browser-runtime.ts:309):
7
+ * snapshot(options) -> { content: string, refs: [{ backendNodeId, role, name }] }
8
+ *
9
+ * `refs` is the load-bearing half: browserSnapshotRefsToRefMap() keys the ref map
10
+ * by String(backendNodeId), which is exactly what `@N` / `ref=N` resolve against.
11
+ * CDP hands out backendNodeIds directly, so refs are reproduced faithfully.
12
+ *
13
+ * `content` is rebuilt rather than reproduced — the native snapshot is closed
14
+ * source. One DOMSnapshot.captureSnapshot call returns every document (iframes
15
+ * included, nested to any depth), each node's backendNodeId and attributes, and
16
+ * the layout tree. That covers hierarchy, visibility and iframe piercing in a
17
+ * single round trip; roles and accessible names are computed here.
18
+ */
19
+
20
+ const SKIP_TAGS = new Set([
21
+ "script", "style", "noscript", "head", "meta", "link", "title", "template", "br",
22
+ ]);
23
+
24
+ const ROLE_BY_TAG = new Map(Object.entries({
25
+ a: "link", button: "button", select: "combobox", textarea: "textbox",
26
+ h1: "heading", h2: "heading", h3: "heading", h4: "heading", h5: "heading", h6: "heading",
27
+ img: "img", nav: "navigation", main: "main", header: "banner", footer: "contentinfo",
28
+ form: "form", ul: "list", ol: "list", li: "listitem", table: "table", tr: "row",
29
+ td: "cell", th: "columnheader", dialog: "dialog", option: "option", summary: "button",
30
+ details: "group", label: "label", fieldset: "group", legend: "legend", article: "article",
31
+ section: "region", aside: "complementary", iframe: "iframe", video: "video", audio: "audio",
32
+ }));
33
+
34
+ const INPUT_TYPE_ROLE = new Map(Object.entries({
35
+ button: "button", submit: "button", reset: "button", image: "button",
36
+ checkbox: "checkbox", radio: "radio", range: "slider", file: "file-input",
37
+ hidden: "hidden",
38
+ }));
39
+
40
+ /** Roles worth handing the agent a ref for. */
41
+ const INTERACTIVE_ROLES = new Set([
42
+ "link", "button", "textbox", "checkbox", "radio", "combobox", "option", "slider",
43
+ "tab", "menuitem", "menuitemcheckbox", "menuitemradio", "switch", "searchbox",
44
+ "file-input", "spinbutton",
45
+ ]);
46
+
47
+ /**
48
+ * Roles whose accessible name comes from their own text content (ARIA's
49
+ * "name from content"). Everything else — main, nav, form, region, list — is a
50
+ * container: naming it would swallow the whole page into one string, and taking
51
+ * that name as final would stop the walk before any child ever gets a ref.
52
+ */
53
+ const NAME_FROM_CONTENT = new Set([
54
+ "button", "link", "heading", "option", "tab", "menuitem", "menuitemcheckbox",
55
+ "menuitemradio", "label", "legend", "switch",
56
+ ]);
57
+
58
+ /** Roles that carry structure worth printing even without a ref. */
59
+ const STRUCTURAL_ROLES = new Set([
60
+ "heading", "list", "listitem", "table", "row", "cell", "columnheader", "navigation",
61
+ "main", "banner", "contentinfo", "form", "dialog", "article", "region", "complementary",
62
+ "img", "label", "legend", "group", "iframe", "video", "audio",
63
+ ]);
64
+
65
+ const MAX_NAME = 120;
66
+ const MAX_TEXT = 200;
67
+
68
+ function squash(value, limit = MAX_TEXT) {
69
+ const text = String(value ?? "").replace(/\s+/g, " ").trim();
70
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
71
+ }
72
+
73
+ /** RareBooleanData -> Set of node indices that are true. */
74
+ function rareBooleanSet(rare) {
75
+ return new Set(rare?.index || []);
76
+ }
77
+
78
+ /** RareIntegerData / RareStringData -> Map of node index -> value. */
79
+ function rareMap(rare) {
80
+ const map = new Map();
81
+ const index = rare?.index || [];
82
+ const value = rare?.value || [];
83
+ for (let i = 0; i < index.length; i += 1) map.set(index[i], value[i]);
84
+ return map;
85
+ }
86
+
87
+ function cssEscapeIdent(value) {
88
+ return String(value).replace(/([^\w-])/g, "\\$1");
89
+ }
90
+
91
+ /** A document's nodes, decoded from the string table into a usable shape. */
92
+ function decodeDocument(document, strings) {
93
+ const nodes = document.nodes;
94
+ const count = nodes.nodeName?.length || 0;
95
+ const str = (index) => (index === undefined || index < 0 ? "" : strings[index] || "");
96
+
97
+ const contentDocumentIndex = rareMap(nodes.contentDocumentIndex);
98
+ const clickable = rareBooleanSet(nodes.isClickable);
99
+ const inputValue = rareMap(nodes.inputValue);
100
+ const inputChecked = rareBooleanSet(nodes.inputChecked);
101
+
102
+ const layoutBounds = new Map();
103
+ const layoutText = new Map();
104
+ const layout = document.layout || {};
105
+ for (let i = 0; i < (layout.nodeIndex || []).length; i += 1) {
106
+ const nodeIndex = layout.nodeIndex[i];
107
+ layoutBounds.set(nodeIndex, layout.bounds?.[i]);
108
+ const text = str(layout.text?.[i]);
109
+ if (text) layoutText.set(nodeIndex, text);
110
+ }
111
+
112
+ const decoded = [];
113
+ const children = new Map();
114
+ const byId = new Map();
115
+
116
+ for (let i = 0; i < count; i += 1) {
117
+ const attributes = {};
118
+ const flat = nodes.attributes?.[i] || [];
119
+ for (let a = 0; a + 1 < flat.length; a += 2) {
120
+ attributes[str(flat[a]).toLowerCase()] = str(flat[a + 1]);
121
+ }
122
+ const node = {
123
+ index: i,
124
+ parent: nodes.parentIndex?.[i] ?? -1,
125
+ nodeType: nodes.nodeType?.[i],
126
+ tag: str(nodes.nodeName?.[i]).toLowerCase(),
127
+ value: str(nodes.nodeValue?.[i]),
128
+ backendNodeId: nodes.backendNodeId?.[i],
129
+ attributes,
130
+ bounds: layoutBounds.get(i),
131
+ text: layoutText.get(i),
132
+ clickable: clickable.has(i),
133
+ inputValue: inputValue.has(i) ? str(inputValue.get(i)) : undefined,
134
+ inputChecked: inputChecked.has(i),
135
+ contentDocumentIndex: contentDocumentIndex.get(i),
136
+ };
137
+ decoded.push(node);
138
+ if (node.parent >= 0) {
139
+ if (!children.has(node.parent)) children.set(node.parent, []);
140
+ children.get(node.parent).push(i);
141
+ }
142
+ if (node.attributes.id) byId.set(node.attributes.id, node);
143
+ }
144
+
145
+ return {
146
+ nodes: decoded,
147
+ children,
148
+ byId,
149
+ scrollX: document.scrollOffsetX || 0,
150
+ scrollY: document.scrollOffsetY || 0,
151
+ url: str(document.documentURL),
152
+ };
153
+ }
154
+
155
+ function roleOf(node) {
156
+ const explicit = node.attributes.role;
157
+ if (explicit) return explicit.trim().split(/\s+/)[0];
158
+ if (node.tag === "input") {
159
+ const type = (node.attributes.type || "text").toLowerCase();
160
+ if (INPUT_TYPE_ROLE.has(type)) return INPUT_TYPE_ROLE.get(type);
161
+ if (type === "search") return "searchbox";
162
+ if (type === "number") return "spinbutton";
163
+ return "textbox";
164
+ }
165
+ if (node.tag === "a") return node.attributes.href !== undefined ? "link" : "generic";
166
+ if (node.attributes.contenteditable === "" || node.attributes.contenteditable === "true") {
167
+ return "textbox";
168
+ }
169
+ return ROLE_BY_TAG.get(node.tag) || "generic";
170
+ }
171
+
172
+ /** Visible text of a subtree, used as the fallback accessible name. */
173
+ function subtreeText(doc, index, budget = MAX_NAME) {
174
+ const parts = [];
175
+ const walk = (current) => {
176
+ if (parts.join(" ").length > budget) return;
177
+ const node = doc.nodes[current];
178
+ if (!node) return;
179
+ if (node.nodeType === 3) {
180
+ const text = node.text || node.value;
181
+ if (text && text.trim()) parts.push(text.trim());
182
+ return;
183
+ }
184
+ if (SKIP_TAGS.has(node.tag)) return;
185
+ for (const child of doc.children.get(current) || []) walk(child);
186
+ };
187
+ walk(index);
188
+ return squash(parts.join(" "), budget);
189
+ }
190
+
191
+ function accessibleName(doc, node, role) {
192
+ const attrs = node.attributes;
193
+ if (attrs["aria-label"]) return squash(attrs["aria-label"], MAX_NAME);
194
+ if (attrs["aria-labelledby"]) {
195
+ const labels = attrs["aria-labelledby"]
196
+ .split(/\s+/)
197
+ .map((id) => doc.byId.get(id))
198
+ .filter(Boolean)
199
+ .map((target) => subtreeText(doc, target.index));
200
+ if (labels.length) return squash(labels.join(" "), MAX_NAME);
201
+ }
202
+ if (node.tag === "img") return squash(attrs.alt || "", MAX_NAME);
203
+ if (node.tag === "input" || node.tag === "textarea" || node.tag === "select") {
204
+ if (attrs.id) {
205
+ for (const candidate of doc.nodes) {
206
+ if (candidate.tag === "label" && candidate.attributes.for === attrs.id) {
207
+ return subtreeText(doc, candidate.index);
208
+ }
209
+ }
210
+ }
211
+ // A wrapping <label> is the other half of the native label association.
212
+ let parent = node.parent;
213
+ while (parent >= 0) {
214
+ const ancestor = doc.nodes[parent];
215
+ if (!ancestor) break;
216
+ if (ancestor.tag === "label") return subtreeText(doc, ancestor.index);
217
+ parent = ancestor.parent;
218
+ }
219
+ return squash(attrs.placeholder || attrs.title || attrs.name || "", MAX_NAME);
220
+ }
221
+ if (role === "iframe") return squash(attrs.title || attrs.name || "", MAX_NAME);
222
+ if (NAME_FROM_CONTENT.has(role)) return subtreeText(doc, node.index);
223
+ // Containers are named only by an explicit label, never by their contents.
224
+ return squash(attrs.title || "", MAX_NAME);
225
+ }
226
+
227
+ /** Most stable `loc=` the resolver (locator-query.ts) can re-find this node by. */
228
+ function stableLocator(node, role, name) {
229
+ const attrs = node.attributes;
230
+ if (attrs["data-testid"]) return `testid:${attrs["data-testid"]}`;
231
+ if (attrs.id && /^[A-Za-z][\w-]*$/.test(attrs.id)) return `css:#${cssEscapeIdent(attrs.id)}`;
232
+ if (role === "link" && attrs.href) return `href:${attrs.href}`;
233
+ if (attrs.placeholder) return `placeholder:${attrs.placeholder}`;
234
+ if (attrs["data-test"]) return `css:[data-test="${attrs["data-test"]}"]`;
235
+ if (name && INTERACTIVE_ROLES.has(role)) return `role:${role}[name='${name.replace(/'/g, "\\'")}']`;
236
+ if (attrs.name) return `css:${node.tag}[name="${attrs.name}"]`;
237
+ return null;
238
+ }
239
+
240
+ function intersectsViewport(bounds, viewport) {
241
+ if (!bounds || !viewport) return true;
242
+ const [x, y, width, height] = bounds;
243
+ return (
244
+ x + width >= viewport.x &&
245
+ y + height >= viewport.y &&
246
+ x <= viewport.x + viewport.width &&
247
+ y <= viewport.y + viewport.height
248
+ );
249
+ }
250
+
251
+ function renderDocument(doc, documents, options, out, refs, depth, seenDocs) {
252
+ const { viewport, includeActionMarks, includeStableLocator } = options;
253
+
254
+ const emit = (indent, line) => out.push(`${" ".repeat(indent)}${line}`);
255
+
256
+ const walk = (index, indent) => {
257
+ const node = doc.nodes[index];
258
+ if (!node) return;
259
+
260
+ if (node.nodeType === 3) {
261
+ const text = squash(node.text || node.value);
262
+ // Text only counts as rendered when it made it into the layout tree, and
263
+ // it answers to the same viewport scope as an element does. Skipping this
264
+ // check meant `only_within_viewport` still emitted every paragraph below
265
+ // the fold — on a text-heavy page that is most of the content, which is
266
+ // why scoping the view saved so much less than it looked like it should.
267
+ if (
268
+ text &&
269
+ node.text !== undefined &&
270
+ intersectsViewport(node.bounds, viewport)
271
+ ) {
272
+ emit(indent, `text: ${text}`);
273
+ }
274
+ return;
275
+ }
276
+ if (node.nodeType !== 1) {
277
+ for (const child of doc.children.get(index) || []) walk(child, indent);
278
+ return;
279
+ }
280
+ if (SKIP_TAGS.has(node.tag)) return;
281
+ if (node.attributes["aria-hidden"] === "true") return;
282
+
283
+ const role = roleOf(node);
284
+ if (role === "hidden") return;
285
+
286
+ const rendered = node.bounds && node.bounds[2] > 0 && node.bounds[3] > 0;
287
+ const inScope = rendered && intersectsViewport(node.bounds, viewport);
288
+
289
+ // An iframe is a document boundary: recurse into its content document so
290
+ // nested frames appear inline in one tree.
291
+ if (node.contentDocumentIndex !== undefined) {
292
+ const childDoc = documents[node.contentDocumentIndex];
293
+ if (childDoc && !seenDocs.has(node.contentDocumentIndex)) {
294
+ seenDocs.add(node.contentDocumentIndex);
295
+ const name = accessibleName(doc, node, role);
296
+ emit(indent, `iframe${name ? ` "${name}"` : ""} [url=${childDoc.url}]`);
297
+ renderDocument(childDoc, documents, options, out, refs, indent + 1, seenDocs);
298
+ return;
299
+ }
300
+ }
301
+
302
+ const interactive =
303
+ INTERACTIVE_ROLES.has(role) ||
304
+ node.clickable ||
305
+ node.attributes.onclick !== undefined ||
306
+ node.attributes.tabindex !== undefined;
307
+
308
+ const shouldEmit =
309
+ inScope && (interactive || STRUCTURAL_ROLES.has(role));
310
+ const addressable = interactive && node.backendNodeId !== undefined;
311
+
312
+ // Being addressable is a different question from being on screen. An
313
+ // interactive node joins the refMap wherever it sits, so `@N` still
314
+ // resolves for something below the fold; only the rendered line stays
315
+ // viewport-scoped. Tying the two together is what made
316
+ // `scope: only_within_viewport` hand back "Unknown ref" for everything it
317
+ // had scrolled past, forcing a choice between a cheap snapshot and usable
318
+ // refs. The extra work is one bounded accessible-name walk per off-screen
319
+ // interactive node, over a document that is already decoded in memory —
320
+ // no additional CDP round trip, and full_page is unaffected because every
321
+ // node is in scope there anyway.
322
+ const name =
323
+ shouldEmit || addressable ? accessibleName(doc, node, role) : "";
324
+ if (addressable) {
325
+ refs.push({ backendNodeId: node.backendNodeId, role, name });
326
+ }
327
+
328
+ if (shouldEmit) {
329
+ const marks = [];
330
+
331
+ if (addressable) {
332
+ marks.push(`ref=${node.backendNodeId}`);
333
+ }
334
+ if (includeStableLocator) {
335
+ const locator = stableLocator(node, role, name);
336
+ if (locator) marks.push(`loc=${locator}`);
337
+ }
338
+ if (role === "link" && node.attributes.href) marks.push(`url=${node.attributes.href}`);
339
+ if (includeActionMarks && interactive) {
340
+ marks.push(role === "textbox" || role === "searchbox" ? "action=type" : "action=click");
341
+ }
342
+ if (node.inputValue) marks.push(`value=${squash(node.inputValue, 40)}`);
343
+ if (node.inputChecked) marks.push("checked");
344
+ if (node.attributes.disabled !== undefined) marks.push("disabled");
345
+
346
+ const heading = node.tag.match(/^h([1-6])$/);
347
+ const label = heading ? `heading${heading[1]}` : role;
348
+ const suffix = marks.length ? ` [${marks.join(", ")}]` : "";
349
+ emit(indent, `${label}${name ? ` "${name}"` : ""}${suffix}`);
350
+
351
+ // A name-from-content node has already printed its whole subtree as its
352
+ // name; recursing would repeat it. Containers must never take this path —
353
+ // their children are where the refs live.
354
+ if (name && NAME_FROM_CONTENT.has(role) && subtreeText(doc, index) === name) {
355
+ return;
356
+ }
357
+ }
358
+
359
+ const nextIndent = shouldEmit ? indent + 1 : indent;
360
+ for (const child of doc.children.get(index) || []) walk(child, nextIndent);
361
+ };
362
+
363
+ walk(0, depth);
364
+ }
365
+
366
+ export function createSnapshotApi(cdp, { listTabs }) {
367
+ // Snapshot whatever page the harness is actually driving: observation and
368
+ // action drifting apart reads as an empty snapshot. See session.mjs.
369
+ const sessionForActiveTab = createSessionResolver(cdp, {
370
+ listTabs,
371
+ op: "snapshot",
372
+ });
373
+
374
+ return {
375
+ async snapshot(options = {}) {
376
+ const sessionId = await sessionForActiveTab();
377
+ const scope = options.scope ?? "full_page";
378
+
379
+ let viewport = null;
380
+ if (scope === "only_within_viewport") {
381
+ const metrics = await cdp.call("Page.getLayoutMetrics", {}, sessionId);
382
+ const visual = metrics.cssVisualViewport || metrics.visualViewport;
383
+ if (visual) {
384
+ viewport = {
385
+ x: visual.pageX ?? 0,
386
+ y: visual.pageY ?? 0,
387
+ width: visual.clientWidth ?? 0,
388
+ height: visual.clientHeight ?? 0,
389
+ };
390
+ }
391
+ }
392
+
393
+ const captured = await cdp.call(
394
+ "DOMSnapshot.captureSnapshot",
395
+ { computedStyles: [], includeDOMRects: false, includePaintOrder: false },
396
+ sessionId,
397
+ );
398
+
399
+ const strings = captured.strings || [];
400
+ const documents = (captured.documents || []).map((document) =>
401
+ decodeDocument(document, strings),
402
+ );
403
+ if (!documents.length) return { content: "", refs: [] };
404
+
405
+ const out = [];
406
+ const refs = [];
407
+ renderDocument(
408
+ documents[0],
409
+ documents,
410
+ {
411
+ viewport,
412
+ includeActionMarks: options.includeActionMarks ?? true,
413
+ includeStableLocator: options.includeStableLocator ?? true,
414
+ },
415
+ out,
416
+ refs,
417
+ 0,
418
+ new Set([0]),
419
+ );
420
+
421
+ return { content: out.join("\n"), refs };
422
+ },
423
+ };
424
+ }