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.
Files changed (62) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +285 -9
  3. package/THIRD_PARTY_NOTICES.md +62 -0
  4. package/bin/cdp-cast-worker.mjs +7012 -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 +5985 -0
  12. package/lib/index.js +8923 -0
  13. package/lib/launcher-CQyI8-By.js +3 -0
  14. package/lib/launcher-DBaxfIsF.js +269 -0
  15. package/locale/de.json +6 -0
  16. package/locale/en.json +6 -0
  17. package/locale/es.json +6 -0
  18. package/locale/fr.json +6 -0
  19. package/locale/it.json +6 -0
  20. package/locale/ja.json +6 -0
  21. package/locale/ko.json +6 -0
  22. package/locale/ru.json +6 -0
  23. package/locale/zh.json +6 -0
  24. package/package.json +94 -14
  25. package/runtime/PATCHES.md +30 -0
  26. package/runtime/ego-browser/dist/out/index.js +7206 -0
  27. package/runtime/ego-browser/screenshot-clip.d.mts +22 -0
  28. package/runtime/ego-browser/screenshot-clip.mjs +45 -0
  29. package/runtime/ego-linux/bin/ego-browser.mjs +399 -0
  30. package/runtime/ego-linux/src/agent-identity.mjs +65 -0
  31. package/runtime/ego-linux/src/chrome.mjs +867 -0
  32. package/runtime/ego-linux/src/cursor.mjs +1292 -0
  33. package/runtime/ego-linux/src/desktop.mjs +73 -0
  34. package/runtime/ego-linux/src/paths.mjs +35 -0
  35. package/runtime/ego-linux/src/session.mjs +37 -0
  36. package/runtime/ego-linux/src/shim.mjs +145 -0
  37. package/runtime/ego-linux/src/snapshot.mjs +424 -0
  38. package/runtime/ego-linux/src/spaces-server.mjs +355 -0
  39. package/runtime/ego-linux/src/spaces-ui.mjs +456 -0
  40. package/runtime/ego-linux/src/tabs.mjs +109 -0
  41. package/runtime/ego-linux/src/task-spaces.mjs +671 -0
  42. package/runtime/ego-linux/src/transport.mjs +321 -0
  43. package/runtime/ego-linux/src/window-fit.mjs +107 -0
  44. package/runtime/skills/ego-browser/SKILL.md +209 -0
  45. package/runtime/skills/ego-browser/agents/openai.yaml +7 -0
  46. package/runtime/skills/ego-browser/assets/composer-icon.png +0 -0
  47. package/runtime/skills/ego-browser/assets/logo.png +0 -0
  48. package/runtime/skills/ego-browser/learnings/google/browser-tools/autocomplete.js +11 -0
  49. package/runtime/skills/ego-browser/learnings/google/manifest.json +40 -0
  50. package/runtime/skills/ego-browser/learnings/google/notes/overview.md +23 -0
  51. package/runtime/skills/ego-browser/learnings/google/tools/search-extract.js +35 -0
  52. package/runtime/skills/ego-browser/learnings/x-com/browser-tools/extract-post.js +9 -0
  53. package/runtime/skills/ego-browser/learnings/x-com/manifest.json +51 -0
  54. package/runtime/skills/ego-browser/learnings/x-com/notes/overview.md +18 -0
  55. package/runtime/skills/ego-browser/learnings/x-com/notes/timeline.md +19 -0
  56. package/runtime/skills/ego-browser/learnings/x-com/tools/search-users.js +33 -0
  57. package/runtime/skills/ego-browser/learnings/x-com/tools/timeline.js +32 -0
  58. package/runtime/skills/ego-browser/references/install.md +131 -0
  59. package/runtime/skills/ego-browser/references/task-spaces.md +122 -0
  60. package/runtime/skills/ego-browser/references/video.md +17 -0
  61. package/runtime/skills/ego-browser/scripts/install.sh +309 -0
  62. package/index.js +0 -11
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Type declarations for screenshot-clip.mjs (PR #50).
3
+ * Sibling declaration so `tests/screenshot-clip.test.ts` can import the plain
4
+ * JS runtime module without TS7016 under tsconfig's tests/ scope.
5
+ */
6
+ export interface ScreenshotClipInfo {
7
+ sx?: number
8
+ sy?: number
9
+ w: number
10
+ h: number
11
+ pw: number
12
+ ph: number
13
+ }
14
+ export interface ScreenshotClipOptions {
15
+ full?: boolean
16
+ clip?: { x?: number; y?: number; width: number; height: number }
17
+ cssScale?: number
18
+ }
19
+ export function captureScreenshotClip(
20
+ info: ScreenshotClipInfo,
21
+ options?: ScreenshotClipOptions,
22
+ ): { x: number; y: number; width: number; height: number; scale: number }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Build a Page.captureScreenshot `clip` in document CSS pixels.
3
+ *
4
+ * CDP clip origin is the layout/document origin, not the visual viewport.
5
+ * `pageInfo().sx/sy` are window.scrollX/scrollY; `boundingBox()` is
6
+ * viewport-relative (getBoundingClientRect). Viewport-only shots and locator
7
+ * clips must add that scroll, otherwise the clip sits at document (0, 0)
8
+ * while captureBeyondViewport is false — Chrome returns a tiny blank PNG
9
+ * after the page has been scrolled. fullPage stays at (0, 0) with
10
+ * captureBeyondViewport: true.
11
+ *
12
+ * Same contract as runtime/ego-linux/src/spaces-server.mjs followClip.
13
+ *
14
+ * @param {{ sx?: number, sy?: number, w: number, h: number, pw: number, ph: number }} info
15
+ * @param {{ full?: boolean, clip?: { x?: number, y?: number, width: number, height: number }, cssScale?: number }} [options]
16
+ */
17
+ export function captureScreenshotClip(info, options = {}) {
18
+ const cssScale = options.cssScale ?? 1;
19
+ const sx = Number(info?.sx) || 0;
20
+ const sy = Number(info?.sy) || 0;
21
+ if (options.clip) {
22
+ return {
23
+ scale: cssScale,
24
+ ...options.clip,
25
+ x: (Number(options.clip.x) || 0) + sx,
26
+ y: (Number(options.clip.y) || 0) + sy,
27
+ };
28
+ }
29
+ if (options.full) {
30
+ return {
31
+ x: 0,
32
+ y: 0,
33
+ width: info.pw,
34
+ height: info.ph,
35
+ scale: cssScale,
36
+ };
37
+ }
38
+ return {
39
+ x: sx,
40
+ y: sy,
41
+ width: info.w,
42
+ height: info.h,
43
+ scale: cssScale,
44
+ };
45
+ }
@@ -0,0 +1,399 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ego-browser, Linux edition.
4
+ *
5
+ * Same CLI shape as the macOS app's `ego-browser`: a heredoc of JS on stdin,
6
+ * executed with every ego-browser helper preloaded. The difference is what backs
7
+ * it — `globalThis.ego` is this port's CDP shim over a stock Chromium instead of
8
+ * the app's native bindings. Everything above that line is the upstream harness,
9
+ * unmodified.
10
+ */
11
+ import { spawn } from "node:child_process";
12
+ import { existsSync } from "node:fs";
13
+ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+ import { fileURLToPath, pathToFileURL } from "node:url";
16
+
17
+ import { browserStatus, stopBrowser } from "../src/chrome.mjs";
18
+ import { installDesktopEntry } from "../src/desktop.mjs";
19
+ import {
20
+ CHROME_CONFIG_CANDIDATES,
21
+ PROFILE_DIR,
22
+ SPACES_STATE_FILE,
23
+ TASK_SPACE_FILE,
24
+ STATE_DIR,
25
+ } from "../src/paths.mjs";
26
+ import { createEgoShim } from "../src/shim.mjs";
27
+ import { startSpacesServer } from "../src/spaces-server.mjs";
28
+
29
+ const HARNESS = new URL("../../ego-browser/dist/out/index.js", import.meta.url);
30
+ const SKILL_WORKSPACE = new URL("../../skills/ego-browser", import.meta.url); // vendored layout: runtime/ego-linux/bin -> runtime/skills/ego-browser
31
+
32
+ const USAGE = `ego-browser (Linux port)
33
+
34
+ ego-browser <<'JS'
35
+ await page.goto('https://example.com')
36
+ console.log(await page.snapshot())
37
+ JS
38
+
39
+ Linux-only commands:
40
+ --status show the backing browser's connection state
41
+ --open open the shared agent browser window
42
+ --spaces open the Spaces overview panel
43
+ --prune-spaces close spaces that hold nothing but about:blank
44
+ Spaces nobody returns to are also closed on their
45
+ own after 30 minutes idle; a space stays alive as
46
+ long as its session keeps using it. Set
47
+ EGO_LINUX_SPACE_IDLE_MIN to change the window, or
48
+ 0 to sweep only by hand
49
+ --stop stop the backing browser
50
+ --import-chrome-profile copy your real Chrome profile in, to inherit logins
51
+ --install-desktop-entry add it to your app launcher, with an icon
52
+ --headless run the backing browser headless (first launch only)
53
+ EGO_LINUX_HEADLESS=1 makes that the default, so the
54
+ agent window never opens over your work; --open
55
+ still gives you a visible one when you want it
56
+ `;
57
+
58
+ async function importChromeProfile() {
59
+ const source = CHROME_CONFIG_CANDIDATES.find((candidate) =>
60
+ existsSync(join(candidate, "Default")),
61
+ );
62
+ if (!source) {
63
+ process.stderr.write("no Chrome/Chromium profile found to import\n");
64
+ return 1;
65
+ }
66
+ const status = await browserStatus();
67
+ if (status.running) {
68
+ process.stderr.write(
69
+ "the backing browser is running; run --stop and close it before importing\n",
70
+ );
71
+ return 1;
72
+ }
73
+ process.stderr.write(`importing ${join(source, "Default")} -> ${PROFILE_DIR}/Default\n`);
74
+ await cp(join(source, "Default"), join(PROFILE_DIR, "Default"), {
75
+ recursive: true,
76
+ force: true,
77
+ });
78
+ process.stderr.write("done — logins and cookies now carry into agent tasks\n");
79
+ return 0;
80
+ }
81
+
82
+ /** Is a Spaces server already listening on the recorded port? */
83
+ async function liveSpacesServer() {
84
+ try {
85
+ const state = JSON.parse(await readFile(SPACES_STATE_FILE, "utf8"));
86
+ const response = await fetch(`http://127.0.0.1:${state.port}/api/health`, {
87
+ signal: AbortSignal.timeout(1500),
88
+ });
89
+ return response.ok ? state.port : null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+
95
+ /** Open the panel as a chrome-less app window on the shared browser. */
96
+ async function openPanelWindow(url) {
97
+ const status = await browserStatus();
98
+ spawn(status.binary || "google-chrome", [`--user-data-dir=${PROFILE_DIR}`, `--app=${url}`], {
99
+ detached: true,
100
+ stdio: "ignore",
101
+ }).unref();
102
+ }
103
+
104
+ /**
105
+ * Serve the Spaces panel until the browser goes away.
106
+ *
107
+ * Runs detached, because the panel's backend must outlive the command that
108
+ * opened it. Tying the server to a foreground CLI process meant that closing
109
+ * the terminal — or any timeout around it — left the panel showing
110
+ * "cannot reach the browser".
111
+ */
112
+ async function runSpacesDaemon() {
113
+ // Spaces created from the panel are the user's, not the profile that happened
114
+ // to launch this daemon (see agent-identity.mjs).
115
+ process.env.EGO_LINUX_PANEL = "1";
116
+ const shim = await createEgoShim({ headless: false });
117
+ const spaces = await startSpacesServer(shim);
118
+ const url = `http://127.0.0.1:${spaces.port}/`;
119
+
120
+ await mkdir(STATE_DIR, { recursive: true });
121
+ await writeFile(
122
+ SPACES_STATE_FILE,
123
+ JSON.stringify({ port: spaces.port, pid: process.pid }, null, 2),
124
+ );
125
+
126
+ // The daemon owns the window it serves, so starting one always shows it.
127
+ await openPanelWindow(url);
128
+
129
+ const outcome = await new Promise((resolve) => {
130
+ process.on("SIGINT", () => resolve("signal"));
131
+ process.on("SIGTERM", () => resolve("signal"));
132
+
133
+ // Give Chrome a moment to register the window before deciding it is absent.
134
+ let seenPanel = false;
135
+ const started = Date.now();
136
+
137
+ const timer = setInterval(async () => {
138
+ let tabs;
139
+ try {
140
+ ({ tabs } = await shim.ego.listTabs());
141
+ } catch {
142
+ // The browser went away, taking every window — including this panel —
143
+ // with it. That is a restart, not a decision, so hand off to a fresh
144
+ // daemon that will reopen the panel against the new browser.
145
+ clearInterval(timer);
146
+ resolve("browser-gone");
147
+ return;
148
+ }
149
+
150
+ const open = tabs.some((tab) => tab.url.startsWith(url));
151
+ if (open) {
152
+ seenPanel = true;
153
+ return;
154
+ }
155
+ // Closing the panel while the browser keeps running is deliberate: stop
156
+ // serving rather than reopening a window the user just dismissed.
157
+ if (seenPanel || Date.now() - started > 20000) {
158
+ clearInterval(timer);
159
+ resolve("panel-closed");
160
+ }
161
+ }, 2500);
162
+ });
163
+
164
+ spaces.close();
165
+ shim.close();
166
+ await rm(SPACES_STATE_FILE, { force: true });
167
+
168
+ if (outcome === "browser-gone") {
169
+ spawn(process.execPath, [fileURLToPath(import.meta.url), "--spaces-daemon"], {
170
+ detached: true,
171
+ stdio: "ignore",
172
+ }).unref();
173
+ }
174
+ return 0;
175
+ }
176
+
177
+ /**
178
+ * Open the Spaces overview.
179
+ *
180
+ * The panel is a real Chrome app window (`--app`): no tab strip, no toolbar, its
181
+ * own app_id. Chrome routes the request to the already-running instance because
182
+ * the profile matches, so this adds a window rather than a second browser.
183
+ */
184
+ async function openSpaces() {
185
+ const running = await liveSpacesServer();
186
+
187
+ // A running daemon already owns a window; ask it for another one. A cold start
188
+ // opens its own, so opening one here too would give you two.
189
+ if (running) {
190
+ await openPanelWindow(`http://127.0.0.1:${running}/`);
191
+ process.stderr.write(`Spaces panel: http://127.0.0.1:${running}/\n`);
192
+ return 0;
193
+ }
194
+
195
+ spawn(process.execPath, [fileURLToPath(import.meta.url), "--spaces-daemon"], {
196
+ detached: true,
197
+ stdio: "ignore",
198
+ }).unref();
199
+
200
+ let port = null;
201
+ const deadline = Date.now() + 30000;
202
+ while (!port && Date.now() < deadline) {
203
+ await new Promise((resolve) => setTimeout(resolve, 400));
204
+ port = await liveSpacesServer();
205
+ }
206
+ if (!port) {
207
+ process.stderr.write("the Spaces server did not come up\n");
208
+ return 1;
209
+ }
210
+
211
+ process.stderr.write(`Spaces panel: http://127.0.0.1:${port}/\n`);
212
+ return 0;
213
+ }
214
+
215
+ /**
216
+ * Sweep spaces that hold nothing but about:blank.
217
+ *
218
+ * The automatic sweep in reconcile only touches spaces stamped with a creation
219
+ * time, so it cannot reach the drift left behind before that existed — and a
220
+ * user staring at twenty empty windows wants them gone now, not in two minutes.
221
+ * Explicitly invoked, so it ignores age and asks no questions.
222
+ */
223
+ async function pruneSpaces() {
224
+ // Maintenance must never be the thing that opens a browser. Forcing a headed
225
+ // launch here meant running the sweep on a quiet machine started a visible
226
+ // window — producing exactly the empty windows it exists to clear.
227
+ const status = await browserStatus();
228
+ if (!status.running) {
229
+ process.stdout.write("no backing browser is running; nothing to prune\n");
230
+ return 0;
231
+ }
232
+ const shim = await createEgoShim({ headless: status.headless === true });
233
+ try {
234
+ const { taskSpaces = [] } = await shim.ego.listTaskSpaces();
235
+ // The selected space is the one an agent is working in right now, and its
236
+ // tab is about:blank for a moment on every navigation. Closing it would
237
+ // take the agent's context out from under it mid-task.
238
+ let selectedId = null;
239
+ try {
240
+ ({ selectedId = null } = JSON.parse(await readFile(TASK_SPACE_FILE, "utf8")));
241
+ } catch {
242
+ // No state file means no selection to protect.
243
+ }
244
+ const { targetInfos = [] } = await shim.cdp.call("Target.getTargets");
245
+ const byTarget = new Map(targetInfos.map((target) => [target.targetId, target]));
246
+
247
+ let closed = 0;
248
+ for (const space of taskSpaces) {
249
+ const tabs = (space.targetIds || []).map((id) => byTarget.get(id)).filter(Boolean);
250
+ if (tabs.length === 0) continue;
251
+ if (space.id === selectedId) continue;
252
+ if (space.lastContentAt) continue;
253
+ if (!tabs.every((target) => target.url === "about:blank")) continue;
254
+ await shim.ego.closeTaskSpace(space.id).then(
255
+ () => {
256
+ closed += 1;
257
+ },
258
+ () => {},
259
+ );
260
+ }
261
+ process.stdout.write(
262
+ closed === 0
263
+ ? "no empty spaces to close\n"
264
+ : `closed ${closed} empty ${closed === 1 ? "space" : "spaces"}\n`,
265
+ );
266
+ } finally {
267
+ shim.close();
268
+ }
269
+ return 0;
270
+ }
271
+
272
+ async function main() {
273
+ const argv = process.argv.slice(2);
274
+
275
+ // The skill documents `ego-browser nodejs <<'EOF'`; accept it as a no-op prefix.
276
+ if (argv[0] === "nodejs") argv.shift();
277
+
278
+ if (argv[0] === "--help" || argv[0] === "-h") {
279
+ process.stdout.write(USAGE);
280
+ return 0;
281
+ }
282
+ if (argv[0] === "--status") {
283
+ process.stdout.write(`${JSON.stringify(await browserStatus(), null, 2)}\n`);
284
+ return 0;
285
+ }
286
+ if (argv[0] === "--stop") {
287
+ const stopped = await stopBrowser();
288
+ process.stdout.write(
289
+ stopped
290
+ ? "backing browser stopped; the next run launches a fresh one\n"
291
+ : "no backing browser was running; profile lock cleared\n",
292
+ );
293
+ return 0;
294
+ }
295
+ if (argv[0] === "--import-chrome-profile") {
296
+ return importChromeProfile();
297
+ }
298
+ if (argv[0] === "--prune-spaces") {
299
+ return pruneSpaces();
300
+ }
301
+ if (argv[0] === "--spaces") {
302
+ return openSpaces();
303
+ }
304
+ if (argv[0] === "--spaces-daemon") {
305
+ return runSpacesDaemon();
306
+ }
307
+ if (argv[0] === "--install-desktop-entry") {
308
+ const { entryPath, iconPath } = await installDesktopEntry();
309
+ process.stdout.write(`installed ${entryPath}\n ${iconPath}\n`);
310
+ return 0;
311
+ }
312
+ if (argv[0] === "--open") {
313
+ // Launched from a desktop icon there is no terminal to read an error in, so
314
+ // this has to succeed rather than explain. A headless browser has no window
315
+ // to show, so trade it for a visible one.
316
+ const status = await browserStatus();
317
+ if (status.running && status.headless) {
318
+ process.stderr.write("replacing the headless browser with a visible one\n");
319
+ await stopBrowser();
320
+ }
321
+ const shim = await createEgoShim({ headless: false });
322
+ try {
323
+ const { tabs } = await shim.ego.listTabs();
324
+ // A browser with no page target shows no window; give it one.
325
+ let targetId = tabs.find((tab) => tab.active)?.targetId ?? tabs[0]?.targetId;
326
+ if (!targetId) ({ targetId } = await shim.ego.createTab("about:blank"));
327
+
328
+ // The window usually already exists — it is just behind everything else.
329
+ // Clicking a launcher icon has to raise it, not quietly confirm it is
330
+ // running, which looks identical to nothing happening.
331
+ await shim.cdp.call("Target.activateTarget", { targetId }).catch(() => {});
332
+ const { sessionId } = await shim.cdp.call("Target.attachToTarget", {
333
+ targetId,
334
+ flatten: true,
335
+ });
336
+ await shim.cdp.call("Page.bringToFront", {}, sessionId).catch(() => {});
337
+ } finally {
338
+ shim.close();
339
+ }
340
+ return 0;
341
+ }
342
+
343
+ // EGO_LINUX_HEADLESS is for a machine whose owner does not want the agent
344
+ // window in front of their work (or a box with no display at all). When a
345
+ // usable X display is present (e.g. an Xvfb), run headed so the compositor
346
+ // produces full-rate screencast frames for the watch panel — headless would
347
+ // fall back to swiftshader (~1 fps). --headless still forces headless per run.
348
+ // Windows always "has a display" (the desktop session; see ensureXDisplay's
349
+ // win32 branch) — without this the post-#22 default flipped headed cold
350
+ // starts into an Xvfb lookup that can never succeed there.
351
+ const hasDisplay =
352
+ process.platform === "win32" || (process.env.DISPLAY || "").trim() !== "";
353
+ // An explicit EGO_LINUX_HEADLESS=1 always wins — even on Windows, where
354
+ // hasDisplay is hard-coded true (issue #35: the variable used to be silently
355
+ // ignored there). The display probe only decides when the variable is unset.
356
+ const headlessEnv = (process.env.EGO_LINUX_HEADLESS ?? "").toLowerCase();
357
+ const envHeadless = ["1", "true", "yes", "on"].includes(headlessEnv)
358
+ ? true
359
+ : hasDisplay
360
+ ? false
361
+ : !["", "0", "false", "no"].includes(headlessEnv);
362
+ const headless = argv.includes("--headless") || envHeadless;
363
+ const rest = argv.filter((arg) => arg !== "--headless");
364
+
365
+ // `--sdk-path <file>` selects which harness bundle to run. Upstream's real
366
+ // browser e2e runner passes it to test a local build; here the local build is
367
+ // the only harness there is, so honour the path it names.
368
+ let harness = HARNESS.href;
369
+ const sdkFlag = rest.indexOf("--sdk-path");
370
+ if (sdkFlag !== -1) {
371
+ const path = rest[sdkFlag + 1];
372
+ if (!path) {
373
+ process.stderr.write("--sdk-path requires a path\n");
374
+ return 2;
375
+ }
376
+ harness = pathToFileURL(path).href;
377
+ rest.splice(sdkFlag, 2);
378
+ }
379
+
380
+ // Site skills and learnings live in the repo's skill directory.
381
+ process.env.EGO_BROWSER_AGENT_WORKSPACE ||= SKILL_WORKSPACE.pathname;
382
+
383
+ const shim = await createEgoShim({ headless });
384
+ globalThis.ego = shim.ego;
385
+
386
+ const { runMain } = await import(harness);
387
+ try {
388
+ return await runMain({ argv: rest });
389
+ } finally {
390
+ shim.close();
391
+ }
392
+ }
393
+
394
+ main()
395
+ .then((code) => process.exit(code ?? 0))
396
+ .catch((error) => {
397
+ process.stderr.write(`${error?.stack || error}\n`);
398
+ process.exit(1);
399
+ });
@@ -0,0 +1,65 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ /**
5
+ * Who is opening this space.
6
+ *
7
+ * The panel's right-hand label mirrors the native Space category ("Personal",
8
+ * "Work"). On a cue-managed machine the useful equivalent is the agent profile
9
+ * that opened the space, so a glance at the overview answers "which of my agents
10
+ * is doing this" rather than just "an agent is".
11
+ *
12
+ * Read at creation time, from the environment of the process that ran the
13
+ * heredoc — the browser itself has no idea who is driving it.
14
+ */
15
+
16
+ const RUNTIME_MARKER = "/.config/cue/runtime/";
17
+
18
+ /** cue launches its sessions against a per-profile runtime directory. */
19
+ function profileFromEnvironment() {
20
+ for (const value of Object.values(process.env)) {
21
+ if (typeof value !== "string") continue;
22
+ const at = value.indexOf(RUNTIME_MARKER);
23
+ if (at === -1) continue;
24
+ const rest = value.slice(at + RUNTIME_MARKER.length);
25
+ const name = rest.split("/")[0];
26
+ if (name) return name;
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /** Directories can pin a profile; walk up like cue itself does. */
32
+ function profileFromPinFile(startDir) {
33
+ let dir = startDir;
34
+ for (let depth = 0; depth < 12; depth += 1) {
35
+ const pin = join(dir, ".cue.profile");
36
+ if (existsSync(pin)) {
37
+ try {
38
+ const name = readFileSync(pin, "utf8").trim();
39
+ if (name) return name;
40
+ } catch {
41
+ // unreadable pin is the same as no pin
42
+ }
43
+ }
44
+ const parent = dirname(dir);
45
+ if (parent === dir) break;
46
+ dir = parent;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ export function agentIdentity(cwd = process.cwd()) {
52
+ // The Spaces panel's own daemon inherits the environment of whichever session
53
+ // happened to start it. A space you create by hand from the panel is yours,
54
+ // not that profile's, so the daemon opts out of attribution entirely.
55
+ if (process.env.EGO_LINUX_PANEL === "1") {
56
+ return { profile: null, session: null };
57
+ }
58
+ const profile = profileFromEnvironment() || profileFromPinFile(cwd) || null;
59
+ const session = process.env.CLAUDE_CODE_SESSION_ID || null;
60
+ return {
61
+ profile,
62
+ // Enough to tell two concurrent sessions apart without being a wall of hex.
63
+ session: session ? session.slice(0, 8) : null,
64
+ };
65
+ }