dsh-browser-cdp 0.0.1 → 0.16.24
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/LICENSE +27 -0
- package/README.md +285 -9
- package/THIRD_PARTY_NOTICES.md +62 -0
- package/bin/cdp-cast-worker.mjs +7012 -0
- package/bin/cdp-chrome-wrapper.sh +53 -0
- package/bin/cdp-render-worker.mjs +610 -0
- package/bin/record-normalize.d.mts +32 -0
- package/bin/record-normalize.mjs +156 -0
- package/cordis.patch.yml +17 -0
- package/dsh-plugin.json +148 -0
- package/lib/client.js +5985 -0
- package/lib/index.js +8923 -0
- package/lib/launcher-CQyI8-By.js +3 -0
- package/lib/launcher-DBaxfIsF.js +269 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/it.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/ko.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +94 -14
- package/runtime/PATCHES.md +30 -0
- package/runtime/ego-browser/dist/out/index.js +7206 -0
- package/runtime/ego-browser/screenshot-clip.d.mts +22 -0
- package/runtime/ego-browser/screenshot-clip.mjs +45 -0
- package/runtime/ego-linux/bin/ego-browser.mjs +399 -0
- package/runtime/ego-linux/src/agent-identity.mjs +65 -0
- package/runtime/ego-linux/src/chrome.mjs +867 -0
- package/runtime/ego-linux/src/cursor.mjs +1292 -0
- package/runtime/ego-linux/src/desktop.mjs +73 -0
- package/runtime/ego-linux/src/paths.mjs +35 -0
- package/runtime/ego-linux/src/session.mjs +37 -0
- package/runtime/ego-linux/src/shim.mjs +145 -0
- package/runtime/ego-linux/src/snapshot.mjs +424 -0
- package/runtime/ego-linux/src/spaces-server.mjs +355 -0
- package/runtime/ego-linux/src/spaces-ui.mjs +456 -0
- package/runtime/ego-linux/src/tabs.mjs +109 -0
- package/runtime/ego-linux/src/task-spaces.mjs +671 -0
- package/runtime/ego-linux/src/transport.mjs +321 -0
- package/runtime/ego-linux/src/window-fit.mjs +107 -0
- package/runtime/skills/ego-browser/SKILL.md +209 -0
- package/runtime/skills/ego-browser/agents/openai.yaml +7 -0
- package/runtime/skills/ego-browser/assets/composer-icon.png +0 -0
- package/runtime/skills/ego-browser/assets/logo.png +0 -0
- package/runtime/skills/ego-browser/learnings/google/browser-tools/autocomplete.js +11 -0
- package/runtime/skills/ego-browser/learnings/google/manifest.json +40 -0
- package/runtime/skills/ego-browser/learnings/google/notes/overview.md +23 -0
- package/runtime/skills/ego-browser/learnings/google/tools/search-extract.js +35 -0
- package/runtime/skills/ego-browser/learnings/x-com/browser-tools/extract-post.js +9 -0
- package/runtime/skills/ego-browser/learnings/x-com/manifest.json +51 -0
- package/runtime/skills/ego-browser/learnings/x-com/notes/overview.md +18 -0
- package/runtime/skills/ego-browser/learnings/x-com/notes/timeline.md +19 -0
- package/runtime/skills/ego-browser/learnings/x-com/tools/search-users.js +33 -0
- package/runtime/skills/ego-browser/learnings/x-com/tools/timeline.js +32 -0
- package/runtime/skills/ego-browser/references/install.md +131 -0
- package/runtime/skills/ego-browser/references/task-spaces.md +122 -0
- package/runtime/skills/ego-browser/references/video.md +17 -0
- package/runtime/skills/ego-browser/scripts/install.sh +309 -0
- package/index.js +0 -11
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
|
|
4
|
+
import { agentIdentity } from "./agent-identity.mjs";
|
|
5
|
+
import { STATE_DIR, TASK_SPACE_FILE } from "./paths.mjs";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Task spaces, emulated as tracked sets of tabs.
|
|
9
|
+
*
|
|
10
|
+
* The app's Space is isolated *and* inherits your login state. On stock Chromium
|
|
11
|
+
* those two properties look like they pull apart:
|
|
12
|
+
*
|
|
13
|
+
* Target.createBrowserContext -> real isolation, but a blank cookie jar
|
|
14
|
+
* sharing the default profile -> your real logins, but no isolation
|
|
15
|
+
*
|
|
16
|
+
* They don't: the empty jar can be filled. A space owns a browser context seeded
|
|
17
|
+
* from the default jar at creation, so it gets both — see createSeededContext
|
|
18
|
+
* below and docs/isolation-with-inherited-logins.md. The seed is a point-in-time
|
|
19
|
+
* copy, not live shared state, and a space that fails to get a context falls
|
|
20
|
+
* back to the shared default jar.
|
|
21
|
+
*
|
|
22
|
+
* Spaces deliberately do NOT get their own browser window. That was the first
|
|
23
|
+
* design, and it was measurably worse: a headless Chrome does not render tabs in
|
|
24
|
+
* background windows, so `document.elementFromPoint` returned null for pages
|
|
25
|
+
* living in a non-foreground window. That broke hit-testing, which in turn made
|
|
26
|
+
* the harness's input-fallback path re-synthesise drags that had already landed
|
|
27
|
+
* (see driver/pointer.ts finishDragProbe) — every canvas case in the upstream
|
|
28
|
+
* e2e suite failed or double-counted strokes. One window, tracked tab sets.
|
|
29
|
+
*
|
|
30
|
+
* Each heredoc is a fresh Node process, so state lives in a file, not memory.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const EMPTY = { spaces: [], selectedId: null, nextId: 1, closedSpaces: [] };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* How many idle-closed spaces to remember.
|
|
37
|
+
*
|
|
38
|
+
* Enough that a session returning from a long break still finds its own, few
|
|
39
|
+
* enough that the state file cannot grow without bound.
|
|
40
|
+
*/
|
|
41
|
+
const REMEMBERED_CLOSURES = 20;
|
|
42
|
+
|
|
43
|
+
export function createTaskSpacesApi(cdp) {
|
|
44
|
+
/**
|
|
45
|
+
* Which space *this process* is working in.
|
|
46
|
+
*
|
|
47
|
+
* selectedId lives in a file every concurrent session shares, and each heredoc
|
|
48
|
+
* writes it on the way in. So a second agent starting up silently reassigns
|
|
49
|
+
* the first one: from that moment the first agent scoped its tab list, its
|
|
50
|
+
* navigations and its cursor to the *other* session's space. The observed
|
|
51
|
+
* symptom is a tab navigating away to an unrelated site while the agent that
|
|
52
|
+
* opened it is still working in it, and the other agent finding a stranger's
|
|
53
|
+
* page where its own should be.
|
|
54
|
+
*
|
|
55
|
+
* Once this process has chosen a space it pins it here and stops consulting
|
|
56
|
+
* the shared value. The file still records the global selection — the Spaces
|
|
57
|
+
* overview reads it, and it is the right answer for a fresh process that has
|
|
58
|
+
* not chosen yet — it simply no longer decides what an already-committed
|
|
59
|
+
* process acts on.
|
|
60
|
+
*/
|
|
61
|
+
let pinnedSpaceId = null;
|
|
62
|
+
|
|
63
|
+
/** The pinned space if it still exists, else whatever the file last recorded. */
|
|
64
|
+
function effectiveSelectedId(state) {
|
|
65
|
+
if (
|
|
66
|
+
pinnedSpaceId !== null &&
|
|
67
|
+
state.spaces.some((space) => space.id === pinnedSpaceId)
|
|
68
|
+
) {
|
|
69
|
+
return pinnedSpaceId;
|
|
70
|
+
}
|
|
71
|
+
return state.selectedId;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function readState() {
|
|
75
|
+
try {
|
|
76
|
+
const parsed = JSON.parse(await readFile(TASK_SPACE_FILE, "utf8"));
|
|
77
|
+
return { ...EMPTY, ...parsed };
|
|
78
|
+
} catch {
|
|
79
|
+
return { ...EMPTY };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function writeState(state) {
|
|
84
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
85
|
+
await writeFile(TASK_SPACE_FILE, JSON.stringify(state, null, 2));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function livePageTargets() {
|
|
89
|
+
const { targetInfos = [] } = await cdp.call("Target.getTargets");
|
|
90
|
+
const live = new Map();
|
|
91
|
+
for (const target of targetInfos) {
|
|
92
|
+
if (target.type === "page" && !target.url.startsWith("devtools://")) {
|
|
93
|
+
live.set(target.targetId, target);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return live;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Re-adopt a space's pages after the browser restarted.
|
|
101
|
+
*
|
|
102
|
+
* A space is identified by target ids, and those die with the browser. A
|
|
103
|
+
* restart therefore wiped every space even though Chrome had restored the
|
|
104
|
+
* very pages they described — the overview read "No spaces yet" next to a
|
|
105
|
+
* window full of tabs. Remembered urls are what survive a restart, so they
|
|
106
|
+
* are what the pages get matched back by.
|
|
107
|
+
*
|
|
108
|
+
* Only attempted when EVERY space lost EVERY tab at once, which is the
|
|
109
|
+
* signature of a restart. Closing one space's tabs by hand leaves the others
|
|
110
|
+
* alive, and must stay a deletion — otherwise a space would resurrect itself
|
|
111
|
+
* from any other tab that happened to share its url.
|
|
112
|
+
*/
|
|
113
|
+
function readoptRestoredPages(state, live) {
|
|
114
|
+
if (state.spaces.length === 0) return false;
|
|
115
|
+
if (
|
|
116
|
+
state.spaces.some((space) => (space.targetIds || []).some((id) => live.has(id)))
|
|
117
|
+
) {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const claimed = new Set();
|
|
122
|
+
let changed = false;
|
|
123
|
+
for (const space of state.spaces) {
|
|
124
|
+
const wanted = new Set(space.urls || []);
|
|
125
|
+
if (wanted.size === 0) continue;
|
|
126
|
+
const matches = [...live.values()].filter(
|
|
127
|
+
(target) => !claimed.has(target.targetId) && wanted.has(target.url),
|
|
128
|
+
);
|
|
129
|
+
if (matches.length === 0) continue;
|
|
130
|
+
for (const target of matches) claimed.add(target.targetId);
|
|
131
|
+
space.targetIds = matches.map((target) => target.targetId);
|
|
132
|
+
// Browser contexts do not outlive the browser. The restored pages are in
|
|
133
|
+
// the default jar, so the space is no longer isolated and must not keep
|
|
134
|
+
// claiming a context id that now refers to nothing.
|
|
135
|
+
if (space.browserContextId) space.browserContextId = null;
|
|
136
|
+
space.restored = true;
|
|
137
|
+
changed = true;
|
|
138
|
+
}
|
|
139
|
+
return changed;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Close spaces that were opened and never used.
|
|
144
|
+
*
|
|
145
|
+
* A context-backed space cannot share a window with the default context, so
|
|
146
|
+
* every space is its own window, and every space starts life as a single
|
|
147
|
+
* about:blank tab. Anything that creates spaces in bulk — the e2e suite, a
|
|
148
|
+
* crashed run, an agent that gave up — therefore leaves a drift of empty
|
|
149
|
+
* windows across the desktop, which is what users actually notice.
|
|
150
|
+
*
|
|
151
|
+
* Only a space that is not selected, has *never* held a real page, holds
|
|
152
|
+
* nothing but about:blank, and has had a grace period to receive its first
|
|
153
|
+
* one is swept. "Never held a page" is the load-bearing condition: a tab is
|
|
154
|
+
* momentarily about:blank on every navigation, so judging by the current url
|
|
155
|
+
* alone would delete a working space mid-goto.
|
|
156
|
+
*/
|
|
157
|
+
const ABANDONED_AFTER_MS = 120000;
|
|
158
|
+
|
|
159
|
+
async function pruneAbandoned(state, live) {
|
|
160
|
+
const doomed = state.spaces.filter((space) => {
|
|
161
|
+
if (space.id === effectiveSelectedId(state)) return false;
|
|
162
|
+
// Ever held a real page => not abandoned, only between pages.
|
|
163
|
+
if (space.lastContentAt) return false;
|
|
164
|
+
if (!space.createdAt || Date.now() - space.createdAt < ABANDONED_AFTER_MS) return false;
|
|
165
|
+
const tabs = (space.targetIds || []).map((id) => live.get(id)).filter(Boolean);
|
|
166
|
+
if (tabs.length === 0) return false;
|
|
167
|
+
return tabs.every((target) => target.url === "about:blank");
|
|
168
|
+
});
|
|
169
|
+
if (doomed.length === 0) return false;
|
|
170
|
+
|
|
171
|
+
for (const space of doomed) {
|
|
172
|
+
for (const targetId of space.targetIds) {
|
|
173
|
+
await cdp.call("Target.closeTarget", { targetId }).catch(() => {});
|
|
174
|
+
}
|
|
175
|
+
if (space.browserContextId) await disposeContext(space.browserContextId);
|
|
176
|
+
}
|
|
177
|
+
const gone = new Set(doomed.map((space) => space.id));
|
|
178
|
+
state.spaces = state.spaces.filter((space) => !gone.has(space.id));
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Close spaces nobody has come back to.
|
|
184
|
+
*
|
|
185
|
+
* A space outlives the process that opened it — every heredoc is a fresh Node
|
|
186
|
+
* run — so nothing reaps one whose agent simply stopped returning. A session
|
|
187
|
+
* that ends mid-task leaves its tabs open for good, and the count only climbs;
|
|
188
|
+
* spaces from long-finished work were still holding pages days later.
|
|
189
|
+
*
|
|
190
|
+
* Idleness is measured from the last time something addressed the space, not
|
|
191
|
+
* from when its page last changed: an agent reading one page for ten minutes
|
|
192
|
+
* is working, and a space parked on a live dashboard is not. Live work keeps
|
|
193
|
+
* itself alive by continuing, since every round touches the space it uses.
|
|
194
|
+
*
|
|
195
|
+
* The selected space is never swept — it is the one someone is on right now —
|
|
196
|
+
* and EGO_LINUX_SPACE_IDLE_MIN=0 turns the sweep off for anyone who would
|
|
197
|
+
* rather clean up by hand.
|
|
198
|
+
*/
|
|
199
|
+
const IDLE_MINUTES = Number(process.env.EGO_LINUX_SPACE_IDLE_MIN ?? 30);
|
|
200
|
+
const IDLE_AFTER_MS =
|
|
201
|
+
Number.isFinite(IDLE_MINUTES) && IDLE_MINUTES > 0 ? IDLE_MINUTES * 60000 : 0;
|
|
202
|
+
|
|
203
|
+
async function pruneIdle(state) {
|
|
204
|
+
if (!IDLE_AFTER_MS) return false;
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
// Stamping is itself a state change worth persisting: drop it and every run
|
|
207
|
+
// would re-stamp from scratch, so nothing would ever reach the threshold.
|
|
208
|
+
let stamped = false;
|
|
209
|
+
const doomed = state.spaces.filter((space) => {
|
|
210
|
+
if (space.id === effectiveSelectedId(state)) return false;
|
|
211
|
+
// touchedAt only moves when an API call names the space, and nothing a
|
|
212
|
+
// person does at the keyboard produces one. A space handed over for a
|
|
213
|
+
// login or a captcha, or completed with keep: true — which exists purely
|
|
214
|
+
// to say "leave this page open" — would therefore go idle while it is
|
|
215
|
+
// being used, and get closed out from under them.
|
|
216
|
+
if (
|
|
217
|
+
space.ownership === "user" ||
|
|
218
|
+
space.ownership === "agentDelegatedToUser"
|
|
219
|
+
) {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
// Spaces that predate this field have no idle history, and judging them
|
|
223
|
+
// by createdAt would sweep every one of them the first time the feature
|
|
224
|
+
// runs — including whatever a colleague session is halfway through. Stamp
|
|
225
|
+
// them instead and let them earn a full idle window from here.
|
|
226
|
+
if (!space.touchedAt) {
|
|
227
|
+
space.touchedAt = now;
|
|
228
|
+
stamped = true;
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
return now - space.touchedAt >= IDLE_AFTER_MS;
|
|
232
|
+
});
|
|
233
|
+
if (doomed.length === 0) return stamped;
|
|
234
|
+
|
|
235
|
+
for (const space of doomed) {
|
|
236
|
+
for (const targetId of space.targetIds || []) {
|
|
237
|
+
await cdp.call("Target.closeTarget", { targetId }).catch(() => {});
|
|
238
|
+
}
|
|
239
|
+
if (space.browserContextId) await disposeContext(space.browserContextId);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Leave a trail. Without one, an agent coming back after a long break calls
|
|
243
|
+
// useOrCreate with the same name, silently gets a brand-new empty space, and
|
|
244
|
+
// carries on believing it resumed — the tabs it had open are simply gone and
|
|
245
|
+
// nothing says so. A closed space that names itself and lists what it held
|
|
246
|
+
// turns that into something the agent can put back.
|
|
247
|
+
const closures = state.closedSpaces || [];
|
|
248
|
+
for (const space of doomed) {
|
|
249
|
+
closures.unshift({
|
|
250
|
+
name: space.name,
|
|
251
|
+
urls: (space.urls || []).filter((url) => url && url !== "about:blank"),
|
|
252
|
+
closedAt: now,
|
|
253
|
+
idleMinutes: Math.round((now - space.touchedAt) / 60000),
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
state.closedSpaces = closures.slice(0, REMEMBERED_CLOSURES);
|
|
257
|
+
|
|
258
|
+
const gone = new Set(doomed.map((space) => space.id));
|
|
259
|
+
state.spaces = state.spaces.filter((space) => !gone.has(space.id));
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Drop tabs the user closed, and spaces left with none. */
|
|
264
|
+
async function reconcile(state) {
|
|
265
|
+
const live = await livePageTargets();
|
|
266
|
+
let changed = false;
|
|
267
|
+
|
|
268
|
+
for (const space of state.spaces) {
|
|
269
|
+
const kept = (space.targetIds || []).filter((id) => live.has(id));
|
|
270
|
+
if (kept.length !== (space.targetIds || []).length) {
|
|
271
|
+
space.targetIds = kept;
|
|
272
|
+
changed = true;
|
|
273
|
+
}
|
|
274
|
+
// Remembered while the pages are alive, so a restart has something to
|
|
275
|
+
// match them back by.
|
|
276
|
+
if (kept.length > 0) {
|
|
277
|
+
const urls = kept.map((id) => live.get(id).url).filter(Boolean);
|
|
278
|
+
// A space that has ever held a real page is never "opened and never
|
|
279
|
+
// used", however blank it looks right now — a tab is momentarily
|
|
280
|
+
// about:blank on every navigation.
|
|
281
|
+
if (!space.lastContentAt && urls.some((url) => url !== "about:blank")) {
|
|
282
|
+
space.lastContentAt = Date.now();
|
|
283
|
+
changed = true;
|
|
284
|
+
}
|
|
285
|
+
if (urls.join("\n") !== (space.urls || []).join("\n")) {
|
|
286
|
+
space.urls = urls;
|
|
287
|
+
changed = true;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (readoptRestoredPages(state, live)) changed = true;
|
|
293
|
+
if (await pruneAbandoned(state, live)) changed = true;
|
|
294
|
+
if (await pruneIdle(state)) changed = true;
|
|
295
|
+
|
|
296
|
+
const surviving = state.spaces.filter((space) => space.targetIds.length > 0);
|
|
297
|
+
if (surviving.length !== state.spaces.length) {
|
|
298
|
+
// Losing its last tab is how a space ends when the user closes tabs by
|
|
299
|
+
// hand, so its context has to go the same way closeTaskSpace disposes
|
|
300
|
+
// one. Dropping the record alone would strand a live context holding a
|
|
301
|
+
// full copy of the seeded cookie jar until the browser restarts.
|
|
302
|
+
for (const space of state.spaces) {
|
|
303
|
+
if (space.targetIds.length === 0 && space.browserContextId) {
|
|
304
|
+
await disposeContext(space.browserContextId);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
state.spaces = surviving;
|
|
308
|
+
changed = true;
|
|
309
|
+
}
|
|
310
|
+
if (!state.spaces.some((space) => space.id === state.selectedId)) {
|
|
311
|
+
state.selectedId = null;
|
|
312
|
+
changed = true;
|
|
313
|
+
}
|
|
314
|
+
if (changed) await writeState(state);
|
|
315
|
+
return { state, live };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function decorate(space, live) {
|
|
319
|
+
return {
|
|
320
|
+
...space,
|
|
321
|
+
taskId: space.taskId ?? space.id,
|
|
322
|
+
recentTabTitles: space.targetIds
|
|
323
|
+
.map((id) => live.get(id)?.title || "")
|
|
324
|
+
.filter(Boolean),
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* The harness selects a space with useTaskSpace() and then calls handOff /
|
|
330
|
+
* takeOver / complete / close with NO arguments — they act on whatever is
|
|
331
|
+
* currently selected (see helpers.ts:326-354). Only useTaskSpace, claim and
|
|
332
|
+
* create are passed an id.
|
|
333
|
+
*/
|
|
334
|
+
async function requireSpace(state, id, op) {
|
|
335
|
+
const wanted =
|
|
336
|
+
id === undefined || id === null ? effectiveSelectedId(state) : Number(id);
|
|
337
|
+
const space = state.spaces.find((candidate) => candidate.id === wanted);
|
|
338
|
+
if (!space) {
|
|
339
|
+
throw new Error(
|
|
340
|
+
id === undefined || id === null
|
|
341
|
+
? `${op}: no task space is selected`
|
|
342
|
+
: `${op}: task space not found: ${id}`,
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
// Every API call that names a space is a session saying it is still here.
|
|
346
|
+
// That is what the idle sweep measures, and touching it in the one place
|
|
347
|
+
// they all pass through is what keeps live work from being swept out from
|
|
348
|
+
// under an agent that simply had a long think between rounds.
|
|
349
|
+
space.touchedAt = Date.now();
|
|
350
|
+
return space;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Bring the space's own tab to the front, so the agent lands back on it. */
|
|
354
|
+
async function focusSpace(space) {
|
|
355
|
+
const live = await livePageTargets();
|
|
356
|
+
const targetId = space.targetIds.find((id) => live.has(id));
|
|
357
|
+
if (targetId) {
|
|
358
|
+
await cdp.call("Target.activateTarget", { targetId }).catch(() => {});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Give a space its own cookie jar, pre-filled with the user's.
|
|
364
|
+
*
|
|
365
|
+
* Target.createBrowserContext isolates for real, but starts empty — which on
|
|
366
|
+
* its own would log the agent out of everything, so this port used to take a
|
|
367
|
+
* bare window instead and accept a shared jar. Seeding the new context from
|
|
368
|
+
* the default jar gets both properties at once: measurements and the two
|
|
369
|
+
* reproducible experiments are in docs/isolation-with-inherited-logins.md.
|
|
370
|
+
*
|
|
371
|
+
* These calls carry no sessionId, so the transport sends them at the browser
|
|
372
|
+
* level, which is where browserContextId is accepted.
|
|
373
|
+
*
|
|
374
|
+
* Returns null if the browser refuses a context, so a space degrades to the
|
|
375
|
+
* previous window-only behaviour rather than failing to open at all.
|
|
376
|
+
*/
|
|
377
|
+
/**
|
|
378
|
+
* The selected space's context id, read synchronously.
|
|
379
|
+
*
|
|
380
|
+
* Sync because its only caller is the transport rewriting an outgoing payload
|
|
381
|
+
* on its way to the socket, which has nowhere to await. The state file is a
|
|
382
|
+
* few hundred bytes and the rewrite only fires on Browser.setDownloadBehavior,
|
|
383
|
+
* so this is not on any hot path.
|
|
384
|
+
*/
|
|
385
|
+
function selectedContextId() {
|
|
386
|
+
try {
|
|
387
|
+
const state = JSON.parse(readFileSync(TASK_SPACE_FILE, "utf8"));
|
|
388
|
+
const wanted = effectiveSelectedId({ ...state, spaces: state.spaces ?? [] });
|
|
389
|
+
const space = state.spaces?.find((candidate) => candidate.id === wanted);
|
|
390
|
+
return space?.browserContextId ?? null;
|
|
391
|
+
} catch {
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** The space's own still-blank tab, if it has exactly that and nothing else. */
|
|
397
|
+
async function blankAnchor(space) {
|
|
398
|
+
const ids = space.targetIds || [];
|
|
399
|
+
if (ids.length !== 1) return null;
|
|
400
|
+
const live = await livePageTargets().catch(() => new Map());
|
|
401
|
+
const target = live.get(ids[0]);
|
|
402
|
+
return target && target.url === "about:blank" ? target.targetId : null;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function disposeContext(browserContextId) {
|
|
406
|
+
await cdp
|
|
407
|
+
.call("Target.disposeBrowserContext", { browserContextId })
|
|
408
|
+
.catch(() => {});
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function createSeededContext() {
|
|
412
|
+
// 若未开启沙盒隔离(默认):直接使用 Chrome 默认原生磁盘 Profile。
|
|
413
|
+
// 效果:用户在任务中登录的账号 Cookie 实时落盘,关机重启永久保留。
|
|
414
|
+
if (process.env.EGO_ISOLATE_SPACES !== "1") {
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// 若开启沙盒隔离:按原作者设计创建独立内存 BrowserContext,防止 Cookie 串扰
|
|
419
|
+
let browserContextId;
|
|
420
|
+
try {
|
|
421
|
+
({ browserContextId } = await cdp.call("Target.createBrowserContext", {}));
|
|
422
|
+
} catch {
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
if (!browserContextId) return null;
|
|
426
|
+
try {
|
|
427
|
+
const { cookies } = await cdp.call("Storage.getCookies", {});
|
|
428
|
+
if (cookies?.length) {
|
|
429
|
+
await cdp.call("Storage.setCookies", { browserContextId, cookies });
|
|
430
|
+
}
|
|
431
|
+
} catch {
|
|
432
|
+
// An unseeded context is still a usable space, just a logged-out one.
|
|
433
|
+
}
|
|
434
|
+
return browserContextId;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return {
|
|
438
|
+
selectedContextId,
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Remember that the selected space received a real page.
|
|
442
|
+
*
|
|
443
|
+
* This is what keeps a working space out of the abandoned sweep: its tab is
|
|
444
|
+
* about:blank again on every navigation, so the current url can never tell
|
|
445
|
+
* "never used" apart from "between pages". Recorded once, never cleared.
|
|
446
|
+
*/
|
|
447
|
+
async noteContent() {
|
|
448
|
+
const state = await readState();
|
|
449
|
+
const space = state.spaces.find(
|
|
450
|
+
(candidate) => candidate.id === effectiveSelectedId(state),
|
|
451
|
+
);
|
|
452
|
+
if (!space || space.lastContentAt) return;
|
|
453
|
+
space.lastContentAt = Date.now();
|
|
454
|
+
await writeState(state);
|
|
455
|
+
},
|
|
456
|
+
|
|
457
|
+
async listTaskSpaces() {
|
|
458
|
+
const { state, live } = await reconcile(await readState());
|
|
459
|
+
return { taskSpaces: state.spaces.map((space) => decorate(space, live)) };
|
|
460
|
+
},
|
|
461
|
+
|
|
462
|
+
async createTaskSpace(name) {
|
|
463
|
+
const state = await readState();
|
|
464
|
+
const browserContextId = await createSeededContext();
|
|
465
|
+
let targetId;
|
|
466
|
+
try {
|
|
467
|
+
({ targetId } = await cdp.call("Target.createTarget", {
|
|
468
|
+
url: "about:blank",
|
|
469
|
+
...(browserContextId ? { browserContextId } : {}),
|
|
470
|
+
}));
|
|
471
|
+
} catch (err) {
|
|
472
|
+
// Nothing will ever reference this context if the space fails to open.
|
|
473
|
+
if (browserContextId) await disposeContext(browserContextId);
|
|
474
|
+
throw err;
|
|
475
|
+
}
|
|
476
|
+
await cdp.call("Target.activateTarget", { targetId }).catch(() => {});
|
|
477
|
+
|
|
478
|
+
const space = {
|
|
479
|
+
id: state.nextId,
|
|
480
|
+
taskId: state.nextId,
|
|
481
|
+
name: String(name ?? `task ${state.nextId}`),
|
|
482
|
+
createdAt: Date.now(),
|
|
483
|
+
touchedAt: Date.now(),
|
|
484
|
+
ownership: "agent",
|
|
485
|
+
createdBy: "agent",
|
|
486
|
+
// Which agent profile opened it — the overview's right-hand label.
|
|
487
|
+
...agentIdentity(),
|
|
488
|
+
browserContextId,
|
|
489
|
+
targetIds: [targetId],
|
|
490
|
+
};
|
|
491
|
+
state.spaces.push(space);
|
|
492
|
+
state.nextId += 1;
|
|
493
|
+
state.selectedId = space.id;
|
|
494
|
+
pinnedSpaceId = space.id;
|
|
495
|
+
|
|
496
|
+
// useOrCreate lands here whenever it cannot find the name it was given —
|
|
497
|
+
// including when the idle sweep closed that very space while its agent was
|
|
498
|
+
// away. Handing back what the old one held is the difference between
|
|
499
|
+
// "resumed" and "started over without noticing". Consumed on use, so it is
|
|
500
|
+
// reported once rather than on every later run of the same name.
|
|
501
|
+
const closures = state.closedSpaces || [];
|
|
502
|
+
const index = closures.findIndex((entry) => entry.name === space.name);
|
|
503
|
+
if (index !== -1) {
|
|
504
|
+
const [previous] = closures.splice(index, 1);
|
|
505
|
+
state.closedSpaces = closures;
|
|
506
|
+
space.previously = {
|
|
507
|
+
closedAt: previous.closedAt,
|
|
508
|
+
idleMinutes: previous.idleMinutes,
|
|
509
|
+
urls: previous.urls,
|
|
510
|
+
note:
|
|
511
|
+
`a task space named ${JSON.stringify(space.name)} was closed after ` +
|
|
512
|
+
`${previous.idleMinutes} minutes idle; this is a new, empty one. ` +
|
|
513
|
+
(previous.urls.length
|
|
514
|
+
? `It had these pages open: ${previous.urls.join(", ")}`
|
|
515
|
+
: "It had no pages open."),
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
await writeState(state);
|
|
520
|
+
return space;
|
|
521
|
+
},
|
|
522
|
+
|
|
523
|
+
async useTaskSpace(id) {
|
|
524
|
+
const state = await readState();
|
|
525
|
+
const space = await requireSpace(state, id, "useTaskSpace");
|
|
526
|
+
state.selectedId = space.id;
|
|
527
|
+
pinnedSpaceId = space.id;
|
|
528
|
+
await writeState(state);
|
|
529
|
+
await focusSpace(space);
|
|
530
|
+
return { done: true };
|
|
531
|
+
},
|
|
532
|
+
|
|
533
|
+
async claimTaskSpace(id) {
|
|
534
|
+
const state = await readState();
|
|
535
|
+
const space = await requireSpace(state, id, "claimTaskSpace");
|
|
536
|
+
space.ownership = "agent";
|
|
537
|
+
state.selectedId = space.id;
|
|
538
|
+
pinnedSpaceId = space.id;
|
|
539
|
+
await writeState(state);
|
|
540
|
+
await focusSpace(space);
|
|
541
|
+
return space;
|
|
542
|
+
},
|
|
543
|
+
|
|
544
|
+
async handOffTaskSpace(id) {
|
|
545
|
+
const state = await readState();
|
|
546
|
+
const space = await requireSpace(state, id, "handOffTaskSpace");
|
|
547
|
+
space.ownership = "agentDelegatedToUser";
|
|
548
|
+
await writeState(state);
|
|
549
|
+
return { done: true };
|
|
550
|
+
},
|
|
551
|
+
|
|
552
|
+
async takeOverTaskSpace(id) {
|
|
553
|
+
const state = await readState();
|
|
554
|
+
const space = await requireSpace(state, id, "takeOverTaskSpace");
|
|
555
|
+
space.ownership = "agent";
|
|
556
|
+
state.selectedId = space.id;
|
|
557
|
+
pinnedSpaceId = space.id;
|
|
558
|
+
await writeState(state);
|
|
559
|
+
await focusSpace(space);
|
|
560
|
+
return { done: true };
|
|
561
|
+
},
|
|
562
|
+
|
|
563
|
+
// Only the `keep: true` path reaches here; the harness routes `keep: false`
|
|
564
|
+
// to closeTaskSpace instead (helpers.ts:299-315).
|
|
565
|
+
async completeTaskSpace(id) {
|
|
566
|
+
const state = await readState();
|
|
567
|
+
const space = await requireSpace(state, id, "completeTaskSpace");
|
|
568
|
+
space.ownership = "user";
|
|
569
|
+
await writeState(state);
|
|
570
|
+
return { done: true };
|
|
571
|
+
},
|
|
572
|
+
|
|
573
|
+
async closeTaskSpace(id) {
|
|
574
|
+
const state = await readState();
|
|
575
|
+
const space = await requireSpace(state, id, "closeTaskSpace");
|
|
576
|
+
for (const targetId of space.targetIds) {
|
|
577
|
+
await cdp.call("Target.closeTarget", { targetId }).catch(() => {});
|
|
578
|
+
}
|
|
579
|
+
if (space.browserContextId) {
|
|
580
|
+
// Also drops the space's cookie jar, which is the point of having one.
|
|
581
|
+
await disposeContext(space.browserContextId);
|
|
582
|
+
}
|
|
583
|
+
state.spaces = state.spaces.filter((candidate) => candidate.id !== space.id);
|
|
584
|
+
if (state.selectedId === space.id) state.selectedId = null;
|
|
585
|
+
if (pinnedSpaceId === space.id) pinnedSpaceId = null;
|
|
586
|
+
await writeState(state);
|
|
587
|
+
return { done: true };
|
|
588
|
+
},
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Open a tab and attribute it to the selected space, so completing that
|
|
592
|
+
* space closes the tabs it opened. Membership is tracked by the ids we
|
|
593
|
+
* create rather than inferred from which window a tab landed in, which CDP
|
|
594
|
+
* gives no way to control (Target.createTarget takes no window id). For a
|
|
595
|
+
* space with a context the browser also enforces membership, but the id
|
|
596
|
+
* list stays authoritative so context-less spaces behave identically.
|
|
597
|
+
*/
|
|
598
|
+
/**
|
|
599
|
+
* What listTabs() should show: the selected space's tabs.
|
|
600
|
+
*
|
|
601
|
+
* A browser context identifies membership exactly, so it is preferred. The
|
|
602
|
+
* tracked target ids cover spaces that have no context — the fallback path,
|
|
603
|
+
* and spaces re-adopted after a restart, whose context died with the
|
|
604
|
+
* browser.
|
|
605
|
+
*/
|
|
606
|
+
async selectedScope() {
|
|
607
|
+
const state = await readState();
|
|
608
|
+
if (!effectiveSelectedId(state)) return null;
|
|
609
|
+
const space = state.spaces.find(
|
|
610
|
+
(candidate) => candidate.id === effectiveSelectedId(state),
|
|
611
|
+
);
|
|
612
|
+
if (!space) return null;
|
|
613
|
+
return {
|
|
614
|
+
browserContextId: space.browserContextId || null,
|
|
615
|
+
targetIds: new Set(space.targetIds || []),
|
|
616
|
+
};
|
|
617
|
+
},
|
|
618
|
+
|
|
619
|
+
async createTabInSelectedSpace(tabs, url) {
|
|
620
|
+
const state = await readState();
|
|
621
|
+
const space = state.spaces.find(
|
|
622
|
+
(candidate) => candidate.id === effectiveSelectedId(state),
|
|
623
|
+
);
|
|
624
|
+
// A space is anchored by a tab — one with none is reaped as soon as it is
|
|
625
|
+
// reconciled — so it opens on about:blank before it has anywhere to go.
|
|
626
|
+
// Creating a second tab for the first navigation strands that anchor, and
|
|
627
|
+
// the window then shows a blank tab beside the real page for the rest of
|
|
628
|
+
// the session. Navigating the anchor is what it was opened for.
|
|
629
|
+
//
|
|
630
|
+
// Guarded on lastContentAt rather than on the tab's current url: a tab is
|
|
631
|
+
// about:blank for a moment during every navigation, so matching on the url
|
|
632
|
+
// alone would hijack a tab that is already carrying work. "Never held a
|
|
633
|
+
// page" is only true of a space that has not started yet.
|
|
634
|
+
const anchor = space && !space.lastContentAt ? await blankAnchor(space) : null;
|
|
635
|
+
if (anchor && url && url !== "about:blank") {
|
|
636
|
+
const { sessionId } = await cdp.call("Target.attachToTarget", {
|
|
637
|
+
targetId: anchor,
|
|
638
|
+
flatten: true,
|
|
639
|
+
});
|
|
640
|
+
await cdp.call("Page.navigate", { url }, sessionId);
|
|
641
|
+
await cdp.call("Target.activateTarget", { targetId: anchor }).catch(() => {});
|
|
642
|
+
return { targetId: anchor };
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Open it inside the space's context, so every tab of a space shares that
|
|
646
|
+
// space's jar rather than the first tab being isolated and the rest not.
|
|
647
|
+
let result;
|
|
648
|
+
try {
|
|
649
|
+
result = await tabs.createTab(url, space?.browserContextId);
|
|
650
|
+
} catch (error) {
|
|
651
|
+
// Browser contexts die with the browser, but the selected space's id
|
|
652
|
+
// outlives it in the state file. Chrome then rejects the create with
|
|
653
|
+
// "Failed to find browser context", which used to leave the port unable
|
|
654
|
+
// to open any tab at all after a restart. Fall back to the default jar
|
|
655
|
+
// and forget the dead id — the space stops being isolated, which is
|
|
656
|
+
// already true, rather than stopping working.
|
|
657
|
+
if (!space?.browserContextId || !/browser context/i.test(String(error?.message))) {
|
|
658
|
+
throw error;
|
|
659
|
+
}
|
|
660
|
+
space.browserContextId = null;
|
|
661
|
+
space.restored = true;
|
|
662
|
+
result = await tabs.createTab(url);
|
|
663
|
+
}
|
|
664
|
+
if (space && result.targetId) {
|
|
665
|
+
space.targetIds.push(result.targetId);
|
|
666
|
+
await writeState(state);
|
|
667
|
+
}
|
|
668
|
+
return result;
|
|
669
|
+
},
|
|
670
|
+
};
|
|
671
|
+
}
|