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,456 @@
1
+ /**
2
+ * The Spaces overview page, served by spaces-server.mjs.
3
+ *
4
+ * Kept as a single self-contained string: the page is loaded in an --app window
5
+ * with no toolbar, so there is no navigation to a second file, and inlining
6
+ * avoids a static-file route that would widen the server's surface.
7
+ */
8
+ export const SPACES_HTML = `<!doctype html>
9
+ <html lang="en">
10
+ <head>
11
+ <meta charset="utf-8" />
12
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
13
+ <title>Spaces</title>
14
+ <style>
15
+ :root {
16
+ color-scheme: light dark;
17
+ --bg: #eef1f7;
18
+ --card: #ffffff;
19
+ --line: rgba(15, 18, 25, 0.10);
20
+ --text: #12151c;
21
+ --muted: #6b7280;
22
+ --accent: #2f6df6;
23
+ }
24
+ @media (prefers-color-scheme: dark) {
25
+ :root {
26
+ --bg: #14161b;
27
+ --card: #1c1f26;
28
+ --line: rgba(255, 255, 255, 0.10);
29
+ --text: #eef0f4;
30
+ --muted: #9aa1ad;
31
+ }
32
+ }
33
+ * { box-sizing: border-box; }
34
+ body {
35
+ margin: 0;
36
+ min-height: 100vh;
37
+ padding: 34px 40px 48px;
38
+ background:
39
+ radial-gradient(1200px 460px at 12% -8%, rgba(47, 109, 246, .10), transparent 60%),
40
+ radial-gradient(900px 420px at 92% 4%, rgba(120, 90, 220, .09), transparent 62%),
41
+ var(--bg);
42
+ color: var(--text);
43
+ font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
44
+ -webkit-font-smoothing: antialiased;
45
+ }
46
+ header { display: flex; align-items: baseline; gap: 12px; margin-bottom: 26px; }
47
+ h1 { font-size: 19px; font-weight: 650; margin: 0; letter-spacing: -0.01em; }
48
+ .sub { color: var(--muted); font-size: 13px; }
49
+ .grid {
50
+ display: grid;
51
+ grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
52
+ gap: 30px 26px;
53
+ }
54
+ /* The outer container stacks sections; only each section's body is a grid. */
55
+ .sections { display: block; }
56
+ .section + .section { margin-top: 38px; }
57
+ .section-head {
58
+ display: flex; align-items: baseline; gap: 10px;
59
+ margin-bottom: 14px; padding-bottom: 9px;
60
+ border-bottom: 1px solid var(--line);
61
+ }
62
+ .section-title { font-weight: 620; letter-spacing: -0.005em; }
63
+ .section-count { color: var(--muted); font-size: 12px; }
64
+ .card { display: flex; flex-direction: column; gap: 11px; }
65
+ .frame {
66
+ position: relative;
67
+ aspect-ratio: 16 / 10;
68
+ background: var(--card);
69
+ border: 1px solid var(--line);
70
+ border-radius: 16px;
71
+ overflow: hidden;
72
+ cursor: pointer;
73
+ box-shadow: 0 1px 2px rgba(10, 14, 25, .05);
74
+ transition: box-shadow .18s ease, transform .18s ease, border-color .18s ease;
75
+ }
76
+ .frame:hover {
77
+ box-shadow: 0 14px 34px rgba(10, 14, 25, .16);
78
+ transform: translateY(-3px);
79
+ border-color: rgba(47, 109, 246, .35);
80
+ }
81
+ .dot {
82
+ display: inline-block; width: 7px; height: 7px; border-radius: 50%;
83
+ margin-right: 8px; vertical-align: middle;
84
+ background: var(--accent);
85
+ }
86
+ .dot.user { background: var(--muted); }
87
+ .dot.agentDelegatedToUser { background: #e0a02a; }
88
+ .frame img {
89
+ width: 100%; height: 100%; object-fit: cover; object-position: top center;
90
+ display: block;
91
+ transition: transform .28s ease-out, transform-origin .28s ease-out;
92
+ }
93
+ /* A working space is cropped to where its agent is, so the frame shows the
94
+ action rather than the whole page — say so, or the zoom looks like a bug. */
95
+ .frame.live { border-color: rgba(217, 119, 87, .55); }
96
+ .frame.live img { object-position: center; }
97
+ .live-chip {
98
+ position: absolute; left: 9px; bottom: 9px; right: 9px;
99
+ display: flex; align-items: center; gap: 7px;
100
+ padding: 5px 11px 5px 9px; border-radius: 999px;
101
+ background: rgba(24, 24, 27, .92); color: #fff;
102
+ font-size: 11.5px; font-weight: 500; line-height: 1.35;
103
+ box-shadow: 0 6px 16px rgba(0, 0, 0, .28);
104
+ pointer-events: none;
105
+ }
106
+ .live-chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
107
+ .live-chip i {
108
+ flex: none; width: 7px; height: 7px; border-radius: 50%;
109
+ background: #d97757; animation: breathe 1.7s ease-in-out infinite;
110
+ }
111
+ @keyframes breathe { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
112
+ .frame.empty { display: grid; place-items: center; color: var(--muted); font-size: 13px; }
113
+ .meta { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; padding: 0 3px; }
114
+ .name { font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
115
+ .tag { color: var(--muted); font-size: 12px; white-space: nowrap; }
116
+ .close {
117
+ position: absolute; top: 9px; right: 9px;
118
+ width: 25px; height: 25px; border-radius: 50%;
119
+ border: 1px solid var(--line); background: var(--card); color: var(--muted);
120
+ font-size: 15px; line-height: 1; cursor: pointer;
121
+ opacity: 0; transition: opacity .14s ease;
122
+ }
123
+ .frame:hover .close { opacity: 1; }
124
+ .close:hover { color: #d3453c; }
125
+ .add {
126
+ aspect-ratio: 16 / 10;
127
+ border: 1px dashed var(--line);
128
+ border-radius: 13px;
129
+ background: transparent;
130
+ color: var(--muted);
131
+ font-size: 30px; font-weight: 300;
132
+ cursor: pointer;
133
+ transition: border-color .16s ease, color .16s ease, background .16s ease;
134
+ }
135
+ .add:hover { border-color: var(--accent); color: var(--accent); background: var(--card); }
136
+ /* Ownership controls: quiet until the card is hovered, so a grid of spaces
137
+ stays calm rather than reading as a wall of buttons. */
138
+ .controls { display: flex; gap: 8px; padding: 0 3px; min-height: 26px; }
139
+ .ctl {
140
+ font: inherit; font-size: 12px; line-height: 1;
141
+ padding: 6px 12px; border-radius: 999px;
142
+ border: 1px solid var(--line); background: var(--card); color: var(--muted);
143
+ cursor: pointer; opacity: 0;
144
+ transition: opacity .14s ease, color .14s ease, border-color .14s ease;
145
+ }
146
+ .card:hover .ctl, .ctl:focus-visible { opacity: 1; }
147
+ .ctl:hover { color: var(--text); border-color: var(--accent); }
148
+ .ctl.primary { color: var(--accent); border-color: rgba(47, 109, 246, .45); }
149
+ .note {
150
+ margin-top: 34px; padding-top: 16px; border-top: 1px solid var(--line);
151
+ color: var(--muted); font-size: 12px; max-width: 62ch;
152
+ }
153
+ /* What the space actually did, so a card that has gone quiet still says
154
+ something. Reads newest first, like a log. */
155
+ .trail { display: flex; flex-direction: column; gap: 2px; padding: 2px 3px 0; }
156
+ .trail div {
157
+ display: flex; gap: 7px; color: var(--muted); font-size: 11.5px;
158
+ overflow: hidden; white-space: nowrap;
159
+ }
160
+ .trail div span:first-child { overflow: hidden; text-overflow: ellipsis; }
161
+ .trail div span:last-child { flex: none; opacity: .72; }
162
+ .trail div:first-child { color: var(--text); opacity: .82; }
163
+ .empty-state { color: var(--muted); padding: 40px 0; }
164
+ </style>
165
+ </head>
166
+ <body>
167
+ <header>
168
+ <h1>Spaces</h1>
169
+ <span class="sub">workspaces you and your agents share</span>
170
+ </header>
171
+ <div class="sections" id="grid"></div>
172
+ <p class="note" id="note"></p>
173
+
174
+ <script>
175
+ const grid = document.getElementById("grid");
176
+ const note = document.getElementById("note");
177
+ let busy = false;
178
+ let anyLive = false;
179
+
180
+ async function api(path, options) {
181
+ const response = await fetch(path, {
182
+ ...options,
183
+ headers: { "content-type": "application/json" },
184
+ });
185
+ if (!response.ok) throw new Error(await response.text());
186
+ return response.json();
187
+ }
188
+
189
+ /**
190
+ * What the agent in this space is doing, over the thumbnail. The cursor itself
191
+ * is only a few pixels at card scale, so the chip — not the crop — is what makes
192
+ * activity readable at a glance.
193
+ */
194
+ function liveChip(activity) {
195
+ const chip = document.createElement("div");
196
+ chip.className = "live-chip";
197
+ const seconds = Math.round(activity.ageMs / 1000);
198
+ const when = seconds < 2 ? "now" : seconds + "s ago";
199
+ const text = document.createElement("span");
200
+ text.textContent =
201
+ (activity.name || "agent") +
202
+ (activity.label ? " \\u00b7 " + activity.label : "") +
203
+ " \\u00b7 " +
204
+ when;
205
+ chip.append(document.createElement("i"), text);
206
+ return chip;
207
+ }
208
+
209
+ function card(space) {
210
+ const wrap = document.createElement("div");
211
+ wrap.className = "card";
212
+
213
+ const frame = document.createElement("div");
214
+ frame.className =
215
+ "frame" + (space.thumbnail ? "" : " empty") + (space.activity ? " live" : "");
216
+ frame.title = space.url || "";
217
+ if (space.thumbnail) {
218
+ const img = document.createElement("img");
219
+ img.src = space.thumbnail;
220
+ img.alt = space.title || space.name;
221
+ // A screencast frame is the whole viewport, where the cursor is about five
222
+ // pixels wide in a card — unreadable. The server used to crop to the cursor;
223
+ // now the frames arrive continuously and the zoom happens here instead, so
224
+ // motion stays smooth and the action still fills the card.
225
+ const spot = space.activity;
226
+ if (spot && spot.fx != null && spot.fy != null) {
227
+ img.style.transformOrigin =
228
+ (spot.fx * 100).toFixed(1) + "% " + (spot.fy * 100).toFixed(1) + "%";
229
+ img.style.transform = "scale(2.4)";
230
+ }
231
+ frame.append(img);
232
+ } else {
233
+ frame.textContent = "no page yet";
234
+ }
235
+ if (space.activity) frame.append(liveChip(space.activity));
236
+ frame.addEventListener("click", () => act("/api/spaces/" + space.id + "/use", "POST"));
237
+
238
+ const close = document.createElement("button");
239
+ close.className = "close";
240
+ close.textContent = "\\u00d7";
241
+ close.title = "close this space";
242
+ close.addEventListener("click", (event) => {
243
+ event.stopPropagation();
244
+ act("/api/spaces/" + space.id + "/close", "POST");
245
+ });
246
+ frame.append(close);
247
+
248
+ const meta = document.createElement("div");
249
+ meta.className = "meta";
250
+
251
+ const name = document.createElement("span");
252
+ name.className = "name";
253
+ const dot = document.createElement("i");
254
+ dot.className = "dot " + space.ownership;
255
+ dot.title =
256
+ space.ownership === "user"
257
+ ? "yours"
258
+ : space.ownership === "agentDelegatedToUser"
259
+ ? "handed to you"
260
+ : "an agent is working here";
261
+ name.append(dot, document.createTextNode(space.name));
262
+
263
+ // The native overview labels each space with its category. The useful
264
+ // equivalent here is the agent profile that opened it.
265
+ const tag = document.createElement("span");
266
+ tag.className = "tag";
267
+ const label = space.profile
268
+ ? space.profile + (space.session ? " \\u00b7 " + space.session : "")
269
+ : space.ownership === "user"
270
+ ? "yours"
271
+ : "agent";
272
+ tag.textContent = label;
273
+ tag.title =
274
+ (space.profile ? "cue profile: " + space.profile : "no cue profile recorded") +
275
+ " \\u2014 " +
276
+ space.tabCount +
277
+ (space.tabCount === 1 ? " tab" : " tabs");
278
+
279
+ meta.append(name, tag);
280
+
281
+ // The ownership handshake, the same pair the native app puts on its Space
282
+ // overlay: stop hands the space back to you and the agent's cursor goes away;
283
+ // take over gives it back. Shown on hover so a wall of cards stays calm.
284
+ const controls = document.createElement("div");
285
+ controls.className = "controls";
286
+ const agentOwned = space.ownership === "agent";
287
+ const action = document.createElement("button");
288
+ action.className = "ctl" + (agentOwned ? "" : " primary");
289
+ action.textContent = agentOwned ? "Stop" : "Take over";
290
+ action.title = agentOwned
291
+ ? "hand this space back to you — the agent stops driving it"
292
+ : "let the agent drive this space again";
293
+ action.addEventListener("click", (event) => {
294
+ event.stopPropagation();
295
+ act("/api/spaces/" + space.id + "/" + (agentOwned ? "stop" : "takeover"), "POST");
296
+ });
297
+ controls.append(action);
298
+
299
+ wrap.append(frame, meta, controls);
300
+ if (space.trail?.length) wrap.append(trail(space.trail));
301
+ return wrap;
302
+ }
303
+
304
+ /** Rough, human ages: nobody reads a card to the second. */
305
+ function ago(ms) {
306
+ const seconds = Math.round(ms / 1000);
307
+ if (seconds < 5) return "just now";
308
+ if (seconds < 60) return seconds + "s ago";
309
+ const minutes = Math.round(seconds / 60);
310
+ return minutes < 60 ? minutes + "m ago" : Math.round(minutes / 60) + "h ago";
311
+ }
312
+
313
+ /** What the space actually did, newest first. */
314
+ function trail(entries) {
315
+ const list = document.createElement("div");
316
+ list.className = "trail";
317
+ for (const entry of entries) {
318
+ const row = document.createElement("div");
319
+ const what = document.createElement("span");
320
+ what.textContent = entry.text;
321
+ const when = document.createElement("span");
322
+ when.textContent = ago(entry.ageMs);
323
+ row.append(what, when);
324
+ list.append(row);
325
+ }
326
+ return list;
327
+ }
328
+
329
+ function addCard() {
330
+ const wrap = document.createElement("div");
331
+ wrap.className = "card";
332
+ const button = document.createElement("button");
333
+ button.className = "add";
334
+ button.textContent = "+";
335
+ button.title = "new space";
336
+ button.addEventListener("click", async () => {
337
+ const name = prompt("Name this space", "new space");
338
+ if (name === null) return;
339
+ await act("/api/spaces", "POST", { name: name.trim() || "new space" });
340
+ });
341
+ wrap.append(button);
342
+ return wrap;
343
+ }
344
+
345
+ async function act(path, method, body) {
346
+ if (busy) return;
347
+ busy = true;
348
+ try {
349
+ await api(path, { method, body: body ? JSON.stringify(body) : undefined });
350
+ await refresh();
351
+ } catch (error) {
352
+ note.textContent = "action failed: " + error.message;
353
+ } finally {
354
+ busy = false;
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Several cue profiles can drive the browser at once, so the overview groups by
360
+ * the profile that opened each space. Without that, a row of cards from three
361
+ * different agents reads as one undifferentiated pile.
362
+ */
363
+ function groupByProfile(spaces) {
364
+ const groups = new Map();
365
+ for (const space of spaces) {
366
+ const key = space.profile || "";
367
+ if (!groups.has(key)) groups.set(key, []);
368
+ groups.get(key).push(space);
369
+ }
370
+ // Named profiles first, alphabetically; unattributed spaces last.
371
+ return [...groups.entries()].sort(([a], [b]) => {
372
+ if (!a) return 1;
373
+ if (!b) return -1;
374
+ return a.localeCompare(b);
375
+ });
376
+ }
377
+
378
+ function section(profile, spaces, withAddCard) {
379
+ const wrap = document.createElement("section");
380
+ wrap.className = "section";
381
+
382
+ const head = document.createElement("div");
383
+ head.className = "section-head";
384
+ const title = document.createElement("span");
385
+ title.className = "section-title";
386
+ title.textContent = profile || "not from an agent";
387
+ const count = document.createElement("span");
388
+ count.className = "section-count";
389
+ const sessions = new Set(spaces.map((s) => s.session).filter(Boolean));
390
+ count.textContent =
391
+ spaces.length +
392
+ (spaces.length === 1 ? " space" : " spaces") +
393
+ (sessions.size > 1 ? " \\u00b7 " + sessions.size + " sessions" : "");
394
+ head.append(title, count);
395
+
396
+ const body = document.createElement("div");
397
+ body.className = "grid";
398
+ body.append(...spaces.map(card));
399
+ if (withAddCard) body.append(addCard());
400
+
401
+ wrap.append(head, body);
402
+ return wrap;
403
+ }
404
+
405
+ async function refresh() {
406
+ try {
407
+ const { spaces } = await api("/api/spaces");
408
+ anyLive = spaces.some((space) => space.activity);
409
+ const groups = groupByProfile(spaces);
410
+
411
+ if (!spaces.length) {
412
+ const body = document.createElement("div");
413
+ body.className = "grid";
414
+ body.append(addCard());
415
+ const empty = document.createElement("p");
416
+ empty.className = "empty-state";
417
+ empty.textContent = "No spaces yet. Create one, or let an agent open its own.";
418
+ grid.replaceChildren(empty, body);
419
+ } else {
420
+ grid.replaceChildren(
421
+ ...groups.map(([profile, list], index) =>
422
+ section(profile, list, index === groups.length - 1),
423
+ ),
424
+ );
425
+ }
426
+
427
+ note.textContent = spaces.length
428
+ ? "Each space gets its own cookie jar, seeded from your logins when it is created."
429
+ : "";
430
+ } catch (error) {
431
+ note.textContent = "cannot reach the browser: " + error.message;
432
+ }
433
+ }
434
+
435
+ // Poll faster while an agent is actually working, so a card that is meant to
436
+ // show movement gets to show some. Idle spaces do not need the traffic: every
437
+ // refresh costs a screenshot per space.
438
+ const IDLE_POLL_MS = 4000;
439
+ const LIVE_POLL_MS = 400;
440
+ let timer = null;
441
+
442
+ function schedule() {
443
+ clearTimeout(timer);
444
+ timer = setTimeout(tick, anyLive ? LIVE_POLL_MS : IDLE_POLL_MS);
445
+ }
446
+
447
+ async function tick() {
448
+ if (!busy && !document.hidden) await refresh();
449
+ schedule();
450
+ }
451
+
452
+ refresh().then(schedule);
453
+ </script>
454
+ </body>
455
+ </html>
456
+ `;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Tab surface: ego.listTabs() and ego.createTab(url).
3
+ *
4
+ * Contract (package/ego-browser/src/driver/nav.ts):
5
+ * listTabs() -> { tabs: [{ targetId, title, url, active, index }] }
6
+ * createTab(url)-> { targetId }
7
+ *
8
+ * `active` matters more than it looks: ensureSession() attaches its CDP session
9
+ * to `tabs.find(t => t.active)`, so getting it wrong points every helper at the
10
+ * wrong page. CDP has no "which tab is focused" query, so the DevTools HTTP
11
+ * endpoint is used instead — it lists targets most-recently-used first, which
12
+ * also tracks tabs the user switches to by hand.
13
+ */
14
+
15
+ export function createTabsApi(cdp, { port, getScope }) {
16
+ async function mruOrder() {
17
+ if (!port) return null;
18
+ try {
19
+ const response = await fetch(`http://127.0.0.1:${port}/json/list`, {
20
+ signal: AbortSignal.timeout(2000),
21
+ });
22
+ if (!response.ok) return null;
23
+ const list = await response.json();
24
+ return list.filter((entry) => entry.type === "page").map((entry) => entry.id);
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ return {
31
+ async listTabs() {
32
+ const { targetInfos = [] } = await cdp.call("Target.getTargets");
33
+ let pages = targetInfos.filter(
34
+ (target) => target.type === "page" && !target.url.startsWith("devtools://"),
35
+ );
36
+
37
+ // Scoped to the selected space, the way the native app lists only the
38
+ // selected Space's tabs.
39
+ //
40
+ // This was dropped once, for good reason: membership used to be inferred
41
+ // from which window a tab landed in, and Target.createTarget takes no
42
+ // window id — so every heuristic either hid a tab the harness still held
43
+ // ("switchTab: target not found") or leaked one space's tabs into
44
+ // another's list. Browser-context-backed spaces removed the guesswork:
45
+ // Target.getTargets reports each target's browserContextId, and a tab
46
+ // opened for a space is created in that context, so membership is now a
47
+ // fact rather than an inference.
48
+ //
49
+ // Spaces without a context — the fallback path, and spaces re-adopted
50
+ // after a restart — fall back to the tracked target ids, which are exact
51
+ // for tabs the shim opened.
52
+ const scope = getScope ? await getScope() : null;
53
+ if (scope) {
54
+ const scoped = pages.filter((target) =>
55
+ scope.browserContextId
56
+ ? target.browserContextId === scope.browserContextId
57
+ : scope.targetIds.has(target.targetId),
58
+ );
59
+ // Never hand back an empty list: a space mid-navigation, or one whose
60
+ // only tab the user just closed, must not look like a browser with no
61
+ // tabs at all.
62
+ if (scoped.length > 0) pages = scoped;
63
+ }
64
+
65
+ const order = await mruOrder();
66
+ if (order) {
67
+ const rank = new Map(order.map((id, index) => [id, index]));
68
+ pages.sort(
69
+ (a, b) =>
70
+ (rank.get(a.targetId) ?? Number.MAX_SAFE_INTEGER) -
71
+ (rank.get(b.targetId) ?? Number.MAX_SAFE_INTEGER),
72
+ );
73
+ }
74
+
75
+ // An explicit activation by the harness (switchTab, openOrReuseTab) beats
76
+ // the endpoint's MRU guess, which does not always reflect a programmatic
77
+ // Target.activateTarget — especially headless.
78
+ const hinted = cdp.activeHint?.();
79
+ const activeId =
80
+ hinted && pages.some((target) => target.targetId === hinted)
81
+ ? hinted
82
+ : pages[0]?.targetId;
83
+ return {
84
+ tabs: pages.map((target, index) => ({
85
+ targetId: target.targetId,
86
+ title: target.title || "",
87
+ url: target.url || "",
88
+ active: target.targetId === activeId,
89
+ index,
90
+ })),
91
+ };
92
+ },
93
+
94
+ // browserContextId places the tab in a task space's own cookie jar; without
95
+ // one the tab lands in the default context, which is the pre-context
96
+ // behaviour and still correct for spaces that have no context.
97
+ async createTab(url = "about:blank", browserContextId = undefined) {
98
+ const { targetId } = await cdp.call("Target.createTarget", {
99
+ url,
100
+ ...(browserContextId ? { browserContextId } : {}),
101
+ });
102
+ if (!targetId) throw new Error("Target.createTarget returned no targetId");
103
+ // Make it the active tab, matching the native behaviour where a freshly
104
+ // created tab is the one the agent goes on to act on.
105
+ await cdp.call("Target.activateTarget", { targetId }).catch(() => {});
106
+ return { targetId };
107
+ },
108
+ };
109
+ }