pi-feats 0.1.2 → 0.1.4
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/README.md +24 -1
- package/THIRD_PARTY_NOTICES.md +12 -0
- package/assets/pi-feats-preview.png +0 -0
- package/extensions/api-server/application-log-store.ts +31 -0
- package/extensions/api-server/application-runtime.ts +80 -18
- package/extensions/api-server/application-store.ts +6 -2
- package/extensions/api-server/profile-store.ts +47 -20
- package/extensions/api-server/server.ts +182 -47
- package/extensions/browser-harness/cdp/commands.ts +260 -0
- package/extensions/browser-harness/cdp/console-buffer.ts +188 -0
- package/extensions/browser-harness/cdp/discovery.ts +198 -0
- package/extensions/browser-harness/cdp/errors.ts +23 -0
- package/extensions/browser-harness/cdp/events.ts +170 -0
- package/extensions/browser-harness/cdp/network-buffer.ts +146 -0
- package/extensions/browser-harness/cdp/ownership.ts +73 -0
- package/extensions/browser-harness/cdp/record-store.ts +61 -0
- package/extensions/browser-harness/cdp/session.ts +403 -0
- package/extensions/browser-harness/cdp/steel-transport.ts +151 -0
- package/extensions/browser-harness/cdp/target-factory.ts +153 -0
- package/extensions/browser-harness/cdp/types.ts +82 -0
- package/extensions/browser-harness/client.ts +366 -0
- package/extensions/browser-harness/daemon/bridge.ts +531 -0
- package/extensions/browser-harness/daemon/index.ts +86 -0
- package/extensions/browser-harness/daemon/protocol.ts +110 -0
- package/extensions/browser-harness/daemon/queue.ts +85 -0
- package/extensions/browser-harness/daemon/server.ts +170 -0
- package/extensions/browser-harness/daemon/spawn.ts +124 -0
- package/extensions/browser-harness/daemon/transport.ts +178 -0
- package/extensions/browser-harness/domains/ax-tree.ts +179 -0
- package/extensions/browser-harness/domains/box.ts +51 -0
- package/extensions/browser-harness/domains/cdp-call.ts +55 -0
- package/extensions/browser-harness/domains/click.ts +97 -0
- package/extensions/browser-harness/domains/console.ts +219 -0
- package/extensions/browser-harness/domains/dialog.ts +34 -0
- package/extensions/browser-harness/domains/drag.ts +67 -0
- package/extensions/browser-harness/domains/element-call.ts +117 -0
- package/extensions/browser-harness/domains/files.ts +219 -0
- package/extensions/browser-harness/domains/fill-engine.ts +80 -0
- package/extensions/browser-harness/domains/form-batch.ts +65 -0
- package/extensions/browser-harness/domains/form.ts +283 -0
- package/extensions/browser-harness/domains/headers.ts +89 -0
- package/extensions/browser-harness/domains/history.ts +80 -0
- package/extensions/browser-harness/domains/isolated-tab.ts +91 -0
- package/extensions/browser-harness/domains/js.ts +241 -0
- package/extensions/browser-harness/domains/keyboard.ts +197 -0
- package/extensions/browser-harness/domains/navigate.ts +161 -0
- package/extensions/browser-harness/domains/network.ts +301 -0
- package/extensions/browser-harness/domains/page.ts +154 -0
- package/extensions/browser-harness/domains/readpage/read-page.ts +174 -0
- package/extensions/browser-harness/domains/readpage/readability.ts +65 -0
- package/extensions/browser-harness/domains/ref-resolve.ts +118 -0
- package/extensions/browser-harness/domains/render.ts +43 -0
- package/extensions/browser-harness/domains/screenshot-capture.ts +80 -0
- package/extensions/browser-harness/domains/screenshot.ts +76 -0
- package/extensions/browser-harness/domains/scroll.ts +59 -0
- package/extensions/browser-harness/domains/search/google-serp.ts +85 -0
- package/extensions/browser-harness/domains/search/web-search.ts +144 -0
- package/extensions/browser-harness/domains/setup.ts +35 -0
- package/extensions/browser-harness/domains/snapshot.ts +256 -0
- package/extensions/browser-harness/domains/tabs.ts +202 -0
- package/extensions/browser-harness/domains/target.ts +35 -0
- package/extensions/browser-harness/domains/viewport.ts +42 -0
- package/extensions/browser-harness/index.ts +88 -0
- package/extensions/browser-harness/profile/bind.ts +90 -0
- package/extensions/browser-harness/profile/browser-process.ts +320 -0
- package/extensions/browser-harness/profile/command.ts +189 -0
- package/extensions/browser-harness/profile/launch.ts +80 -0
- package/extensions/browser-harness/profile/list.ts +131 -0
- package/extensions/browser-harness/profile/paths.ts +103 -0
- package/extensions/browser-harness/profile/store.ts +84 -0
- package/extensions/browser-harness/prompt.ts +16 -0
- package/extensions/browser-harness/registry.ts +80 -0
- package/extensions/browser-harness/schemas/common.ts +11 -0
- package/extensions/browser-harness/schemas/parse.ts +23 -0
- package/extensions/browser-harness/setup.ts +47 -0
- package/extensions/browser-harness/state.ts +51 -0
- package/extensions/browser-harness/steel.ts +215 -0
- package/extensions/browser-harness/util/debug.ts +8 -0
- package/extensions/browser-harness/util/guards.ts +30 -0
- package/extensions/browser-harness/util/js-template.ts +12 -0
- package/extensions/browser-harness/util/mutex.ts +20 -0
- package/extensions/browser-harness/util/paths.ts +31 -0
- package/extensions/browser-harness/util/result.ts +9 -0
- package/extensions/browser-harness/util/sharp-shim.ts +42 -0
- package/extensions/browser-harness/util/tool.ts +185 -0
- package/extensions/browser-harness/util/truncate.ts +41 -0
- package/extensions/cli-resources.ts +35 -16
- package/extensions/composio/index.ts +163 -0
- package/extensions/context-memory/index.ts +58 -0
- package/extensions/lib/application-context.ts +22 -0
- package/extensions/lib/application-handler-templates.ts +17 -1
- package/extensions/lib/context-memory.ts +165 -0
- package/extensions/lib/profile-sandbox.ts +3 -0
- package/extensions/lib/workflow-harness.ts +238 -0
- package/extensions/pi-console-webui/app/[section]/page.tsx +6 -1
- package/extensions/pi-console-webui/app/applications/[slug]/page.tsx +15 -0
- package/extensions/pi-console-webui/app/layout.tsx +6 -1
- package/extensions/pi-console-webui/app/login/page.tsx +5 -9
- package/extensions/pi-console-webui/app/not-found.tsx +5 -0
- package/extensions/pi-console-webui/app/page.tsx +6 -0
- package/extensions/pi-console-webui/app/terminal/page.tsx +3 -0
- package/extensions/pi-console-webui/components/application-handler-editor.tsx +4 -4
- package/extensions/pi-console-webui/components/application-logs.tsx +12 -8
- package/extensions/pi-console-webui/components/application-settings.tsx +5 -1
- package/extensions/pi-console-webui/components/chat-workspace.tsx +7 -4
- package/extensions/pi-console-webui/components/console-page.tsx +3 -1
- package/extensions/pi-console-webui/components/console.tsx +53 -7
- package/extensions/pi-console-webui/components/login-form.tsx +14 -0
- package/extensions/pi-console-webui/components/pulse-resources.tsx +10 -6
- package/extensions/pi-console-webui/components/skill-resources.tsx +3 -3
- package/extensions/pi-console-webui/lib/page-metadata.ts +33 -0
- package/extensions/profiles.ts +18 -7
- package/extensions/pulse/store.ts +5 -2
- package/extensions/sequential-workflow.ts +340 -256
- package/extensions/skill-sources/store.ts +24 -3
- package/licenses/pi-browser-harness-MIT.txt +21 -0
- package/package.json +25 -4
- package/schemas/sequential-workflow-template.schema.json +62 -0
- package/skills/browser-harness/SKILL.md +33 -0
- package/skills/composio-connections/SKILL.md +75 -0
- package/skills/sequential-workflow/SKILL.md +70 -0
- package/skills/sequential-workflow-template/SKILL.md +44 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { BrowserClient } from "../client";
|
|
2
|
+
import type { ResultOf } from "../cdp/commands";
|
|
3
|
+
import { type CdpError, cdpError } from "../cdp/errors";
|
|
4
|
+
import { type Result, err, ok } from "../util/result";
|
|
5
|
+
import { detectRunningBrowser, resolveBrowserExecutable } from "./browser-process";
|
|
6
|
+
import { openProfileWindow } from "./launch";
|
|
7
|
+
import type { ProfilePin } from "./store";
|
|
8
|
+
|
|
9
|
+
const SEED_DEADLINE_MS = 15_000;
|
|
10
|
+
const SEED_POLL_MS = 500;
|
|
11
|
+
|
|
12
|
+
type PageTarget = ResultOf<"Target.getTargets">["targetInfos"][number];
|
|
13
|
+
|
|
14
|
+
const pageTargets = async (client: BrowserClient): Promise<ReadonlyArray<PageTarget>> => {
|
|
15
|
+
const r = await client.session().callBrowser("Target.getTargets");
|
|
16
|
+
if (!r.success) return [];
|
|
17
|
+
return r.data.targetInfos.filter((t) => t.type === "page");
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const manualFallbackHint = (pin: ProfilePin): string =>
|
|
21
|
+
`open a window for "${pin.label}" yourself (browser profile menu → ${pin.profileDir}), then retry. ` +
|
|
22
|
+
`Run /browser-profile to pick a different profile, or clear the selection to use whichever window is focused.`;
|
|
23
|
+
|
|
24
|
+
export const seedProfileWindow = async (
|
|
25
|
+
client: BrowserClient,
|
|
26
|
+
pin: ProfilePin,
|
|
27
|
+
): Promise<Result<string, CdpError>> => {
|
|
28
|
+
const connectedDir = client.userDataDir();
|
|
29
|
+
if (connectedDir && connectedDir !== pin.userDataDir) {
|
|
30
|
+
return err(cdpError(
|
|
31
|
+
"discovery_failed",
|
|
32
|
+
`the selected profile "${pin.label}" belongs to ${pin.userDataDir}, but the harness is connected to ${connectedDir}. ` +
|
|
33
|
+
`Run /browser-profile to choose a profile in the browser you're using.`,
|
|
34
|
+
));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const targetUserDataDir = connectedDir ?? pin.userDataDir;
|
|
38
|
+
const running = await detectRunningBrowser(targetUserDataDir);
|
|
39
|
+
const exePath = await resolveBrowserExecutable(running);
|
|
40
|
+
if (!exePath) {
|
|
41
|
+
return err(cdpError(
|
|
42
|
+
"discovery_failed",
|
|
43
|
+
`could not locate the browser executable needed to open "${pin.label}" — ${manualFallbackHint(pin)}`,
|
|
44
|
+
));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const launched = await openProfileWindow({
|
|
48
|
+
exePath,
|
|
49
|
+
profileDir: pin.profileDir,
|
|
50
|
+
// ProcessSingleton keys on the user-data-dir path, so forward only the value the running browser reports: a reconstructed one may differ by case and start a SECOND browser.
|
|
51
|
+
...(running.explicitUserDataDir ? { explicitUserDataDir: running.explicitUserDataDir } : {}),
|
|
52
|
+
});
|
|
53
|
+
if (!launched.success) {
|
|
54
|
+
return err(cdpError("discovery_failed", `${launched.error} — ${manualFallbackHint(pin)}`));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const { sentinelUrl, cleanup, kill } = launched.data;
|
|
58
|
+
const deadline = Date.now() + SEED_DEADLINE_MS;
|
|
59
|
+
let seed: PageTarget | undefined;
|
|
60
|
+
while (Date.now() < deadline && !seed) {
|
|
61
|
+
await new Promise((r) => setTimeout(r, SEED_POLL_MS));
|
|
62
|
+
seed = (await pageTargets(client)).find((t) => t.url === sentinelUrl);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (!seed) {
|
|
66
|
+
kill();
|
|
67
|
+
await cleanup();
|
|
68
|
+
return err(cdpError(
|
|
69
|
+
"timeout",
|
|
70
|
+
`couldn't open a window in "${pin.label}" automatically — ${manualFallbackHint(pin)}`,
|
|
71
|
+
));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The sentinel's context is the profile's context — the only way to learn it.
|
|
75
|
+
if (seed.browserContextId) client.setProfileContextId(seed.browserContextId);
|
|
76
|
+
|
|
77
|
+
const ownership = client.ownership();
|
|
78
|
+
ownership.setHarnessWindow(seed.targetId);
|
|
79
|
+
ownership.add(seed.targetId);
|
|
80
|
+
const win = await client.session().windowId(seed.targetId);
|
|
81
|
+
if (win.success) ownership.setHarnessWindowId(win.data);
|
|
82
|
+
|
|
83
|
+
const attached = await client.session().attach(seed.targetId);
|
|
84
|
+
if (attached.success) {
|
|
85
|
+
await client.session().callOnTarget("Page.navigate", { url: "about:blank" }, attached.data);
|
|
86
|
+
}
|
|
87
|
+
await cleanup();
|
|
88
|
+
|
|
89
|
+
return ok(seed.targetId);
|
|
90
|
+
};
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// `running` is derived only from live-process evidence: an installed-but-closed browser must read as "not running".
|
|
2
|
+
// `wmic` is deliberately unused — Microsoft removed it by default in Windows 11 24H2 and entirely in 25H2, so PowerShell CIM plus tasklist replace it.
|
|
3
|
+
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { access, readFile, readlink } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import { Type } from "typebox";
|
|
9
|
+
import { Compile } from "typebox/compile";
|
|
10
|
+
import { parseJson } from "../schemas/parse";
|
|
11
|
+
import { browserNameForUserDataDir } from "./paths";
|
|
12
|
+
|
|
13
|
+
const run = promisify(execFile);
|
|
14
|
+
const EXEC_TIMEOUT_MS = 5_000;
|
|
15
|
+
|
|
16
|
+
export type RunningBrowser = {
|
|
17
|
+
readonly running: boolean;
|
|
18
|
+
readonly exePath?: string;
|
|
19
|
+
readonly explicitUserDataDir?: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const LINUX_COMMS: ReadonlyArray<string> = [
|
|
23
|
+
"chrome", "chromium", "chromium-browser", "msedge", "microsoft-edge",
|
|
24
|
+
"google-chrome", "brave", "brave-browser",
|
|
25
|
+
];
|
|
26
|
+
const MAC_BROWSER_NAMES: ReadonlyArray<string> = [
|
|
27
|
+
"google chrome", "chromium", "microsoft edge", "brave browser",
|
|
28
|
+
];
|
|
29
|
+
const WIN_IMAGE_NAMES: ReadonlyArray<string> = ["chrome.exe", "msedge.exe", "brave.exe"];
|
|
30
|
+
|
|
31
|
+
// Match the `--type=` flag, not words like "renderer" anywhere in the string, or an install path containing one is filtered out.
|
|
32
|
+
const hasChildProcessType = (commandLine: string): boolean => {
|
|
33
|
+
const lower = commandLine.toLowerCase();
|
|
34
|
+
return lower.includes("--type=") && !lower.includes("--type=browser");
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// macOS names its child processes in the executable path itself, so the process NAME must be filtered too.
|
|
38
|
+
const isMacChildProcessName = (comm: string): boolean => {
|
|
39
|
+
const lower = comm.toLowerCase();
|
|
40
|
+
return (
|
|
41
|
+
lower.includes("helper") ||
|
|
42
|
+
lower.includes("renderer") ||
|
|
43
|
+
lower.includes("crashpad") ||
|
|
44
|
+
lower.includes(" gpu") ||
|
|
45
|
+
lower.includes("updater")
|
|
46
|
+
);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type BrowserCandidate = {
|
|
50
|
+
readonly exePath?: string;
|
|
51
|
+
readonly explicitUserDataDir?: string;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// A package upgrade under a running browser makes `/proc/<pid>/exe` read "… (deleted)", which fails to spawn with ENOENT unless the marker comes off.
|
|
55
|
+
const DELETED_SUFFIX = " (deleted)";
|
|
56
|
+
|
|
57
|
+
export const stripDeletedSuffix = (path: string): string | undefined =>
|
|
58
|
+
path.endsWith(DELETED_SUFFIX) && path.length > DELETED_SUFFIX.length
|
|
59
|
+
? path.slice(0, -DELETED_SUFFIX.length)
|
|
60
|
+
: undefined;
|
|
61
|
+
|
|
62
|
+
const exists = async (path: string): Promise<boolean> => {
|
|
63
|
+
try {
|
|
64
|
+
await access(path);
|
|
65
|
+
return true;
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export const spawnableExePath = async (raw: string): Promise<string | undefined> => {
|
|
72
|
+
if (raw.length === 0) return undefined;
|
|
73
|
+
if (await exists(raw)) return raw;
|
|
74
|
+
const stripped = stripDeletedSuffix(raw);
|
|
75
|
+
if (stripped && (await exists(stripped))) return stripped;
|
|
76
|
+
return undefined;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const samePath = (a: string, b: string): boolean => {
|
|
80
|
+
const norm = (p: string): string => {
|
|
81
|
+
const unified = p.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
82
|
+
return process.platform === "linux" ? unified : unified.toLowerCase();
|
|
83
|
+
};
|
|
84
|
+
return norm(a) === norm(b);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export const rankBrowserCandidate = (candidate: BrowserCandidate, preferUserDataDir?: string): number => {
|
|
88
|
+
if (!preferUserDataDir) return 1;
|
|
89
|
+
if (candidate.explicitUserDataDir) {
|
|
90
|
+
return samePath(candidate.explicitUserDataDir, preferUserDataDir) ? 4 : 0;
|
|
91
|
+
}
|
|
92
|
+
const family = browserNameForUserDataDir(preferUserDataDir).toLowerCase();
|
|
93
|
+
const exe = (candidate.exePath ?? "").toLowerCase();
|
|
94
|
+
if (!exe) return 1;
|
|
95
|
+
if (family === "brave" && exe.includes("brave")) return 3;
|
|
96
|
+
if (family === "edge" && (exe.includes("edge") || exe.includes("msedge"))) return 3;
|
|
97
|
+
if (family === "chromium" && exe.includes("chromium")) return 3;
|
|
98
|
+
if (family === "chrome" && exe.includes("chrome") && !exe.includes("chromium")) return 3;
|
|
99
|
+
return 1;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export const parseUserDataDirFlag = (commandLine: string): string | undefined => {
|
|
103
|
+
const match = /--user-data-dir=(?:"([^"]*)"|'([^']*)'|(\S+))/.exec(commandLine);
|
|
104
|
+
if (!match) return undefined;
|
|
105
|
+
const value = match[1] ?? match[2] ?? match[3];
|
|
106
|
+
return value && value.length > 0 ? value : undefined;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const collectLinux = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
110
|
+
let pids: string[];
|
|
111
|
+
try {
|
|
112
|
+
const { stdout } = await run("ps", ["-A", "-o", "pid=,comm="], { timeout: EXEC_TIMEOUT_MS });
|
|
113
|
+
pids = stdout
|
|
114
|
+
.split("\n")
|
|
115
|
+
.map((line) => line.trim())
|
|
116
|
+
.flatMap((line) => {
|
|
117
|
+
const [pid, comm] = line.split(/\s+/, 2);
|
|
118
|
+
if (!pid || !comm) return [];
|
|
119
|
+
return LINUX_COMMS.includes(comm.toLowerCase()) ? [pid] : [];
|
|
120
|
+
});
|
|
121
|
+
} catch {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const candidates: BrowserCandidate[] = [];
|
|
126
|
+
for (const pid of pids) {
|
|
127
|
+
let cmdline: string;
|
|
128
|
+
try {
|
|
129
|
+
cmdline = (await readFile(`/proc/${pid}/cmdline`, "utf8")).replace(/\0/g, " ").trim();
|
|
130
|
+
} catch {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (!cmdline || hasChildProcessType(cmdline)) continue;
|
|
134
|
+
let link: string | undefined;
|
|
135
|
+
try {
|
|
136
|
+
link = await readlink(`/proc/${pid}/exe`);
|
|
137
|
+
} catch {}
|
|
138
|
+
// Chrome rewrites its argv to the bare executable path, so argv[0] is the live install location when /proc/<pid>/exe is unreadable or stale.
|
|
139
|
+
const exePath =
|
|
140
|
+
(link ? await spawnableExePath(link) : undefined) ??
|
|
141
|
+
(await spawnableExePath(cmdline.split(" ")[0] ?? ""));
|
|
142
|
+
const explicit = parseUserDataDirFlag(cmdline);
|
|
143
|
+
candidates.push({
|
|
144
|
+
...(exePath ? { exePath } : {}),
|
|
145
|
+
...(explicit ? { explicitUserDataDir: explicit } : {}),
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return candidates;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const collectDarwin = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
152
|
+
let lines: string[];
|
|
153
|
+
try {
|
|
154
|
+
// BSD ps prints the full executable path for `comm`, unlike Linux.
|
|
155
|
+
const { stdout } = await run("ps", ["-A", "-ww", "-o", "pid=,comm="], { timeout: EXEC_TIMEOUT_MS });
|
|
156
|
+
lines = stdout.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
157
|
+
} catch {
|
|
158
|
+
return [];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const candidates: BrowserCandidate[] = [];
|
|
162
|
+
for (const line of lines) {
|
|
163
|
+
const spaceAt = line.indexOf(" ");
|
|
164
|
+
if (spaceAt < 0) continue;
|
|
165
|
+
const pid = line.slice(0, spaceAt);
|
|
166
|
+
const comm = line.slice(spaceAt + 1).trim();
|
|
167
|
+
const lower = comm.toLowerCase();
|
|
168
|
+
if (!MAC_BROWSER_NAMES.some((name) => lower.includes(name))) continue;
|
|
169
|
+
if (isMacChildProcessName(comm)) continue;
|
|
170
|
+
|
|
171
|
+
let args = "";
|
|
172
|
+
try {
|
|
173
|
+
const { stdout } = await run("ps", ["-ww", "-o", "args=", "-p", pid], { timeout: EXEC_TIMEOUT_MS });
|
|
174
|
+
args = stdout.trim();
|
|
175
|
+
} catch {}
|
|
176
|
+
if (args && hasChildProcessType(args)) continue;
|
|
177
|
+
const explicit = args ? parseUserDataDirFlag(args) : undefined;
|
|
178
|
+
candidates.push({
|
|
179
|
+
exePath: comm,
|
|
180
|
+
...(explicit ? { explicitUserDataDir: explicit } : {}),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return candidates;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const POWERSHELL_QUERY = [
|
|
187
|
+
"$ErrorActionPreference='SilentlyContinue';",
|
|
188
|
+
"Get-CimInstance Win32_Process",
|
|
189
|
+
"-Filter \"Name='chrome.exe' or Name='msedge.exe' or Name='brave.exe'\"",
|
|
190
|
+
"| Select-Object ExecutablePath,CommandLine",
|
|
191
|
+
"| ConvertTo-Json -Compress",
|
|
192
|
+
].join(" ");
|
|
193
|
+
|
|
194
|
+
const WinProcessSchema = Type.Object(
|
|
195
|
+
{
|
|
196
|
+
ExecutablePath: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
|
197
|
+
CommandLine: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
|
198
|
+
},
|
|
199
|
+
{ additionalProperties: true },
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
const WinProcessesSchema = Type.Union([WinProcessSchema, Type.Array(WinProcessSchema)]);
|
|
203
|
+
|
|
204
|
+
const winProcessesValidator = Compile(WinProcessesSchema);
|
|
205
|
+
|
|
206
|
+
const collectWin32 = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
207
|
+
try {
|
|
208
|
+
const { stdout } = await run(
|
|
209
|
+
"powershell.exe",
|
|
210
|
+
["-NoProfile", "-NonInteractive", "-Command", POWERSHELL_QUERY],
|
|
211
|
+
{ timeout: EXEC_TIMEOUT_MS, windowsHide: true },
|
|
212
|
+
);
|
|
213
|
+
const trimmed = stdout.trim();
|
|
214
|
+
if (trimmed) {
|
|
215
|
+
const parsed = parseJson(trimmed, winProcessesValidator);
|
|
216
|
+
if (parsed.success) {
|
|
217
|
+
const rows = Array.isArray(parsed.data) ? parsed.data : [parsed.data];
|
|
218
|
+
const candidates = rows
|
|
219
|
+
.filter((row) => !hasChildProcessType(row.CommandLine ?? ""))
|
|
220
|
+
.map((row): BrowserCandidate => {
|
|
221
|
+
const explicit = parseUserDataDirFlag(row.CommandLine ?? "");
|
|
222
|
+
return {
|
|
223
|
+
...(row.ExecutablePath ? { exePath: row.ExecutablePath } : {}),
|
|
224
|
+
...(explicit ? { explicitUserDataDir: explicit } : {}),
|
|
225
|
+
};
|
|
226
|
+
});
|
|
227
|
+
if (candidates.length > 0) return candidates;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch {}
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
const { stdout } = await run("tasklist.exe", [], { timeout: EXEC_TIMEOUT_MS, windowsHide: true });
|
|
234
|
+
const lower = stdout.toLowerCase();
|
|
235
|
+
if (WIN_IMAGE_NAMES.some((n) => lower.includes(n))) return [{}];
|
|
236
|
+
} catch {}
|
|
237
|
+
return [];
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
const winInstallCandidates = (): ReadonlyArray<string> => {
|
|
241
|
+
const roots = [
|
|
242
|
+
process.env["PROGRAMFILES"],
|
|
243
|
+
process.env["PROGRAMFILES(X86)"],
|
|
244
|
+
process.env["LOCALAPPDATA"],
|
|
245
|
+
].filter((r): r is string => typeof r === "string" && r.length > 0);
|
|
246
|
+
const suffixes = [
|
|
247
|
+
"Google\\Chrome\\Application\\chrome.exe",
|
|
248
|
+
"Google\\Chrome Beta\\Application\\chrome.exe",
|
|
249
|
+
"Google\\Chrome SxS\\Application\\chrome.exe",
|
|
250
|
+
"Chromium\\Application\\chrome.exe",
|
|
251
|
+
"BraveSoftware\\Brave-Browser\\Application\\brave.exe",
|
|
252
|
+
"Microsoft\\Edge\\Application\\msedge.exe",
|
|
253
|
+
];
|
|
254
|
+
return roots.flatMap((root) => suffixes.map((suffix) => join(root, suffix)));
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const winRegistryExecutable = async (): Promise<string | undefined> => {
|
|
258
|
+
for (const image of WIN_IMAGE_NAMES) {
|
|
259
|
+
for (const hive of ["HKLM", "HKCU"]) {
|
|
260
|
+
try {
|
|
261
|
+
const { stdout } = await run(
|
|
262
|
+
"reg.exe",
|
|
263
|
+
["query", `${hive}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${image}`, "/ve"],
|
|
264
|
+
{ timeout: EXEC_TIMEOUT_MS, windowsHide: true },
|
|
265
|
+
);
|
|
266
|
+
const match = /REG_[A-Z_]+\s+(.+)$/m.exec(stdout.trim());
|
|
267
|
+
const path = match?.[1]?.trim();
|
|
268
|
+
if (path) return path;
|
|
269
|
+
} catch {}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return undefined;
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
export const detectRunningBrowser = async (preferUserDataDir?: string): Promise<RunningBrowser> => {
|
|
276
|
+
const candidates =
|
|
277
|
+
process.platform === "darwin"
|
|
278
|
+
? await collectDarwin()
|
|
279
|
+
: process.platform === "win32"
|
|
280
|
+
? await collectWin32()
|
|
281
|
+
: await collectLinux();
|
|
282
|
+
if (candidates.length === 0) return { running: false };
|
|
283
|
+
|
|
284
|
+
const [first, ...rest] = candidates;
|
|
285
|
+
if (!first) return { running: false };
|
|
286
|
+
let best = first;
|
|
287
|
+
let bestRank = rankBrowserCandidate(best, preferUserDataDir);
|
|
288
|
+
for (const candidate of rest) {
|
|
289
|
+
const rank = rankBrowserCandidate(candidate, preferUserDataDir);
|
|
290
|
+
if (rank > bestRank) {
|
|
291
|
+
best = candidate;
|
|
292
|
+
bestRank = rank;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
running: true,
|
|
298
|
+
...(best.exePath ? { exePath: best.exePath } : {}),
|
|
299
|
+
...(best.explicitUserDataDir ? { explicitUserDataDir: best.explicitUserDataDir } : {}),
|
|
300
|
+
};
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
export const isBrowserRunning = async (): Promise<boolean> => (await detectRunningBrowser()).running;
|
|
304
|
+
|
|
305
|
+
export const resolveBrowserExecutable = async (running?: RunningBrowser): Promise<string | undefined> => {
|
|
306
|
+
const detected = running ?? (await detectRunningBrowser());
|
|
307
|
+
const usable = detected.exePath ? await spawnableExePath(detected.exePath) : undefined;
|
|
308
|
+
if (usable) return usable;
|
|
309
|
+
if (process.platform !== "win32") return undefined;
|
|
310
|
+
|
|
311
|
+
const fromRegistry = await winRegistryExecutable();
|
|
312
|
+
if (fromRegistry) return fromRegistry;
|
|
313
|
+
for (const candidate of winInstallCandidates()) {
|
|
314
|
+
try {
|
|
315
|
+
await access(candidate);
|
|
316
|
+
return candidate;
|
|
317
|
+
} catch {}
|
|
318
|
+
}
|
|
319
|
+
return undefined;
|
|
320
|
+
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { BrowserClient } from "../client";
|
|
3
|
+
import { discoverEndpoint } from "../cdp/discovery";
|
|
4
|
+
import { type Result, err, ok } from "../util/result";
|
|
5
|
+
import { type BrowserProfile, listProfiles } from "./list";
|
|
6
|
+
import { browserNameForUserDataDir, userDataDirCandidates } from "./paths";
|
|
7
|
+
import { clearPin, type ProfilePin, readPin, writePin } from "./store";
|
|
8
|
+
|
|
9
|
+
// `ctx.ui.select` resolves to undefined both on Escape and in non-interactive modes, so "no answer" must mean "change nothing".
|
|
10
|
+
|
|
11
|
+
const CLEAR_SELECTION_LABEL = "— Clear selection (use whichever window is focused) —";
|
|
12
|
+
|
|
13
|
+
type ProfileChoice =
|
|
14
|
+
| { readonly kind: "profile"; readonly profile: BrowserProfile }
|
|
15
|
+
| { readonly kind: "clear" }
|
|
16
|
+
| { readonly kind: "cancelled" };
|
|
17
|
+
|
|
18
|
+
const disambiguate = (profiles: ReadonlyArray<BrowserProfile>): ReadonlyArray<string> => {
|
|
19
|
+
const counts = new Map<string, number>();
|
|
20
|
+
for (const p of profiles) counts.set(p.label, (counts.get(p.label) ?? 0) + 1);
|
|
21
|
+
return profiles.map((p) => ((counts.get(p.label) ?? 0) > 1 ? `${p.label} [${p.dir}]` : p.label));
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const promptForProfile = async (
|
|
25
|
+
ctx: ExtensionContext,
|
|
26
|
+
profiles: ReadonlyArray<BrowserProfile>,
|
|
27
|
+
currentPin: ProfilePin | null,
|
|
28
|
+
title = "Select browser profile",
|
|
29
|
+
): Promise<ProfileChoice> => {
|
|
30
|
+
if (!ctx.hasUI || profiles.length === 0) return { kind: "cancelled" };
|
|
31
|
+
|
|
32
|
+
const labels = disambiguate(profiles);
|
|
33
|
+
const rows = labels.map((label, i) => {
|
|
34
|
+
const isPinned = currentPin?.profileDir === profiles[i]?.dir;
|
|
35
|
+
return isPinned ? `✓ ${label}` : ` ${label}`;
|
|
36
|
+
});
|
|
37
|
+
const options = [...rows, CLEAR_SELECTION_LABEL];
|
|
38
|
+
|
|
39
|
+
const answer = await ctx.ui.select(title, options);
|
|
40
|
+
if (answer === undefined) return { kind: "cancelled" };
|
|
41
|
+
if (answer === CLEAR_SELECTION_LABEL) return { kind: "clear" };
|
|
42
|
+
|
|
43
|
+
const index = options.indexOf(answer);
|
|
44
|
+
const profile = index >= 0 ? profiles[index] : undefined;
|
|
45
|
+
if (!profile) return { kind: "cancelled" };
|
|
46
|
+
return { kind: "profile", profile };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const pinFor = (userDataDir: string, profile: BrowserProfile): ProfilePin => ({
|
|
50
|
+
userDataDir,
|
|
51
|
+
profileDir: profile.dir,
|
|
52
|
+
label: profile.label,
|
|
53
|
+
savedAt: new Date().toISOString(),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const resolveUserDataDir = async (client: BrowserClient): Promise<Result<string, string>> => {
|
|
57
|
+
const connected = client.userDataDir();
|
|
58
|
+
if (connected) return ok(connected);
|
|
59
|
+
|
|
60
|
+
const endpoint = await discoverEndpoint();
|
|
61
|
+
if (endpoint.success && endpoint.data.userDataDir) return ok(endpoint.data.userDataDir);
|
|
62
|
+
|
|
63
|
+
const withProfiles: string[] = [];
|
|
64
|
+
for (const dir of userDataDirCandidates()) {
|
|
65
|
+
if ((await listProfiles(dir)).length > 0) withProfiles.push(dir);
|
|
66
|
+
}
|
|
67
|
+
const only = withProfiles[0];
|
|
68
|
+
if (withProfiles.length === 1 && only !== undefined) return ok(only);
|
|
69
|
+
if (withProfiles.length === 0) {
|
|
70
|
+
return err("No browser profiles found on this machine. Open Chrome, Brave, or Edge and try again.");
|
|
71
|
+
}
|
|
72
|
+
return err(
|
|
73
|
+
`Found profiles for more than one browser (${withProfiles.map(browserNameForUserDataDir).join(", ")}). ` +
|
|
74
|
+
"Open the browser you want the agent to use, then run /browser-profile again.",
|
|
75
|
+
);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const loadProfiles = async (
|
|
79
|
+
client: BrowserClient,
|
|
80
|
+
): Promise<Result<{ userDataDir: string; profiles: ReadonlyArray<BrowserProfile> }, string>> => {
|
|
81
|
+
const dir = await resolveUserDataDir(client);
|
|
82
|
+
if (!dir.success) return dir;
|
|
83
|
+
const profiles = await listProfiles(dir.data);
|
|
84
|
+
if (profiles.length === 0) {
|
|
85
|
+
return err(`No profiles found in ${dir.data}. If the browser was just installed, open it once and retry.`);
|
|
86
|
+
}
|
|
87
|
+
return ok({ userDataDir: dir.data, profiles });
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const applyToLiveSession = async (client: BrowserClient): Promise<Result<void, string>> => {
|
|
91
|
+
if (!client.status().alive) return ok(undefined);
|
|
92
|
+
await client.closeOwnedTabs();
|
|
93
|
+
await client.stop();
|
|
94
|
+
const started = await client.start();
|
|
95
|
+
if (!started.success) return err(started.error.message);
|
|
96
|
+
return ok(undefined);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
export function registerProfileCommand(pi: ExtensionAPI, client: BrowserClient): void {
|
|
100
|
+
pi.registerCommand("browser-profile", {
|
|
101
|
+
description: "Choose which browser profile the agent uses",
|
|
102
|
+
handler: async (_args, ctx) => {
|
|
103
|
+
const loaded = await loadProfiles(client);
|
|
104
|
+
if (!loaded.success) {
|
|
105
|
+
ctx.ui.notify(loaded.error, "error");
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!ctx.hasUI) {
|
|
109
|
+
ctx.ui.notify("Profile selection needs an interactive terminal.", "warning");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const currentPin = client.profilePin() ?? (await readPin());
|
|
114
|
+
const choice = await promptForProfile(ctx, loaded.data.profiles, currentPin);
|
|
115
|
+
|
|
116
|
+
if (choice.kind === "cancelled") {
|
|
117
|
+
ctx.ui.notify("Profile unchanged.", "info");
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (choice.kind === "clear") {
|
|
122
|
+
const cleared = await clearPin();
|
|
123
|
+
if (!cleared.success) {
|
|
124
|
+
ctx.ui.notify(cleared.error, "error");
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
client.setProfilePin(null);
|
|
128
|
+
ctx.ui.notify(
|
|
129
|
+
"Profile selection cleared. New windows will open in whichever browser profile is focused.",
|
|
130
|
+
"info",
|
|
131
|
+
);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const pin = pinFor(loaded.data.userDataDir, choice.profile);
|
|
136
|
+
const saved = await writePin(pin);
|
|
137
|
+
if (!saved.success) {
|
|
138
|
+
ctx.ui.notify(saved.error, "error");
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
client.setProfilePin(pin);
|
|
142
|
+
|
|
143
|
+
const applied = await applyToLiveSession(client);
|
|
144
|
+
if (!applied.success) {
|
|
145
|
+
ctx.ui.notify(
|
|
146
|
+
`Saved ${pin.label}, but switching the open session failed: ${applied.error}`,
|
|
147
|
+
"warning",
|
|
148
|
+
);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
ctx.ui.notify(`Browser profile: ${pin.label} ✓\nSaved — this profile is used until you change it.`, "info");
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export const promptForProfileIfUnset = async (
|
|
157
|
+
client: BrowserClient,
|
|
158
|
+
ctx: ExtensionContext | undefined,
|
|
159
|
+
): Promise<string | undefined> => {
|
|
160
|
+
if (client.profilePin()) return undefined;
|
|
161
|
+
|
|
162
|
+
const stored = await readPin();
|
|
163
|
+
if (stored) {
|
|
164
|
+
client.setProfilePin(stored);
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
if (!ctx?.hasUI) {
|
|
168
|
+
return "No browser profile selected — using whichever window is focused. Run /browser-profile to pin one.";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const loaded = await loadProfiles(client);
|
|
172
|
+
if (!loaded.success) return loaded.error;
|
|
173
|
+
|
|
174
|
+
const choice = await promptForProfile(
|
|
175
|
+
ctx,
|
|
176
|
+
loaded.data.profiles,
|
|
177
|
+
null,
|
|
178
|
+
"Select the browser profile the agent should use",
|
|
179
|
+
);
|
|
180
|
+
if (choice.kind !== "profile") {
|
|
181
|
+
return "No browser profile selected — using whichever window is focused. Run /browser-profile to pin one.";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const pin = pinFor(loaded.data.userDataDir, choice.profile);
|
|
185
|
+
const saved = await writePin(pin);
|
|
186
|
+
if (!saved.success) return saved.error;
|
|
187
|
+
client.setProfilePin(pin);
|
|
188
|
+
return `Browser profile: ${pin.label}`;
|
|
189
|
+
};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// CDP cannot open a window in another profile, so this goes through the command line: ProcessSingleton hands the argv to the running browser.
|
|
2
|
+
// The sentinel must ride on a real `file://` URL — Chrome discards a bare `about:blank#token` argument and opens chrome://newtab instead.
|
|
3
|
+
|
|
4
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { type Result, err, ok } from "../util/result";
|
|
11
|
+
|
|
12
|
+
export type ProfileWindowRequest = {
|
|
13
|
+
readonly exePath: string;
|
|
14
|
+
readonly profileDir: string;
|
|
15
|
+
readonly explicitUserDataDir?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type ProfileWindowHandle = {
|
|
19
|
+
readonly sentinelUrl: string;
|
|
20
|
+
readonly cleanup: () => Promise<void>;
|
|
21
|
+
readonly kill: () => void;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const SENTINEL_HTML = (token: string): string =>
|
|
25
|
+
`<!doctype html><meta charset="utf-8"><title>${token}</title>` +
|
|
26
|
+
`<body style="font:14px system-ui;padding:2rem;color:#555">pi browser harness — opening this profile…</body>`;
|
|
27
|
+
|
|
28
|
+
export const openProfileWindow = async (
|
|
29
|
+
req: ProfileWindowRequest,
|
|
30
|
+
): Promise<Result<ProfileWindowHandle, string>> => {
|
|
31
|
+
const token = `pi-harness-${randomUUID()}`;
|
|
32
|
+
const file = join(tmpdir(), `${token}.html`);
|
|
33
|
+
try {
|
|
34
|
+
await writeFile(file, SENTINEL_HTML(token), "utf8");
|
|
35
|
+
} catch (e) {
|
|
36
|
+
return err(`could not write the profile handshake page: ${e instanceof Error ? e.message : String(e)}`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const sentinelUrl = pathToFileURL(file).href;
|
|
40
|
+
const args: string[] = [];
|
|
41
|
+
if (req.explicitUserDataDir) args.push(`--user-data-dir=${req.explicitUserDataDir}`);
|
|
42
|
+
args.push(`--profile-directory=${req.profileDir}`, "--new-window", sentinelUrl);
|
|
43
|
+
|
|
44
|
+
let child: ChildProcess;
|
|
45
|
+
try {
|
|
46
|
+
child = spawn(req.exePath, args, { detached: true, stdio: "ignore" });
|
|
47
|
+
} catch (e) {
|
|
48
|
+
await rm(file, { force: true }).catch(() => {});
|
|
49
|
+
return err(`could not launch ${req.exePath}: ${e instanceof Error ? e.message : String(e)}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// spawn() reports a bad binary asynchronously as an 'error' event rather than throwing; unhandled, an ENOENT looked like the 15s sentinel timeout.
|
|
53
|
+
const spawnFailure = await new Promise<string | undefined>((resolve) => {
|
|
54
|
+
child.once("spawn", () => resolve(undefined));
|
|
55
|
+
child.once("error", (e: Error) => resolve(e.message));
|
|
56
|
+
});
|
|
57
|
+
// A later 'error' event with no listener would throw, so keep one attached for the detached launcher's lifetime.
|
|
58
|
+
child.on("error", () => {});
|
|
59
|
+
child.unref();
|
|
60
|
+
|
|
61
|
+
if (spawnFailure) {
|
|
62
|
+
await rm(file, { force: true }).catch(() => {});
|
|
63
|
+
return err(`could not launch ${req.exePath}: ${spawnFailure}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let live: ChildProcess | null = child;
|
|
67
|
+
|
|
68
|
+
return ok({
|
|
69
|
+
sentinelUrl,
|
|
70
|
+
cleanup: async () => {
|
|
71
|
+
await rm(file, { force: true }).catch(() => {});
|
|
72
|
+
},
|
|
73
|
+
kill: () => {
|
|
74
|
+
if (live) {
|
|
75
|
+
try { live.kill("SIGTERM"); } catch {}
|
|
76
|
+
live = null;
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
};
|