dsh-browser-cdp 0.0.1 → 0.17.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 (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 +90 -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,355 @@
1
+ import { createServer } from "node:http";
2
+
3
+ import { CURSOR_PROBE_EXPRESSION } from "./cursor.mjs";
4
+ import { SPACES_HTML } from "./spaces-ui.mjs";
5
+
6
+ /**
7
+ * The Spaces overview.
8
+ *
9
+ * Upstream draws this inside the browser's own chrome, which a Chromium fork can
10
+ * do and a stock Chromium cannot: Chrome 137 removed --load-extension, and the
11
+ * CDP Extensions domain reports "Method not available", so nothing can inject UI
12
+ * into the tab strip from outside. What is reachable is an --app window: no tab
13
+ * strip, no toolbar, its own app_id — a standalone panel that behaves like part
14
+ * of the browser.
15
+ *
16
+ * The server is the only source of truth's front door: it reads and writes the
17
+ * same task-space state file the CLI uses, so the overview and the agent never
18
+ * disagree about which spaces exist.
19
+ */
20
+
21
+ const THUMBNAIL = {
22
+ format: "jpeg",
23
+ quality: 60,
24
+ };
25
+
26
+ /** How long after its last pointer event a space still counts as being worked in. */
27
+ const ACTIVE_WINDOW_MS = 30_000;
28
+
29
+ /** The crop used while an agent is active. Matches the card's 16/10 frame. */
30
+ const FOLLOW = { width: 760, aspect: 16 / 10 };
31
+
32
+ function clamp(value, low, high) {
33
+ return Math.max(low, Math.min(high, value));
34
+ }
35
+
36
+ /** Where the agent's cursor is in this page, or null if none has acted here. */
37
+ async function readCursor(cdp, sessionId) {
38
+ try {
39
+ const { result } = await cdp.call(
40
+ "Runtime.evaluate",
41
+ { expression: CURSOR_PROBE_EXPRESSION, returnByValue: true },
42
+ sessionId,
43
+ );
44
+ return result?.value ?? null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * A crop centred on the cursor, clamped to the visible viewport.
52
+ *
53
+ * A full-page thumbnail scaled into a ~294px card renders the cursor about five
54
+ * pixels wide, which reads as "nothing is happening" even while the agent is
55
+ * clicking. Cropping to where it is working makes the activity legible; the
56
+ * clamp keeps the rect inside what captureBeyondViewport:false actually paints.
57
+ */
58
+ function followClip(cursor) {
59
+ const width = Math.min(FOLLOW.width, cursor.viewportWidth);
60
+ const height = Math.min(width / FOLLOW.aspect, cursor.viewportHeight);
61
+ const left = clamp(cursor.x - width / 2, 0, cursor.viewportWidth - width);
62
+ const top = clamp(cursor.y - height / 2, 0, cursor.viewportHeight - height);
63
+ // The overlay is viewport-fixed; the clip is in page coordinates.
64
+ return {
65
+ x: left + cursor.scrollX,
66
+ y: top + cursor.scrollY,
67
+ width,
68
+ height,
69
+ scale: 1,
70
+ };
71
+ }
72
+
73
+ /**
74
+ * Live frames, pushed rather than polled.
75
+ *
76
+ * captureScreenshot per poll cost four CDP round trips per space (attach, read
77
+ * cursor, capture, detach) and could never show more than one frame per poll —
78
+ * an agent's cursor jumped between stills instead of moving. Page.startScreencast
79
+ * inverts it: Chrome sends a frame whenever the page changes, into a cache the
80
+ * request path just reads.
81
+ *
82
+ * The cost is the crop. A screencast frame is the whole viewport, so the
83
+ * cursor-following zoom moves to the client, which has the cursor position
84
+ * anyway — see the transform in spaces-ui.mjs.
85
+ */
86
+ const CAST = { format: "jpeg", quality: 55, maxWidth: 960, maxHeight: 600 };
87
+
88
+ function createCastPool(cdp) {
89
+ const casts = new Map();
90
+ // Opening is async, so two concurrent polls for the same tab would each find
91
+ // no cast and each attach — the loser's session then leaks, attached and
92
+ // acking frames nobody reads.
93
+ const opening = new Map();
94
+ let closed = false;
95
+
96
+ cdp.onShimEvent("Page.screencastFrame", (params, sessionId) => {
97
+ for (const cast of casts.values()) {
98
+ if (cast.sessionId !== sessionId) continue;
99
+ cast.frame = params.data || null;
100
+ cast.seq += 1;
101
+ break;
102
+ }
103
+ // Chrome stops sending frames until each one is acknowledged.
104
+ cdp
105
+ .call("Page.screencastFrameAck", { sessionId: params.sessionId }, sessionId)
106
+ .catch(() => {});
107
+ });
108
+
109
+ async function open(targetId) {
110
+ const { sessionId } = await cdp.call("Target.attachToTarget", {
111
+ targetId,
112
+ flatten: true,
113
+ });
114
+ cdp.claimSession(sessionId);
115
+ if (closed) {
116
+ // The pool was torn down while this attach was in flight. Registering it
117
+ // now would leave a claimed session that nothing will ever detach.
118
+ cdp.releaseSession(sessionId);
119
+ cdp.call("Target.detachFromTarget", { sessionId }).catch(() => {});
120
+ throw new Error("cast pool is closed");
121
+ }
122
+ const cast = { sessionId, frame: null, seq: 0 };
123
+ casts.set(targetId, cast);
124
+ try {
125
+ await cdp.call("Page.startScreencast", { ...CAST, everyNthFrame: 1 }, sessionId);
126
+ } catch (error) {
127
+ // Leaving the entry behind would serve a blank card for as long as the tab
128
+ // lives: every later poll finds it, skips open(), and reads a stream that
129
+ // is not running.
130
+ casts.delete(targetId);
131
+ cdp.releaseSession(sessionId);
132
+ cdp.call("Target.detachFromTarget", { sessionId }).catch(() => {});
133
+ throw error;
134
+ }
135
+ // The first frame only arrives once the page next paints, which on a static
136
+ // page can be never — so prime the cache with one shot rather than show an
137
+ // empty card until something happens to move.
138
+ try {
139
+ const shot = await cdp.call(
140
+ "Page.captureScreenshot",
141
+ { format: CAST.format, quality: CAST.quality, captureBeyondViewport: false },
142
+ sessionId,
143
+ );
144
+ if (shot.data && !cast.frame) cast.frame = shot.data;
145
+ } catch {
146
+ // The stream will fill it in as soon as the page paints.
147
+ }
148
+ return cast;
149
+ }
150
+
151
+ return {
152
+ /** The newest frame for this tab, opening a stream for it on first ask. */
153
+ async frameFor(targetId) {
154
+ const existing = casts.get(targetId);
155
+ if (existing) return existing;
156
+ // Same contract for every caller: a broken stream yields null, never a
157
+ // rejection a caller has to remember to catch.
158
+ const inFlight = opening.get(targetId);
159
+ if (inFlight) return inFlight.catch(() => null);
160
+
161
+ const attempt = open(targetId).finally(() => opening.delete(targetId));
162
+ opening.set(targetId, attempt);
163
+ return attempt.catch(() => null);
164
+ },
165
+
166
+ sessionFor(targetId) {
167
+ return casts.get(targetId)?.sessionId ?? null;
168
+ },
169
+
170
+ /** Tabs that went away take their stream with them. */
171
+ async retain(liveTargetIds) {
172
+ for (const [targetId, cast] of [...casts.entries()]) {
173
+ if (liveTargetIds.has(targetId)) continue;
174
+ casts.delete(targetId);
175
+ cdp.releaseSession(cast.sessionId);
176
+ await cdp.call("Target.detachFromTarget", { sessionId: cast.sessionId }).catch(() => {});
177
+ }
178
+ },
179
+
180
+ closeAll() {
181
+ closed = true;
182
+ // Detach first. Releasing alone stops the shim claiming the session while
183
+ // Chrome is still streaming to it, so every frame in flight is forwarded
184
+ // to the harness — into the buffer drainEvents() hands to agents, which is
185
+ // the exact leak the claim exists to prevent.
186
+ for (const cast of casts.values()) {
187
+ cdp.call("Target.detachFromTarget", { sessionId: cast.sessionId }).catch(() => {});
188
+ cdp.releaseSession(cast.sessionId);
189
+ }
190
+ casts.clear();
191
+ },
192
+ };
193
+ }
194
+
195
+ async function captureCard(cdp, targetId, pool) {
196
+ try {
197
+ const cast = await pool.frameFor(targetId);
198
+ if (!cast) return { thumbnail: null, activity: null, trail: [] };
199
+
200
+ const cursor = await readCursor(cdp, cast.sessionId);
201
+ const active = Boolean(cursor) && cursor.ageMs < ACTIVE_WINDOW_MS;
202
+ return {
203
+ thumbnail: cast.frame ? `data:image/jpeg;base64,${cast.frame}` : null,
204
+ activity: active
205
+ ? {
206
+ name: cursor.name,
207
+ label: cursor.label,
208
+ ageMs: Math.round(cursor.ageMs),
209
+ // Fractions of the viewport, so the card can zoom to the cursor
210
+ // without the server cropping the frame.
211
+ fx: cursor.viewportWidth ? cursor.x / cursor.viewportWidth : null,
212
+ fy: cursor.viewportHeight ? cursor.y / cursor.viewportHeight : null,
213
+ }
214
+ : null,
215
+ trail: cursor?.trail?.slice(-3).reverse() ?? [],
216
+ };
217
+ } catch {
218
+ return { thumbnail: null, activity: null, trail: [] };
219
+ }
220
+ }
221
+
222
+ function json(response, status, body) {
223
+ const payload = JSON.stringify(body);
224
+ response.writeHead(status, {
225
+ "content-type": "application/json",
226
+ "content-length": Buffer.byteLength(payload),
227
+ "cache-control": "no-store",
228
+ });
229
+ response.end(payload);
230
+ }
231
+
232
+ async function readBody(request) {
233
+ const chunks = [];
234
+ for await (const chunk of request) chunks.push(chunk);
235
+ if (chunks.length === 0) return {};
236
+ try {
237
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
238
+ } catch {
239
+ return {};
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Start the overview server.
245
+ * @param {object} shim The live ego shim (ego + cdp).
246
+ * @returns {Promise<{port:number, close:() => void}>}
247
+ */
248
+ export async function startSpacesServer(shim) {
249
+ const { ego, cdp } = shim;
250
+ const pool = createCastPool(cdp);
251
+
252
+ const server = createServer(async (request, response) => {
253
+ // Bound to loopback, but a page in the agent's own browser can still reach
254
+ // it, so only same-origin callers get to act.
255
+ const origin = request.headers.origin;
256
+ if (origin && !origin.startsWith("http://127.0.0.1:")) {
257
+ json(response, 403, { error: "cross-origin request refused" });
258
+ return;
259
+ }
260
+
261
+ const url = new URL(request.url, "http://127.0.0.1");
262
+
263
+ if (request.method === "GET" && url.pathname === "/") {
264
+ const html = SPACES_HTML;
265
+ response.writeHead(200, {
266
+ "content-type": "text/html; charset=utf-8",
267
+ "content-length": Buffer.byteLength(html),
268
+ });
269
+ response.end(html);
270
+ return;
271
+ }
272
+
273
+ if (request.method === "GET" && url.pathname === "/api/health") {
274
+ json(response, 200, { ok: true });
275
+ return;
276
+ }
277
+
278
+ if (request.method === "GET" && url.pathname === "/api/spaces") {
279
+ const { taskSpaces = [] } = await ego.listTaskSpaces();
280
+ // Deliberately NOT ego.listTabs(): that is scoped to the selected space,
281
+ // which is right for an agent (it should only see its own tabs) and wrong
282
+ // for an overview of every space — every non-selected card would report
283
+ // zero tabs, no title and no thumbnail. The panel needs the whole browser.
284
+ const { targetInfos = [] } = await cdp.call("Target.getTargets");
285
+ const byTarget = new Map(
286
+ targetInfos
287
+ .filter((target) => target.type === "page")
288
+ .map((target) => [target.targetId, target]),
289
+ );
290
+
291
+ await pool.retain(new Set(byTarget.keys()));
292
+ const spaces = await Promise.all(
293
+ taskSpaces.map(async (space) => {
294
+ const live = (space.targetIds || []).filter((id) => byTarget.has(id));
295
+ const lead = live[0];
296
+ const card = lead
297
+ ? await captureCard(cdp, lead, pool)
298
+ : { thumbnail: null, activity: null, trail: [] };
299
+ return {
300
+ id: space.id,
301
+ name: space.name,
302
+ ownership: space.ownership,
303
+ profile: space.profile || null,
304
+ session: space.session || null,
305
+ tabCount: live.length,
306
+ title: lead ? byTarget.get(lead).title : "",
307
+ url: lead ? byTarget.get(lead).url : "",
308
+ thumbnail: card.thumbnail,
309
+ activity: card.activity,
310
+ trail: card.trail,
311
+ };
312
+ }),
313
+ );
314
+ json(response, 200, { spaces });
315
+ return;
316
+ }
317
+
318
+ if (request.method === "POST" && url.pathname === "/api/spaces") {
319
+ const { name } = await readBody(request);
320
+ const space = await ego.createTaskSpace(name || "new space");
321
+ json(response, 200, { space });
322
+ return;
323
+ }
324
+
325
+ // takeover / stop are the panel's half of the ownership handshake the
326
+ // native app puts on its Space overlay: stop hands the space back to you
327
+ // (the agent's cursor goes away), takeover claims it for the agent again.
328
+ const match = /^\/api\/spaces\/(\d+)\/(use|close|stop|takeover)$/.exec(url.pathname);
329
+ if (request.method === "POST" && match) {
330
+ const id = Number(match[1]);
331
+ if (match[2] === "use") {
332
+ await ego.useTaskSpace(id);
333
+ } else if (match[2] === "stop") {
334
+ await ego.handOffTaskSpace(id);
335
+ } else if (match[2] === "takeover") {
336
+ await ego.takeOverTaskSpace(id);
337
+ } else {
338
+ await ego.closeTaskSpace(id);
339
+ }
340
+ json(response, 200, { done: true });
341
+ return;
342
+ }
343
+
344
+ json(response, 404, { error: "not found" });
345
+ });
346
+
347
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
348
+ return {
349
+ port: server.address().port,
350
+ close: () => {
351
+ pool.closeAll();
352
+ server.close();
353
+ },
354
+ };
355
+ }