@narumitw/pi-chrome-devtools 0.13.0 → 0.14.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.
@@ -0,0 +1,340 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ browserCandidateHint,
4
+ chromeLaunchCommand,
5
+ devToolsEndpoint,
6
+ endpointConfigHint,
7
+ endpointSourceLabel,
8
+ launchAttemptLines,
9
+ launchHint,
10
+ launchModeLabel,
11
+ } from "./browser-manager.js";
12
+ import { loadSettings, saveSettings, settingsFilePath } from "./settings.js";
13
+ import { state } from "./runtime.js";
14
+ import {
15
+ CHROME_DEVTOOLS_TOOL_NAMES,
16
+ type ChromeDevToolsToolName,
17
+ } from "./tool-names.js";
18
+
19
+ type CommandContext = ExtensionCommandContext;
20
+ const TOOL_SELECTOR_DONE = "Done";
21
+ const TOOL_SELECTOR_ENABLE_ALL = "Enable all Chrome DevTools tools";
22
+ const TOOL_SELECTOR_DISABLE_ALL = "Disable all Chrome DevTools tools";
23
+ type ToolSelectorAction = "enableAll" | "disableAll" | "done";
24
+ type ToolSelectorRow =
25
+ | { kind: "tool"; toolName: ChromeDevToolsToolName }
26
+ | { kind: "action"; action: ToolSelectorAction; label: string };
27
+ function unique<T>(values: T[]) {
28
+ return Array.from(new Set(values));
29
+ }
30
+
31
+ function recordSettingsNotice(settings: { notice?: string }) {
32
+ if (settings.notice) state.settingsNotice = settings.notice;
33
+ }
34
+
35
+ function formatError(error: unknown) {
36
+ return error instanceof Error ? error.message : String(error);
37
+ }
38
+
39
+ interface ToolStatusSummary {
40
+ runtimeStatus: "enabled" | "disabled" | "partial";
41
+ activeChromeToolCount: number;
42
+ activeNonChromeToolCount: number;
43
+ }
44
+
45
+ export async function showToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
46
+ if (!ctx.hasUI) {
47
+ ctx.ui.notify(
48
+ `Chrome DevTools tool selection needs an interactive UI.
49
+
50
+ ${await buildToolStatusMessage(pi)}`,
51
+ "info",
52
+ );
53
+ return;
54
+ }
55
+
56
+ let selectedTools = new Set<ChromeDevToolsToolName>(getActiveChromeDevtoolsTools(pi));
57
+ let persistQueue = Promise.resolve();
58
+ const commitSelectedTools = () => {
59
+ const nextSelectedTools = orderedChromeDevtoolsTools(selectedTools);
60
+ applyChromeDevtoolsTools(pi, nextSelectedTools);
61
+ persistQueue = persistQueue.then(() => persistSettings(ctx, nextSelectedTools));
62
+ };
63
+
64
+ const customResult = await ctx.ui.custom<"closed" | undefined>(
65
+ (tui, theme, keybindings, done) => {
66
+ const rows = chromeDevtoolsToolSelectorRows();
67
+ let selectedIndex = 0;
68
+ const moveSelection = (delta: number) => {
69
+ selectedIndex = (selectedIndex + delta + rows.length) % rows.length;
70
+ };
71
+ const activateSelectedRow = () => {
72
+ const row = rows[selectedIndex];
73
+ if (!row) return;
74
+
75
+ if (row.kind === "tool") {
76
+ if (selectedTools.has(row.toolName)) selectedTools.delete(row.toolName);
77
+ else selectedTools.add(row.toolName);
78
+ commitSelectedTools();
79
+ return;
80
+ }
81
+
82
+ if (row.action === "enableAll") {
83
+ selectedTools = new Set(allChromeDevtoolsTools());
84
+ commitSelectedTools();
85
+ return;
86
+ }
87
+ if (row.action === "disableAll") {
88
+ selectedTools = new Set();
89
+ commitSelectedTools();
90
+ return;
91
+ }
92
+
93
+ done("closed");
94
+ };
95
+
96
+ return {
97
+ invalidate() {},
98
+ render() {
99
+ return [
100
+ theme.fg("accent", theme.bold(toolSelectorTitle(selectedTools))),
101
+ "",
102
+ ...rows.map((row, index) => {
103
+ const label = formatToolSelectorRow(row, selectedTools);
104
+ if (index === selectedIndex) {
105
+ return `${theme.fg("accent", "›")} ${theme.fg("accent", label)}`;
106
+ }
107
+ return ` ${label}`;
108
+ }),
109
+ "",
110
+ theme.fg("dim", "↑↓ navigate • Enter/Space toggle • Esc close"),
111
+ ];
112
+ },
113
+ handleInput(data: string) {
114
+ if (keybindings.matches(data, "tui.select.up")) {
115
+ moveSelection(-1);
116
+ tui.requestRender();
117
+ return;
118
+ }
119
+ if (keybindings.matches(data, "tui.select.down")) {
120
+ moveSelection(1);
121
+ tui.requestRender();
122
+ return;
123
+ }
124
+ if (keybindings.matches(data, "tui.select.pageUp")) {
125
+ selectedIndex = 0;
126
+ tui.requestRender();
127
+ return;
128
+ }
129
+ if (keybindings.matches(data, "tui.select.pageDown")) {
130
+ selectedIndex = rows.length - 1;
131
+ tui.requestRender();
132
+ return;
133
+ }
134
+ if (keybindings.matches(data, "tui.select.confirm") || data === " ") {
135
+ activateSelectedRow();
136
+ tui.requestRender();
137
+ return;
138
+ }
139
+ if (keybindings.matches(data, "tui.select.cancel")) {
140
+ done("closed");
141
+ }
142
+ },
143
+ };
144
+ },
145
+ );
146
+
147
+ if (customResult !== "closed") {
148
+ await showDialogToolSelector(pi, ctx);
149
+ return;
150
+ }
151
+
152
+ await persistQueue;
153
+ ctx.ui.notify(await buildToolStatusMessage(pi), "info");
154
+ }
155
+
156
+ async function showDialogToolSelector(pi: ExtensionAPI, ctx: CommandContext) {
157
+ let selectedTools = new Set<ChromeDevToolsToolName>(getActiveChromeDevtoolsTools(pi));
158
+ while (true) {
159
+ const rows = chromeDevtoolsToolSelectorRows();
160
+ const choices = rows.map((row) => formatToolSelectorRow(row, selectedTools));
161
+ const choice = await ctx.ui.select(toolSelectorTitle(selectedTools), choices);
162
+ if (!choice) break;
163
+
164
+ const row = rows[choices.indexOf(choice)];
165
+ if (!row) continue;
166
+ if (row.kind === "action" && row.action === "done") break;
167
+
168
+ if (row.kind === "tool") {
169
+ if (selectedTools.has(row.toolName)) selectedTools.delete(row.toolName);
170
+ else selectedTools.add(row.toolName);
171
+ } else if (row.action === "enableAll") {
172
+ selectedTools = new Set(allChromeDevtoolsTools());
173
+ } else if (row.action === "disableAll") {
174
+ selectedTools = new Set();
175
+ }
176
+
177
+ await setSelectedChromeDevtoolsTools(pi, ctx, orderedChromeDevtoolsTools(selectedTools));
178
+ }
179
+
180
+ ctx.ui.notify(await buildToolStatusMessage(pi), "info");
181
+ }
182
+
183
+ export async function updateChromeDevtoolsTools(
184
+ pi: ExtensionAPI,
185
+ ctx: CommandContext,
186
+ selectedTools: readonly ChromeDevToolsToolName[],
187
+ action: string,
188
+ ) {
189
+ await setSelectedChromeDevtoolsTools(pi, ctx, selectedTools);
190
+ ctx.ui.notify(`Chrome DevTools tools ${action}.
191
+
192
+ ${await buildToolStatusMessage(pi)}`, "info");
193
+ }
194
+
195
+ export async function setSelectedChromeDevtoolsTools(
196
+ pi: ExtensionAPI,
197
+ ctx: CommandContext,
198
+ selectedTools: readonly ChromeDevToolsToolName[],
199
+ ) {
200
+ applyChromeDevtoolsTools(pi, selectedTools);
201
+ await persistSettings(ctx, selectedTools);
202
+ }
203
+
204
+ export function applyChromeDevtoolsTools(
205
+ pi: ExtensionAPI,
206
+ selectedTools: readonly ChromeDevToolsToolName[],
207
+ ) {
208
+ const activeToolNames = pi.getActiveTools();
209
+ const chromeToolNames = new Set<string>(CHROME_DEVTOOLS_TOOL_NAMES);
210
+ const activeNonChromeToolNames = activeToolNames.filter((name) => !chromeToolNames.has(name));
211
+ pi.setActiveTools(unique([...activeNonChromeToolNames, ...selectedTools]));
212
+ }
213
+
214
+ function getToolStatusSummary(pi: ExtensionAPI): ToolStatusSummary {
215
+ const chromeToolNames = new Set<string>(CHROME_DEVTOOLS_TOOL_NAMES);
216
+ const activeToolNames = new Set(pi.getActiveTools());
217
+ const activeChromeToolCount = CHROME_DEVTOOLS_TOOL_NAMES.filter((name) =>
218
+ activeToolNames.has(name),
219
+ ).length;
220
+ const activeNonChromeToolCount = Array.from(activeToolNames).filter(
221
+ (name) => !chromeToolNames.has(name),
222
+ ).length;
223
+ const runtimeStatus =
224
+ activeChromeToolCount === CHROME_DEVTOOLS_TOOL_NAMES.length
225
+ ? "enabled"
226
+ : activeChromeToolCount === 0
227
+ ? "disabled"
228
+ : "partial";
229
+
230
+ return { runtimeStatus, activeChromeToolCount, activeNonChromeToolCount };
231
+ }
232
+
233
+ export async function buildToolStatusMessage(pi: ExtensionAPI) {
234
+ const summary = getToolStatusSummary(pi);
235
+ const persistedSetting = await persistedSettingLabel();
236
+ return [
237
+ `Chrome DevTools tools: ${formatRuntimeStatus(summary)}`,
238
+ `Persisted selection: ${persistedSetting}`,
239
+ `Settings file: ${settingsFilePath()}`,
240
+ ...(state.settingsNotice ? [`Settings note: ${state.settingsNotice}`] : []),
241
+ `Other active tools preserved: ${summary.activeNonChromeToolCount}`,
242
+ `Endpoint: ${devToolsEndpoint()}`,
243
+ `Endpoint source: ${endpointSourceLabel()}`,
244
+ `Launch mode: ${launchModeLabel()}`,
245
+ ...launchAttemptLines(),
246
+ ].join("\n");
247
+ }
248
+
249
+ export function buildQuickstartMessage() {
250
+ return [
251
+ `Chrome DevTools endpoint: ${devToolsEndpoint()}`,
252
+ `Endpoint source: ${endpointSourceLabel()}`,
253
+ `Launch mode: ${launchModeLabel()}`,
254
+ launchHint(),
255
+ browserCandidateHint(),
256
+ ...launchAttemptLines(),
257
+ endpointConfigHint(),
258
+ ].join("\n");
259
+ }
260
+
261
+ export function buildCommandGuide() {
262
+ return [
263
+ "Chrome DevTools commands:",
264
+ "/chrome-devtools — open this menu",
265
+ "/chrome-devtools help — show command usage",
266
+ "/chrome-devtools quickstart — show endpoint and launch help",
267
+ "/chrome-devtools status — show tool and settings status",
268
+ "/chrome-devtools tools — select individual Chrome DevTools tools",
269
+ "/chrome-devtools toggle — alias for /chrome-devtools tools",
270
+ "/chrome-devtools enable — enable all Chrome DevTools tools",
271
+ "/chrome-devtools disable — disable all Chrome DevTools tools",
272
+ ].join("\n");
273
+ }
274
+
275
+ function toolSelectorTitle(selectedTools: ReadonlySet<ChromeDevToolsToolName>) {
276
+ return `Chrome DevTools tools (${selectedTools.size}/${CHROME_DEVTOOLS_TOOL_NAMES.length}). Non-built-in tools run at user risk.`;
277
+ }
278
+
279
+ function chromeDevtoolsToolSelectorRows(): ToolSelectorRow[] {
280
+ return [
281
+ ...CHROME_DEVTOOLS_TOOL_NAMES.map((toolName) => ({ kind: "tool" as const, toolName })),
282
+ { kind: "action", action: "enableAll", label: TOOL_SELECTOR_ENABLE_ALL },
283
+ { kind: "action", action: "disableAll", label: TOOL_SELECTOR_DISABLE_ALL },
284
+ { kind: "action", action: "done", label: TOOL_SELECTOR_DONE },
285
+ ];
286
+ }
287
+
288
+ function formatToolSelectorRow(
289
+ row: ToolSelectorRow,
290
+ selectedTools: ReadonlySet<ChromeDevToolsToolName>,
291
+ ) {
292
+ if (row.kind === "action") return row.label;
293
+ return `${selectedTools.has(row.toolName) ? "[x]" : "[ ]"} ${row.toolName}`;
294
+ }
295
+
296
+ function getActiveChromeDevtoolsTools(pi: ExtensionAPI) {
297
+ const activeToolNames = new Set(pi.getActiveTools());
298
+ return CHROME_DEVTOOLS_TOOL_NAMES.filter((toolName) => activeToolNames.has(toolName));
299
+ }
300
+
301
+ export function allChromeDevtoolsTools() {
302
+ return [...CHROME_DEVTOOLS_TOOL_NAMES];
303
+ }
304
+
305
+ export function orderedChromeDevtoolsTools(selectedTools: ReadonlySet<ChromeDevToolsToolName>) {
306
+ return CHROME_DEVTOOLS_TOOL_NAMES.filter((toolName) => selectedTools.has(toolName));
307
+ }
308
+
309
+ function formatRuntimeStatus(summary: ToolStatusSummary) {
310
+ return `${summary.runtimeStatus} (${summary.activeChromeToolCount}/${CHROME_DEVTOOLS_TOOL_NAMES.length} active)`;
311
+ }
312
+
313
+ async function persistedSettingLabel() {
314
+ const settings = await loadSettings();
315
+ recordSettingsNotice(settings);
316
+ if (settings.kind === "loaded") return formatPersistedSelection(settings.settings.tools);
317
+ if (settings.kind === "invalid") {
318
+ return `none; current active-tool policy preserved (invalid settings ignored: ${settings.reason})`;
319
+ }
320
+ return "none; current active-tool policy preserved";
321
+ }
322
+
323
+ function formatPersistedSelection(tools: readonly ChromeDevToolsToolName[]) {
324
+ if (tools.length === CHROME_DEVTOOLS_TOOL_NAMES.length) {
325
+ return `all enabled (${tools.length}/${CHROME_DEVTOOLS_TOOL_NAMES.length} selected)`;
326
+ }
327
+ if (tools.length === 0) return `all disabled (0/${CHROME_DEVTOOLS_TOOL_NAMES.length} selected)`;
328
+ return `${tools.length}/${CHROME_DEVTOOLS_TOOL_NAMES.length} selected: ${tools.join(", ")}`;
329
+ }
330
+
331
+ async function persistSettings(
332
+ ctx: CommandContext,
333
+ selectedTools: readonly ChromeDevToolsToolName[],
334
+ ) {
335
+ try {
336
+ await saveSettings({ tools: [...selectedTools], updatedAt: Date.now() });
337
+ } catch (error) {
338
+ ctx.ui.notify(`Chrome DevTools settings save failed: ${formatError(error)}`, "warning");
339
+ }
340
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,189 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import {
4
+ formatPage,
5
+ getPage,
6
+ listPages,
7
+ resolvePage,
8
+ resolvePageForNavigation,
9
+ textResult,
10
+ withCdp,
11
+ } from "./cdp-client.js";
12
+ import { renderScreenshotResult, renderTextResult, renderToolCall, withStatus } from "./render.js";
13
+ import { state } from "./runtime.js";
14
+ import { formatScreenshotText, saveScreenshot, throwIfAborted } from "./screenshot.js";
15
+ import { CHROME_DEVTOOLS_TOOL_NAMES } from "./tool-names.js";
16
+
17
+ export const listPagesTool = defineTool({
18
+ name: CHROME_DEVTOOLS_TOOL_NAMES[0],
19
+ label: "Chrome DevTools: List Pages",
20
+ description: "List Chrome tabs/pages from a running Chrome DevTools Protocol endpoint.",
21
+ promptSnippet: "List Chrome tabs/pages available over Chrome DevTools Protocol",
22
+ parameters: Type.Object({}),
23
+ renderCall: renderToolCall("list pages"),
24
+ renderResult: renderTextResult,
25
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
26
+ return withStatus(ctx, "list pages", async () => {
27
+ const pages = await listPages();
28
+ return textResult(JSON.stringify(pages.map(formatPage), null, 2), { pages });
29
+ });
30
+ },
31
+ });
32
+
33
+ export const selectPageTool = defineTool({
34
+ name: CHROME_DEVTOOLS_TOOL_NAMES[1],
35
+ label: "Chrome DevTools: Select Page",
36
+ description: "Select the active Chrome page for later chrome_devtools_* tool calls.",
37
+ promptSnippet: "Select the Chrome tab/page to inspect or control",
38
+ parameters: Type.Object({
39
+ pageId: Type.String({ description: "Page id from chrome_devtools_list_pages." }),
40
+ }),
41
+ renderCall: renderToolCall("select page"),
42
+ renderResult: renderTextResult,
43
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
44
+ return withStatus(ctx, "select page", async () => {
45
+ const page = await getPage(params.pageId);
46
+ state.activePageId = page.id;
47
+ return textResult(`Selected page ${page.id}: ${page.title}\n${page.url}`, {
48
+ page: formatPage(page),
49
+ });
50
+ });
51
+ },
52
+ });
53
+
54
+ export const navigateTool = defineTool({
55
+ name: CHROME_DEVTOOLS_TOOL_NAMES[2],
56
+ label: "Chrome DevTools: Navigate",
57
+ description:
58
+ "Navigate a Chrome page to a URL through Chrome DevTools Protocol, creating a page first if none is available.",
59
+ promptSnippet: "Navigate the selected or first Chrome tab to a URL, creating one if needed",
60
+ parameters: Type.Object({
61
+ url: Type.String({ description: "URL to navigate to." }),
62
+ pageId: Type.Optional(
63
+ Type.String({ description: "Optional page id. Defaults to selected or first page." }),
64
+ ),
65
+ }),
66
+ renderCall: renderToolCall("navigate"),
67
+ renderResult: renderTextResult,
68
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
69
+ return withStatus(ctx, "navigate", async () => {
70
+ const { created, page } = await resolvePageForNavigation(params.pageId);
71
+ const result = await withCdp(page, async (client) => {
72
+ await client.send("Page.enable");
73
+ return client.send("Page.navigate", { url: params.url });
74
+ });
75
+
76
+ state.activePageId = page.id;
77
+ const action = created ? "Created page and navigated" : "Navigated";
78
+ return textResult(`${action} ${page.id} to ${params.url}`, {
79
+ created,
80
+ page: formatPage(page),
81
+ result,
82
+ });
83
+ });
84
+ },
85
+ });
86
+
87
+ export const evaluateTool = defineTool({
88
+ name: CHROME_DEVTOOLS_TOOL_NAMES[3],
89
+ label: "Chrome DevTools: Evaluate",
90
+ description: "Evaluate JavaScript in a Chrome page through Chrome DevTools Protocol.",
91
+ promptSnippet: "Evaluate JavaScript in the selected Chrome tab",
92
+ parameters: Type.Object({
93
+ expression: Type.String({ description: "JavaScript expression to evaluate." }),
94
+ pageId: Type.Optional(
95
+ Type.String({ description: "Optional page id. Defaults to selected or first page." }),
96
+ ),
97
+ awaitPromise: Type.Optional(
98
+ Type.Boolean({ description: "Whether to await a returned Promise. Defaults to true." }),
99
+ ),
100
+ }),
101
+ renderCall: renderToolCall("evaluate"),
102
+ renderResult: renderTextResult,
103
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
104
+ return withStatus(ctx, "evaluate", async () => {
105
+ const page = await resolvePage(params.pageId);
106
+ const result = await withCdp(page, (client) =>
107
+ client.send("Runtime.evaluate", {
108
+ expression: params.expression,
109
+ awaitPromise: params.awaitPromise ?? true,
110
+ returnByValue: true,
111
+ }),
112
+ );
113
+
114
+ state.activePageId = page.id;
115
+ return textResult(JSON.stringify(result, null, 2), { page: formatPage(page), result });
116
+ });
117
+ },
118
+ });
119
+
120
+ export const screenshotTool = defineTool({
121
+ name: CHROME_DEVTOOLS_TOOL_NAMES[4],
122
+ label: "Chrome DevTools: Screenshot",
123
+ description: "Capture a PNG screenshot from a Chrome page through Chrome DevTools Protocol.",
124
+ promptSnippet: "Capture a screenshot from the selected Chrome tab",
125
+ parameters: Type.Object({
126
+ pageId: Type.Optional(
127
+ Type.String({ description: "Optional page id. Defaults to selected or first page." }),
128
+ ),
129
+ fullPage: Type.Optional(
130
+ Type.Boolean({ description: "Capture the full document, not just the viewport." }),
131
+ ),
132
+ savePath: Type.Optional(
133
+ Type.String({
134
+ description:
135
+ "Screenshot is always saved as a PNG file. Optional output path; omitted defaults to a unique temp file. Relative paths resolve from the current working directory. A single leading @ is stripped to match Pi file-mention paths. Existing regular files are replaced.",
136
+ }),
137
+ ),
138
+ }),
139
+ renderCall: renderToolCall("screenshot"),
140
+ renderResult: renderScreenshotResult,
141
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
142
+ return withStatus(ctx, "screenshot", async () => {
143
+ const page = await resolvePage(params.pageId);
144
+ const result = await withCdp(page, async (client) => {
145
+ throwIfAborted(signal);
146
+ await client.send("Page.enable");
147
+
148
+ if (!params.fullPage) {
149
+ return client.send<{ data: string }>("Page.captureScreenshot", { format: "png" });
150
+ }
151
+
152
+ const metrics = await client.send<{
153
+ contentSize: { x: number; y: number; width: number; height: number };
154
+ }>("Page.getLayoutMetrics");
155
+
156
+ throwIfAborted(signal);
157
+ return client.send<{ data: string }>("Page.captureScreenshot", {
158
+ captureBeyondViewport: true,
159
+ format: "png",
160
+ clip: {
161
+ x: metrics.contentSize.x,
162
+ y: metrics.contentSize.y,
163
+ width: metrics.contentSize.width,
164
+ height: metrics.contentSize.height,
165
+ scale: 1,
166
+ },
167
+ });
168
+ });
169
+
170
+ state.activePageId = page.id;
171
+ const savedScreenshot = await saveScreenshot(result.data, params.savePath, ctx.cwd, signal);
172
+ return {
173
+ content: [
174
+ {
175
+ type: "text",
176
+ text: formatScreenshotText(page, savedScreenshot),
177
+ },
178
+ { type: "image", data: result.data, mimeType: "image/png" },
179
+ ],
180
+ details: {
181
+ page: formatPage(page),
182
+ bytes: savedScreenshot.bytes,
183
+ savedPath: savedScreenshot.savedPath,
184
+ isDefaultPath: savedScreenshot.isDefaultPath,
185
+ },
186
+ };
187
+ });
188
+ },
189
+ });