pi-browser-harness 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +86 -0
- package/package.json +12 -6
- package/skills/pi-browser-harness/SKILL.md +57 -2
- package/src/cdp/commands.ts +200 -14
- package/src/cdp/console-buffer.ts +37 -23
- package/src/cdp/discovery.ts +57 -25
- package/src/cdp/events.ts +8 -3
- package/src/cdp/network-buffer.ts +38 -32
- package/src/cdp/ownership.ts +22 -4
- package/src/cdp/record-store.ts +2 -2
- package/src/cdp/session.ts +320 -217
- package/src/cdp/target-factory.ts +34 -15
- package/src/cdp/types.ts +17 -1
- package/src/client.ts +76 -43
- package/src/daemon/bridge.ts +110 -349
- package/src/daemon/connection.ts +323 -0
- package/src/daemon/index.ts +77 -48
- package/src/daemon/lines.ts +40 -0
- package/src/daemon/main.ts +12 -0
- package/src/daemon/protocol.ts +55 -25
- package/src/daemon/server.ts +100 -63
- package/src/daemon/socket.ts +10 -0
- package/src/daemon/spawn.ts +21 -22
- package/src/daemon/transport.ts +80 -49
- package/src/domains/ax-tree.ts +8 -8
- package/src/domains/cdp-call.ts +14 -7
- package/src/domains/click.ts +2 -2
- package/src/domains/concurrency.ts +50 -0
- package/src/domains/console.ts +20 -64
- package/src/domains/drag.ts +26 -28
- package/src/domains/element-call.ts +102 -68
- package/src/domains/files.ts +13 -9
- package/src/domains/form-batch.ts +13 -10
- package/src/domains/form.ts +78 -107
- package/src/domains/headers.ts +2 -2
- package/src/domains/history.ts +4 -4
- package/src/domains/io.ts +35 -0
- package/src/domains/isolated-tab.ts +6 -12
- package/src/domains/js.ts +65 -44
- package/src/domains/keyboard.ts +14 -11
- package/src/domains/navigate.ts +102 -66
- package/src/domains/network.ts +55 -95
- package/src/domains/page/fill.page.ts +139 -0
- package/src/domains/page/form.page.ts +61 -0
- package/src/domains/page/inject.ts +37 -0
- package/src/domains/page/keyboard.page.ts +16 -0
- package/src/domains/page/live-value.page.ts +10 -0
- package/src/domains/page/read-page.page.ts +51 -0
- package/src/domains/page/serp.page.ts +39 -0
- package/src/domains/page.ts +18 -51
- package/src/domains/poll.ts +42 -0
- package/src/domains/readpage/read-page.ts +48 -53
- package/src/domains/ref-resolve.ts +43 -29
- package/src/domains/ref-signature.ts +11 -0
- package/src/domains/render.ts +12 -23
- package/src/domains/screenshot-capture.ts +4 -2
- package/src/domains/screenshot.ts +13 -10
- package/src/domains/scroll.ts +4 -4
- package/src/domains/search/google-serp.ts +1 -1
- package/src/domains/search/web-search.ts +38 -33
- package/src/domains/snapshot.ts +71 -73
- package/src/domains/tab-resolve.ts +36 -0
- package/src/domains/tabs.ts +18 -69
- package/src/domains/target.ts +1 -1
- package/src/index.ts +90 -33
- package/src/profile/bind.ts +45 -14
- package/src/profile/browser-process.ts +50 -12
- package/src/profile/command.ts +20 -12
- package/src/profile/launch.ts +13 -9
- package/src/profile/list.ts +9 -13
- package/src/profile/store.ts +2 -1
- package/src/prompt.ts +32 -7
- package/src/registry.ts +65 -4
- package/src/schemas/parse.ts +2 -2
- package/src/setup.ts +28 -19
- package/src/state.ts +2 -1
- package/src/util/debug.ts +7 -1
- package/src/util/guards.ts +3 -0
- package/src/util/mutex.ts +1 -1
- package/src/util/paths.ts +3 -2
- package/src/util/result.ts +8 -0
- package/src/util/sharp-shim.ts +18 -11
- package/src/util/sleep.ts +18 -0
- package/src/util/tool.ts +163 -114
- package/src/util/truncate.ts +1 -1
- package/tsconfig.json +2 -1
- package/src/domains/fill-engine.ts +0 -80
package/src/index.ts
CHANGED
|
@@ -1,25 +1,76 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
2
|
-
import { type BrowserClient, createBrowserClient } from "./client";
|
|
2
|
+
import { type BrowserClient, type BrowserClientOptions, createBrowserClient } from "./client";
|
|
3
3
|
import { getBrowserSystemPrompt } from "./prompt";
|
|
4
4
|
import { registerSetupCommand } from "./setup";
|
|
5
5
|
import { registerProfileCommand } from "./profile/command";
|
|
6
|
-
import { readPin } from "./profile/store";
|
|
7
|
-
import { type BrowserState, createStatePersister,
|
|
8
|
-
import {
|
|
6
|
+
import { type ProfilePin, readPin } from "./profile/store";
|
|
7
|
+
import { type BrowserState, createStatePersister, restoreState } from "./state";
|
|
8
|
+
import { ALL_TOOLS, type RegistryError, createToolRegistry } from "./registry";
|
|
9
9
|
import { cleanupTempDirs } from "./util/truncate";
|
|
10
10
|
import { restoreDownloadBehavior } from "./domains/files";
|
|
11
11
|
import { createDaemonTransport } from "./daemon/transport";
|
|
12
|
+
import type { CdpTransport } from "./cdp/types";
|
|
12
13
|
import { setDebugClicks } from "./util/debug";
|
|
13
14
|
import { asBoolean, asString } from "./util/guards";
|
|
15
|
+
import type { BrowserTool } from "./util/tool";
|
|
16
|
+
import type { Result } from "./util/result";
|
|
14
17
|
|
|
15
|
-
export
|
|
16
|
-
|
|
17
|
-
|
|
18
|
+
export { defineBrowserTool } from "./util/tool";
|
|
19
|
+
export type {
|
|
20
|
+
BrowserTool,
|
|
21
|
+
BrowserToolDefinition,
|
|
22
|
+
DefinedBrowserTool,
|
|
23
|
+
HandlerContext,
|
|
24
|
+
ToolConcurrency,
|
|
25
|
+
ToolErr,
|
|
26
|
+
ToolErrKind,
|
|
27
|
+
ToolHandler,
|
|
28
|
+
ToolOk,
|
|
29
|
+
} from "./util/tool";
|
|
30
|
+
export type { RegistryError, ToolRegistry } from "./registry";
|
|
31
|
+
export type { BrowserClient } from "./client";
|
|
32
|
+
export { err, ok } from "./util/result";
|
|
33
|
+
export type { Result } from "./util/result";
|
|
18
34
|
|
|
19
|
-
|
|
35
|
+
// One registry per process: pi loads this module once, and another extension that imports it
|
|
36
|
+
// shares the same instance, so tools contributed through registerBrowserTools reach the same
|
|
37
|
+
// client, mutation mutex and tab ownership as the built-ins.
|
|
38
|
+
const harnessRegistry = createToolRegistry(ALL_TOOLS);
|
|
39
|
+
|
|
40
|
+
// Contribute tools from another pi extension. Call it at that extension's load time, before
|
|
41
|
+
// session_start; the tools are registered with pi on the next session_start alongside the
|
|
42
|
+
// built-ins. The batch is all-or-nothing: a name clash rejects the whole call and leaves the
|
|
43
|
+
// registry untouched.
|
|
44
|
+
export const registerBrowserTools = (tools: ReadonlyArray<BrowserTool>): Result<void, RegistryError> =>
|
|
45
|
+
harnessRegistry.addAll(tools);
|
|
46
|
+
|
|
47
|
+
// The tools the extension will register, built-ins plus contributions so far.
|
|
48
|
+
export const browserTools = (): ReadonlyArray<BrowserTool> => harnessRegistry.tools();
|
|
49
|
+
|
|
50
|
+
// The collaborators session_start reaches for. Each defaults to the real implementation; tests
|
|
51
|
+
// inject recorders to observe the namespace handed to the transport and the client's lifetime.
|
|
52
|
+
export type ExtensionDeps = {
|
|
53
|
+
readonly createTransport?: (namespace: string) => CdpTransport;
|
|
54
|
+
readonly createClient?: (opts: BrowserClientOptions) => BrowserClient;
|
|
55
|
+
readonly readPin?: () => Promise<ProfilePin | null>;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export const createExtension = (deps: ExtensionDeps = {}): ((pi: ExtensionAPI) => void) => (pi: ExtensionAPI): void => {
|
|
59
|
+
const createTransport = deps.createTransport ?? ((namespace: string): CdpTransport => createDaemonTransport(namespace));
|
|
60
|
+
const createClient = deps.createClient ?? createBrowserClient;
|
|
61
|
+
const loadPin = deps.readPin ?? readPin;
|
|
62
|
+
|
|
63
|
+
// Flags are only readable once pi has parsed them, which is after registration and before the
|
|
64
|
+
// first session event; reading at load time always yielded undefined (#browser-namespace).
|
|
65
|
+
let namespace: string | undefined;
|
|
66
|
+
const resolveNamespace = (): string => {
|
|
67
|
+
namespace ??= asString(pi.getFlag("browser-namespace")) ?? `pi-${Math.random().toString(36).slice(2, 10)}`;
|
|
68
|
+
return namespace;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
let state: BrowserState | undefined;
|
|
20
72
|
const persister = createStatePersister(pi);
|
|
21
73
|
let client: BrowserClient | null = null;
|
|
22
|
-
let toolsRegistered = false;
|
|
23
74
|
|
|
24
75
|
pi.registerFlag("browser-namespace", {
|
|
25
76
|
description: "Browser daemon namespace. Default: auto-generated",
|
|
@@ -49,7 +100,7 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
49
100
|
if (s.alive) {
|
|
50
101
|
const info = await client.pageInfo();
|
|
51
102
|
if (info.success) {
|
|
52
|
-
if ("dialog"
|
|
103
|
+
if (info.data.kind === "dialog") {
|
|
53
104
|
lines.push(`\n⚠️ Dialog open: ${info.data.dialog.type} — "${info.data.dialog.message}"`);
|
|
54
105
|
} else {
|
|
55
106
|
lines.push(
|
|
@@ -74,7 +125,7 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
74
125
|
}
|
|
75
126
|
ctx.ui.notify("Restarting browser client...", "info");
|
|
76
127
|
await client.stop();
|
|
77
|
-
const r = await client.start();
|
|
128
|
+
const r = await client.start({ reconnectNow: true });
|
|
78
129
|
if (r.success) {
|
|
79
130
|
ctx.ui.notify("Browser client restarted ✓", "info");
|
|
80
131
|
} else {
|
|
@@ -84,29 +135,30 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
84
135
|
});
|
|
85
136
|
|
|
86
137
|
pi.on("session_start", async (_event, ctx) => {
|
|
87
|
-
|
|
88
|
-
|
|
138
|
+
const restored = restoreState(ctx, resolveNamespace());
|
|
139
|
+
state = restored;
|
|
140
|
+
persister.markPersisted(restored);
|
|
89
141
|
setDebugClicks(asBoolean(pi.getFlag("browser-debug-clicks")) ?? false);
|
|
90
142
|
|
|
91
143
|
// Re-read the on-disk profile pin every session start: another pi session may have changed it since this client was created.
|
|
92
|
-
const profilePin = await
|
|
144
|
+
const profilePin = await loadPin();
|
|
93
145
|
|
|
94
146
|
if (!client) {
|
|
95
|
-
const transport =
|
|
147
|
+
const transport = createTransport(restored.namespace);
|
|
96
148
|
|
|
97
149
|
const initialOwnership: { ownedTargetIds?: ReadonlyArray<string>; harnessWindowTargetId?: string; harnessWindowId?: number } = {};
|
|
98
|
-
if (
|
|
99
|
-
if (
|
|
100
|
-
if (
|
|
150
|
+
if (restored.ownedTargetIds !== undefined) initialOwnership.ownedTargetIds = restored.ownedTargetIds;
|
|
151
|
+
if (restored.harnessWindowTargetId !== undefined) initialOwnership.harnessWindowTargetId = restored.harnessWindowTargetId;
|
|
152
|
+
if (restored.harnessWindowId !== undefined) initialOwnership.harnessWindowId = restored.harnessWindowId;
|
|
101
153
|
|
|
102
|
-
client =
|
|
103
|
-
namespace:
|
|
154
|
+
client = createClient({
|
|
155
|
+
namespace: restored.namespace,
|
|
104
156
|
transport,
|
|
105
157
|
profilePin,
|
|
106
158
|
...(Object.keys(initialOwnership).length > 0 ? { initialOwnership } : {}),
|
|
107
159
|
onOwnershipChange: (snap) => {
|
|
108
160
|
state = {
|
|
109
|
-
...state,
|
|
161
|
+
...(state ?? restored),
|
|
110
162
|
ownedTargetIds: snap.ownedTargetIds,
|
|
111
163
|
...(snap.harnessWindowTargetId !== undefined
|
|
112
164
|
? { harnessWindowTargetId: snap.harnessWindowTargetId }
|
|
@@ -115,17 +167,18 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
115
167
|
? { harnessWindowId: snap.harnessWindowId }
|
|
116
168
|
: {}),
|
|
117
169
|
};
|
|
118
|
-
try {
|
|
170
|
+
try {
|
|
171
|
+
persister.persist(state);
|
|
172
|
+
} catch {
|
|
173
|
+
// Persisting is best-effort: a failed append must not break ownership tracking.
|
|
174
|
+
}
|
|
119
175
|
},
|
|
120
176
|
});
|
|
121
177
|
} else {
|
|
122
178
|
client.setProfilePin(profilePin);
|
|
123
179
|
}
|
|
124
180
|
|
|
125
|
-
|
|
126
|
-
registerAllTools(pi, client);
|
|
127
|
-
toolsRegistered = true;
|
|
128
|
-
}
|
|
181
|
+
harnessRegistry.register(pi, client);
|
|
129
182
|
registerSetupCommand(pi, client);
|
|
130
183
|
registerProfileCommand(pi, client);
|
|
131
184
|
});
|
|
@@ -145,19 +198,23 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
145
198
|
}
|
|
146
199
|
// Do NOT stop the client or null it out: the surviving daemon connection is what eliminates the per-session "Allow Remote Debugging" prompt.
|
|
147
200
|
}
|
|
148
|
-
persister.persist(state);
|
|
201
|
+
if (state !== undefined) persister.persist(state);
|
|
149
202
|
await cleanupTempDirs();
|
|
150
203
|
});
|
|
151
204
|
|
|
152
205
|
// The branch already holds the restored snapshot: re-appending it only grows the session file.
|
|
153
|
-
pi.on("session_tree",
|
|
154
|
-
|
|
155
|
-
|
|
206
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
207
|
+
const restored = restoreState(ctx, resolveNamespace());
|
|
208
|
+
state = restored;
|
|
209
|
+
persister.markPersisted(restored);
|
|
156
210
|
});
|
|
157
211
|
|
|
158
|
-
pi.on("before_agent_start",
|
|
212
|
+
pi.on("before_agent_start", (event) => {
|
|
159
213
|
return {
|
|
160
|
-
systemPrompt: event.systemPrompt + getBrowserSystemPrompt(client?.status().alive ?? false),
|
|
214
|
+
systemPrompt: event.systemPrompt + getBrowserSystemPrompt(client?.status().alive ?? false, harnessRegistry.tools()),
|
|
161
215
|
};
|
|
162
216
|
});
|
|
163
|
-
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const browserHarnessExtension = createExtension();
|
|
220
|
+
export default browserHarnessExtension;
|
package/src/profile/bind.ts
CHANGED
|
@@ -1,20 +1,37 @@
|
|
|
1
1
|
import type { BrowserClient } from "../client";
|
|
2
2
|
import type { ResultOf } from "../cdp/commands";
|
|
3
3
|
import { type CdpError, cdpError } from "../cdp/errors";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
4
|
+
import { borrowSession } from "../cdp/target-factory";
|
|
5
|
+
import { type Result, err, map, ok, unwrapOr } from "../util/result";
|
|
6
|
+
import { sleep as sleepMs } from "../util/sleep";
|
|
7
|
+
import { detectRunningBrowser, resolveBrowserExecutable, type RunningBrowser } from "./browser-process";
|
|
8
|
+
import { openProfileWindow, type ProfileWindowHandle, type ProfileWindowRequest } from "./launch";
|
|
7
9
|
import type { ProfilePin } from "./store";
|
|
8
10
|
|
|
9
11
|
const SEED_DEADLINE_MS = 15_000;
|
|
10
12
|
const SEED_POLL_MS = 500;
|
|
11
13
|
|
|
14
|
+
// The machine-facing steps of seeding: process detection, executable lookup, the window launch
|
|
15
|
+
// and the sentinel poll's clock. Each defaults to the real implementation.
|
|
16
|
+
export type SeedDeps = {
|
|
17
|
+
readonly detectRunningBrowser?: (preferUserDataDir?: string) => Promise<RunningBrowser>;
|
|
18
|
+
readonly resolveBrowserExecutable?: (running?: RunningBrowser) => Promise<string | undefined>;
|
|
19
|
+
readonly openProfileWindow?: (req: ProfileWindowRequest) => Promise<Result<ProfileWindowHandle, string>>;
|
|
20
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
21
|
+
readonly now?: () => number;
|
|
22
|
+
readonly deadlineMs?: number;
|
|
23
|
+
readonly pollMs?: number;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
|
|
12
27
|
type PageTarget = ResultOf<"Target.getTargets">["targetInfos"][number];
|
|
13
28
|
|
|
14
29
|
const pageTargets = async (client: BrowserClient): Promise<ReadonlyArray<PageTarget>> => {
|
|
15
30
|
const r = await client.session().callBrowser("Target.getTargets");
|
|
16
|
-
|
|
17
|
-
|
|
31
|
+
return unwrapOr(
|
|
32
|
+
map(r, (d): ReadonlyArray<PageTarget> => d.targetInfos.filter((t) => t.type === "page")),
|
|
33
|
+
[],
|
|
34
|
+
);
|
|
18
35
|
};
|
|
19
36
|
|
|
20
37
|
const manualFallbackHint = (pin: ProfilePin): string =>
|
|
@@ -24,7 +41,16 @@ const manualFallbackHint = (pin: ProfilePin): string =>
|
|
|
24
41
|
export const seedProfileWindow = async (
|
|
25
42
|
client: BrowserClient,
|
|
26
43
|
pin: ProfilePin,
|
|
44
|
+
deps: SeedDeps = {},
|
|
27
45
|
): Promise<Result<string, CdpError>> => {
|
|
46
|
+
const detect = deps.detectRunningBrowser ?? detectRunningBrowser;
|
|
47
|
+
const resolveExe = deps.resolveBrowserExecutable ?? resolveBrowserExecutable;
|
|
48
|
+
const launch = deps.openProfileWindow ?? openProfileWindow;
|
|
49
|
+
const sleep = deps.sleep ?? sleepMs;
|
|
50
|
+
const now = deps.now ?? Date.now;
|
|
51
|
+
const deadlineMs = deps.deadlineMs ?? SEED_DEADLINE_MS;
|
|
52
|
+
const pollMs = deps.pollMs ?? SEED_POLL_MS;
|
|
53
|
+
|
|
28
54
|
const connectedDir = client.userDataDir();
|
|
29
55
|
if (connectedDir && connectedDir !== pin.userDataDir) {
|
|
30
56
|
return err(cdpError(
|
|
@@ -35,8 +61,8 @@ export const seedProfileWindow = async (
|
|
|
35
61
|
}
|
|
36
62
|
|
|
37
63
|
const targetUserDataDir = connectedDir ?? pin.userDataDir;
|
|
38
|
-
const running = await
|
|
39
|
-
const exePath = await
|
|
64
|
+
const running = await detect(targetUserDataDir);
|
|
65
|
+
const exePath = await resolveExe(running);
|
|
40
66
|
if (!exePath) {
|
|
41
67
|
return err(cdpError(
|
|
42
68
|
"discovery_failed",
|
|
@@ -44,7 +70,7 @@ export const seedProfileWindow = async (
|
|
|
44
70
|
));
|
|
45
71
|
}
|
|
46
72
|
|
|
47
|
-
const launched = await
|
|
73
|
+
const launched = await launch({
|
|
48
74
|
exePath,
|
|
49
75
|
profileDir: pin.profileDir,
|
|
50
76
|
// 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.
|
|
@@ -55,10 +81,10 @@ export const seedProfileWindow = async (
|
|
|
55
81
|
}
|
|
56
82
|
|
|
57
83
|
const { sentinelUrl, cleanup, kill } = launched.data;
|
|
58
|
-
const deadline =
|
|
84
|
+
const deadline = now() + deadlineMs;
|
|
59
85
|
let seed: PageTarget | undefined;
|
|
60
|
-
while (
|
|
61
|
-
await
|
|
86
|
+
while (now() < deadline && !seed) {
|
|
87
|
+
await sleep(pollMs);
|
|
62
88
|
seed = (await pageTargets(client)).find((t) => t.url === sentinelUrl);
|
|
63
89
|
}
|
|
64
90
|
|
|
@@ -80,9 +106,14 @@ export const seedProfileWindow = async (
|
|
|
80
106
|
const win = await client.session().windowId(seed.targetId);
|
|
81
107
|
if (win.success) ownership.setHarnessWindowId(win.data);
|
|
82
108
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
109
|
+
// Clears the sentinel URL from the seed tab. The session is borrowed and released so an untracked attach never outlives this call.
|
|
110
|
+
const borrowed = await borrowSession(client, seed.targetId);
|
|
111
|
+
if (borrowed.success) {
|
|
112
|
+
try {
|
|
113
|
+
await client.session().callOnTarget("Page.navigate", { url: "about:blank" }, borrowed.data.sessionId);
|
|
114
|
+
} finally {
|
|
115
|
+
await borrowed.data.release();
|
|
116
|
+
}
|
|
86
117
|
}
|
|
87
118
|
await cleanup();
|
|
88
119
|
|
|
@@ -23,6 +23,31 @@ const LINUX_COMMS: ReadonlyArray<string> = [
|
|
|
23
23
|
"chrome", "chromium", "chromium-browser", "msedge", "microsoft-edge",
|
|
24
24
|
"google-chrome", "brave", "brave-browser",
|
|
25
25
|
];
|
|
26
|
+
|
|
27
|
+
// The kernel stores a process name in TASK_COMM_LEN (16) bytes, so `ps -o comm=` prints at most 15
|
|
28
|
+
// characters: "chromium-browser" shows up as "chromium-browse" and would never match in full.
|
|
29
|
+
const LINUX_COMM_MAX = 15;
|
|
30
|
+
|
|
31
|
+
export const isLinuxBrowserComm = (comm: string): boolean => {
|
|
32
|
+
const lower = comm.toLowerCase();
|
|
33
|
+
return LINUX_COMMS.some((name) => name.slice(0, LINUX_COMM_MAX) === lower);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// /proc/<pid>/cmdline separates arguments with NUL, which keeps a space inside argv[0] or a
|
|
37
|
+
// --user-data-dir value intact. A string without NULs (a test fixture, or a zombie's empty
|
|
38
|
+
// cmdline) falls back to whitespace splitting.
|
|
39
|
+
export const parseProcCmdline = (raw: string): ReadonlyArray<string> => {
|
|
40
|
+
const argv = raw.includes("\0") ? raw.split("\0") : raw.trim().split(/\s+/);
|
|
41
|
+
return argv.filter((arg) => arg.length > 0);
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const USER_DATA_DIR_FLAG = "--user-data-dir=";
|
|
45
|
+
|
|
46
|
+
export const userDataDirFromArgv = (argv: ReadonlyArray<string>): string | undefined => {
|
|
47
|
+
const flag = argv.find((arg) => arg.startsWith(USER_DATA_DIR_FLAG));
|
|
48
|
+
const value = flag?.slice(USER_DATA_DIR_FLAG.length);
|
|
49
|
+
return value !== undefined && value.length > 0 ? value : undefined;
|
|
50
|
+
};
|
|
26
51
|
const MAC_BROWSER_NAMES: ReadonlyArray<string> = [
|
|
27
52
|
"google chrome", "chromium", "microsoft edge", "brave browser",
|
|
28
53
|
];
|
|
@@ -116,7 +141,7 @@ const collectLinux = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
116
141
|
.flatMap((line) => {
|
|
117
142
|
const [pid, comm] = line.split(/\s+/, 2);
|
|
118
143
|
if (!pid || !comm) return [];
|
|
119
|
-
return
|
|
144
|
+
return isLinuxBrowserComm(comm) ? [pid] : [];
|
|
120
145
|
});
|
|
121
146
|
} catch {
|
|
122
147
|
return [];
|
|
@@ -124,22 +149,25 @@ const collectLinux = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
124
149
|
|
|
125
150
|
const candidates: BrowserCandidate[] = [];
|
|
126
151
|
for (const pid of pids) {
|
|
127
|
-
let
|
|
152
|
+
let argv: ReadonlyArray<string>;
|
|
128
153
|
try {
|
|
129
|
-
|
|
154
|
+
argv = parseProcCmdline(await readFile(`/proc/${pid}/cmdline`, "utf8"));
|
|
130
155
|
} catch {
|
|
131
156
|
continue;
|
|
132
157
|
}
|
|
133
|
-
|
|
158
|
+
const argv0 = argv[0];
|
|
159
|
+
if (argv0 === undefined || hasChildProcessType(argv.join(" "))) continue;
|
|
134
160
|
let link: string | undefined;
|
|
135
161
|
try {
|
|
136
162
|
link = await readlink(`/proc/${pid}/exe`);
|
|
137
|
-
} catch {
|
|
163
|
+
} catch {
|
|
164
|
+
// /proc/<pid>/exe is unreadable for processes owned by another user; argv[0] is used instead.
|
|
165
|
+
}
|
|
138
166
|
// 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
167
|
const exePath =
|
|
140
168
|
(link ? await spawnableExePath(link) : undefined) ??
|
|
141
|
-
(await spawnableExePath(
|
|
142
|
-
const explicit =
|
|
169
|
+
(await spawnableExePath(argv0));
|
|
170
|
+
const explicit = userDataDirFromArgv(argv);
|
|
143
171
|
candidates.push({
|
|
144
172
|
...(exePath ? { exePath } : {}),
|
|
145
173
|
...(explicit ? { explicitUserDataDir: explicit } : {}),
|
|
@@ -172,7 +200,9 @@ const collectDarwin = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
172
200
|
try {
|
|
173
201
|
const { stdout } = await run("ps", ["-ww", "-o", "args=", "-p", pid], { timeout: EXEC_TIMEOUT_MS });
|
|
174
202
|
args = stdout.trim();
|
|
175
|
-
} catch {
|
|
203
|
+
} catch {
|
|
204
|
+
// ps can fail for a process that exited meanwhile; the pid is still reported, without args.
|
|
205
|
+
}
|
|
176
206
|
if (args && hasChildProcessType(args)) continue;
|
|
177
207
|
const explicit = args ? parseUserDataDirFlag(args) : undefined;
|
|
178
208
|
candidates.push({
|
|
@@ -227,13 +257,17 @@ const collectWin32 = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
227
257
|
if (candidates.length > 0) return candidates;
|
|
228
258
|
}
|
|
229
259
|
}
|
|
230
|
-
} catch {
|
|
260
|
+
} catch {
|
|
261
|
+
// PowerShell is missing or restricted: fall back to tasklist below.
|
|
262
|
+
}
|
|
231
263
|
|
|
232
264
|
try {
|
|
233
265
|
const { stdout } = await run("tasklist.exe", [], { timeout: EXEC_TIMEOUT_MS, windowsHide: true });
|
|
234
266
|
const lower = stdout.toLowerCase();
|
|
235
267
|
if (WIN_IMAGE_NAMES.some((n) => lower.includes(n))) return [{}];
|
|
236
|
-
} catch {
|
|
268
|
+
} catch {
|
|
269
|
+
// tasklist unavailable too: report no running browser rather than failing detection.
|
|
270
|
+
}
|
|
237
271
|
return [];
|
|
238
272
|
};
|
|
239
273
|
|
|
@@ -266,7 +300,9 @@ const winRegistryExecutable = async (): Promise<string | undefined> => {
|
|
|
266
300
|
const match = /REG_[A-Z_]+\s+(.+)$/m.exec(stdout.trim());
|
|
267
301
|
const path = match?.[1]?.trim();
|
|
268
302
|
if (path) return path;
|
|
269
|
-
} catch {
|
|
303
|
+
} catch {
|
|
304
|
+
// Key absent or reg.exe failed: try the next registry location.
|
|
305
|
+
}
|
|
270
306
|
}
|
|
271
307
|
}
|
|
272
308
|
return undefined;
|
|
@@ -314,7 +350,9 @@ export const resolveBrowserExecutable = async (running?: RunningBrowser): Promis
|
|
|
314
350
|
try {
|
|
315
351
|
await access(candidate);
|
|
316
352
|
return candidate;
|
|
317
|
-
} catch {
|
|
353
|
+
} catch {
|
|
354
|
+
// Not installed at this location: try the next one.
|
|
355
|
+
}
|
|
318
356
|
}
|
|
319
357
|
return undefined;
|
|
320
358
|
};
|
package/src/profile/command.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
2
|
import type { BrowserClient } from "../client";
|
|
3
|
-
import { discoverEndpoint } from "../cdp/discovery";
|
|
4
|
-
import
|
|
3
|
+
import { type CdpEndpoint, discoverEndpoint } from "../cdp/discovery";
|
|
4
|
+
import type { CdpError } from "../cdp/errors";
|
|
5
|
+
import { type Result, err, mapErr, ok } from "../util/result";
|
|
5
6
|
import { type BrowserProfile, listProfiles } from "./list";
|
|
6
7
|
import { browserNameForUserDataDir, userDataDirCandidates } from "./paths";
|
|
7
8
|
import { clearPin, type ProfilePin, readPin, writePin } from "./store";
|
|
@@ -53,15 +54,22 @@ const pinFor = (userDataDir: string, profile: BrowserProfile): ProfilePin => ({
|
|
|
53
54
|
savedAt: new Date().toISOString(),
|
|
54
55
|
});
|
|
55
56
|
|
|
56
|
-
|
|
57
|
+
// How the command finds a user-data-dir when the client is not connected: the DevTools endpoint's
|
|
58
|
+
// own report, then a scan of the per-platform candidate directories. Each defaults to the real one.
|
|
59
|
+
export type ProfileCommandDeps = {
|
|
60
|
+
readonly discoverEndpoint?: () => Promise<Result<CdpEndpoint, CdpError>>;
|
|
61
|
+
readonly userDataDirCandidates?: () => ReadonlyArray<string>;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const resolveUserDataDir = async (client: BrowserClient, deps: ProfileCommandDeps): Promise<Result<string, string>> => {
|
|
57
65
|
const connected = client.userDataDir();
|
|
58
66
|
if (connected) return ok(connected);
|
|
59
67
|
|
|
60
|
-
const endpoint = await discoverEndpoint();
|
|
68
|
+
const endpoint = await (deps.discoverEndpoint ?? discoverEndpoint)();
|
|
61
69
|
if (endpoint.success && endpoint.data.userDataDir) return ok(endpoint.data.userDataDir);
|
|
62
70
|
|
|
63
71
|
const withProfiles: string[] = [];
|
|
64
|
-
for (const dir of userDataDirCandidates()) {
|
|
72
|
+
for (const dir of (deps.userDataDirCandidates ?? userDataDirCandidates)()) {
|
|
65
73
|
if ((await listProfiles(dir)).length > 0) withProfiles.push(dir);
|
|
66
74
|
}
|
|
67
75
|
const only = withProfiles[0];
|
|
@@ -77,8 +85,9 @@ const resolveUserDataDir = async (client: BrowserClient): Promise<Result<string,
|
|
|
77
85
|
|
|
78
86
|
const loadProfiles = async (
|
|
79
87
|
client: BrowserClient,
|
|
88
|
+
deps: ProfileCommandDeps,
|
|
80
89
|
): Promise<Result<{ userDataDir: string; profiles: ReadonlyArray<BrowserProfile> }, string>> => {
|
|
81
|
-
const dir = await resolveUserDataDir(client);
|
|
90
|
+
const dir = await resolveUserDataDir(client, deps);
|
|
82
91
|
if (!dir.success) return dir;
|
|
83
92
|
const profiles = await listProfiles(dir.data);
|
|
84
93
|
if (profiles.length === 0) {
|
|
@@ -91,16 +100,14 @@ const applyToLiveSession = async (client: BrowserClient): Promise<Result<void, s
|
|
|
91
100
|
if (!client.status().alive) return ok(undefined);
|
|
92
101
|
await client.closeOwnedTabs();
|
|
93
102
|
await client.stop();
|
|
94
|
-
|
|
95
|
-
if (!started.success) return err(started.error.message);
|
|
96
|
-
return ok(undefined);
|
|
103
|
+
return mapErr(await client.start(), (e) => e.message);
|
|
97
104
|
};
|
|
98
105
|
|
|
99
|
-
export function registerProfileCommand(pi: ExtensionAPI, client: BrowserClient): void {
|
|
106
|
+
export function registerProfileCommand(pi: ExtensionAPI, client: BrowserClient, deps: ProfileCommandDeps = {}): void {
|
|
100
107
|
pi.registerCommand("browser-profile", {
|
|
101
108
|
description: "Choose which browser profile the agent uses",
|
|
102
109
|
handler: async (_args, ctx) => {
|
|
103
|
-
const loaded = await loadProfiles(client);
|
|
110
|
+
const loaded = await loadProfiles(client, deps);
|
|
104
111
|
if (!loaded.success) {
|
|
105
112
|
ctx.ui.notify(loaded.error, "error");
|
|
106
113
|
return;
|
|
@@ -156,6 +163,7 @@ export function registerProfileCommand(pi: ExtensionAPI, client: BrowserClient):
|
|
|
156
163
|
export const promptForProfileIfUnset = async (
|
|
157
164
|
client: BrowserClient,
|
|
158
165
|
ctx: ExtensionContext | undefined,
|
|
166
|
+
deps: ProfileCommandDeps = {},
|
|
159
167
|
): Promise<string | undefined> => {
|
|
160
168
|
if (client.profilePin()) return undefined;
|
|
161
169
|
|
|
@@ -168,7 +176,7 @@ export const promptForProfileIfUnset = async (
|
|
|
168
176
|
return "No browser profile selected — using whichever window is focused. Run /browser-profile to pin one.";
|
|
169
177
|
}
|
|
170
178
|
|
|
171
|
-
const loaded = await loadProfiles(client);
|
|
179
|
+
const loaded = await loadProfiles(client, deps);
|
|
172
180
|
if (!loaded.success) return loaded.error;
|
|
173
181
|
|
|
174
182
|
const choice = await promptForProfile(
|
package/src/profile/launch.ts
CHANGED
|
@@ -41,25 +41,27 @@ export const openProfileWindow = async (
|
|
|
41
41
|
if (req.explicitUserDataDir) args.push(`--user-data-dir=${req.explicitUserDataDir}`);
|
|
42
42
|
args.push(`--profile-directory=${req.profileDir}`, "--new-window", sentinelUrl);
|
|
43
43
|
|
|
44
|
+
const discardSentinel = (): Promise<void> => rm(file, { force: true }).catch(() => undefined);
|
|
45
|
+
|
|
44
46
|
let child: ChildProcess;
|
|
45
47
|
try {
|
|
46
48
|
child = spawn(req.exePath, args, { detached: true, stdio: "ignore" });
|
|
47
49
|
} catch (e) {
|
|
48
|
-
await
|
|
50
|
+
await discardSentinel();
|
|
49
51
|
return err(`could not launch ${req.exePath}: ${e instanceof Error ? e.message : String(e)}`);
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
// spawn() reports a bad binary asynchronously as an 'error' event rather than throwing; unhandled, an ENOENT looked like the 15s sentinel timeout.
|
|
53
55
|
const spawnFailure = await new Promise<string | undefined>((resolve) => {
|
|
54
|
-
child.once("spawn", () => resolve(undefined));
|
|
55
|
-
child.once("error", (e: Error) => resolve(e.message));
|
|
56
|
+
child.once("spawn", () => { resolve(undefined); });
|
|
57
|
+
child.once("error", (e: Error) => { resolve(e.message); });
|
|
56
58
|
});
|
|
57
59
|
// A later 'error' event with no listener would throw, so keep one attached for the detached launcher's lifetime.
|
|
58
|
-
child.on("error", () =>
|
|
60
|
+
child.on("error", () => undefined);
|
|
59
61
|
child.unref();
|
|
60
62
|
|
|
61
63
|
if (spawnFailure) {
|
|
62
|
-
await
|
|
64
|
+
await discardSentinel();
|
|
63
65
|
return err(`could not launch ${req.exePath}: ${spawnFailure}`);
|
|
64
66
|
}
|
|
65
67
|
|
|
@@ -67,12 +69,14 @@ export const openProfileWindow = async (
|
|
|
67
69
|
|
|
68
70
|
return ok({
|
|
69
71
|
sentinelUrl,
|
|
70
|
-
cleanup:
|
|
71
|
-
await rm(file, { force: true }).catch(() => {});
|
|
72
|
-
},
|
|
72
|
+
cleanup: discardSentinel,
|
|
73
73
|
kill: () => {
|
|
74
74
|
if (live) {
|
|
75
|
-
try {
|
|
75
|
+
try {
|
|
76
|
+
live.kill("SIGTERM");
|
|
77
|
+
} catch {
|
|
78
|
+
// The process already exited; there is nothing left to kill.
|
|
79
|
+
}
|
|
76
80
|
live = null;
|
|
77
81
|
}
|
|
78
82
|
},
|
package/src/profile/list.ts
CHANGED
|
@@ -3,6 +3,8 @@ import { join } from "node:path";
|
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import { Compile } from "typebox/compile";
|
|
5
5
|
import { parseJson } from "../schemas/parse";
|
|
6
|
+
// Chrome writes "" for an unnamed profile and an unsigned-in account, so an empty string must read as absent.
|
|
7
|
+
import { asNonEmptyString, asRecord } from "../util/guards";
|
|
6
8
|
|
|
7
9
|
export type BrowserProfile = {
|
|
8
10
|
readonly dir: string;
|
|
@@ -35,12 +37,6 @@ const readJsonFile = async (path: string): Promise<Record<string, unknown> | nul
|
|
|
35
37
|
return parsed.success ? parsed.data : null;
|
|
36
38
|
};
|
|
37
39
|
|
|
38
|
-
const asRecord = (v: unknown): Record<string, unknown> | null =>
|
|
39
|
-
jsonObjectValidator.Check(v) ? v : null;
|
|
40
|
-
|
|
41
|
-
const asString = (v: unknown): string | undefined =>
|
|
42
|
-
typeof v === "string" && v.length > 0 ? v : undefined;
|
|
43
|
-
|
|
44
40
|
const orderDirs = (dirs: ReadonlyArray<string>, order: ReadonlyArray<string>): ReadonlyArray<string> => {
|
|
45
41
|
const known = order.filter((d) => dirs.includes(d));
|
|
46
42
|
const rest = dirs.filter((d) => !known.includes(d)).sort((a, b) => a.localeCompare(b));
|
|
@@ -73,9 +69,9 @@ const listFromLocalState = async (userDataDir: string): Promise<ReadonlyArray<Br
|
|
|
73
69
|
|
|
74
70
|
const rawOrder = profileNode["profiles_order"];
|
|
75
71
|
const order = Array.isArray(rawOrder) ? rawOrder.filter((v): v is string => typeof v === "string") : [];
|
|
76
|
-
const lastUsed =
|
|
72
|
+
const lastUsed = asNonEmptyString(profileNode["last_used"]);
|
|
77
73
|
|
|
78
|
-
const entries: Array<{ dir: string; entry: Record<string, unknown
|
|
74
|
+
const entries: Array<{ dir: string; entry: Readonly<Record<string, unknown>> }> = [];
|
|
79
75
|
for (const [dir, value] of Object.entries(infoCache)) {
|
|
80
76
|
if (NON_PROFILE_DIRS.has(dir)) continue;
|
|
81
77
|
const entry = asRecord(value);
|
|
@@ -91,8 +87,8 @@ const listFromLocalState = async (userDataDir: string): Promise<ReadonlyArray<Br
|
|
|
91
87
|
return ordered.flatMap((dir) => {
|
|
92
88
|
const entry = byDir.get(dir);
|
|
93
89
|
if (!entry) return [];
|
|
94
|
-
const name =
|
|
95
|
-
const email =
|
|
90
|
+
const name = asNonEmptyString(entry["name"]) ?? asNonEmptyString(entry["gaia_name"]);
|
|
91
|
+
const email = asNonEmptyString(entry["user_name"]);
|
|
96
92
|
return [buildProfile(dir, name, email, dir === lastUsed)];
|
|
97
93
|
});
|
|
98
94
|
};
|
|
@@ -115,10 +111,10 @@ const listFromPreferencesScan = async (userDataDir: string): Promise<ReadonlyArr
|
|
|
115
111
|
const prefs = await readJsonFile(join(userDataDir, dir, "Preferences"));
|
|
116
112
|
if (!prefs) continue;
|
|
117
113
|
const profileNode = asRecord(prefs["profile"]);
|
|
118
|
-
const name = profileNode ?
|
|
114
|
+
const name = profileNode ? asNonEmptyString(profileNode["name"]) : undefined;
|
|
119
115
|
const accounts = prefs["account_info"];
|
|
120
|
-
const firstAccount = Array.isArray(accounts) ? asRecord(accounts[0]) :
|
|
121
|
-
const email = firstAccount ?
|
|
116
|
+
const firstAccount = Array.isArray(accounts) ? asRecord(accounts[0]) : undefined;
|
|
117
|
+
const email = firstAccount ? asNonEmptyString(firstAccount["email"]) : undefined;
|
|
122
118
|
profiles.push(buildProfile(dir, name, email, false));
|
|
123
119
|
}
|
|
124
120
|
return profiles;
|
package/src/profile/store.ts
CHANGED
|
@@ -74,7 +74,8 @@ const writePinFile = async (profile: ProfilePin | null): Promise<Result<void, st
|
|
|
74
74
|
await rename(tmp, target);
|
|
75
75
|
return ok(undefined);
|
|
76
76
|
} catch (e) {
|
|
77
|
-
|
|
77
|
+
// The temp file may never have been created; the write error below is the one that matters.
|
|
78
|
+
await unlink(tmp).catch(() => undefined);
|
|
78
79
|
return err(`could not save profile selection to ${target}: ${e instanceof Error ? e.message : String(e)}`);
|
|
79
80
|
}
|
|
80
81
|
};
|