pi-chrome 0.15.54 → 0.15.55
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 +10 -0
- package/extensions/chrome-profile-bridge/browser-extension/manifest.json +1 -1
- package/extensions/chrome-profile-bridge/browser-extension/service_worker.js +98 -26
- package/extensions/chrome-profile-bridge/browser-extension/snapshot_injected.js +1 -9
- package/extensions/chrome-profile-bridge/index.ts +42 -19
- package/package.json +6 -2
- package/test-suite/unit/console-capture.test.mjs +122 -0
- package/test-suite/unit/prompt-section.test.mjs +52 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
All notable user-facing changes to `pi-chrome`.
|
|
4
4
|
|
|
5
|
+
## Unreleased
|
|
6
|
+
|
|
7
|
+
## 0.15.55 — 2026-09-26
|
|
8
|
+
|
|
9
|
+
- **Console capture no longer breaks sites with DevTools detection (#9).** Some sites (BOSS Zhipin) log an object with a getter or custom `toString` and close the tab if anything reads it, since only open DevTools would. The console capture serialized every logged argument immediately, so it tripped the check. Captured arguments are now stored as-is, and `chrome_list_console_messages` serializes them without running page code: data properties only, accessors shown as `[getter]`, and DOM nodes, regexes, dates and errors described through Chrome's native getters.
|
|
10
|
+
- **Early capture only in Pi's tabs.** The document-start console/network capture used to be injected into every page you opened. It now runs only in Pi's automation tab and in tabs tracked for a Pi session. Other tabs are not touched until a Pi tool acts on them.
|
|
11
|
+
- **Prompt-cache-friendly primer.** The Chrome primer is now contributed as a structured `chrome-profile-bridge` prompt section instead of a forced `systemPrompt` override. Previously the `before_agent_start` handler returned `systemPrompt` on every run (even while locked), which made pi collapse all system messages into a freshly rendered leading prompt each run. That disabled pi's append-only prompt/tool deltas for the whole session and busted the provider prompt cache when `/chrome authorize`, revoke, or expiry toggled the primer. Pi now appends a small section delta instead. Older pi versions without structured sections keep the previous append behavior.
|
|
12
|
+
- **Authorization log stays out of model context.** `pi-chrome-tool-change` records (authorize, reauthorize, revoke, expiry) are now session custom entries rendered in the transcript instead of model-facing custom messages. The model already sees the change through pi's tool and prompt-section delta, so the message was redundant context.
|
|
13
|
+
- **Validation.** New `prompt-section` unit suite.
|
|
14
|
+
|
|
5
15
|
## 0.15.54 — 2026-09-26
|
|
6
16
|
|
|
7
17
|
- **Hidden tabs report instead of silently dropping input.** Chrome ignores trusted input to hidden pages. A page is hidden when it is an inactive tab, its window is minimized, its window is fully covered by another window, or (on macOS) its window became a hidden window tab behind a full-screen window. In a hidden page, mouse presses and keys were dropped while the tool reported success, and mouse moves could hang until a timeout (the source of `Detached while handling command` in background runs). Input tools now check page visibility first. `chrome_type`, `chrome_key`, `chrome_hover`, `chrome_scroll`, `chrome_tap` and `chrome_drag` fail fast with the reason and the options (`background:false`, or `/chrome background off`). `chrome_click` and `chrome_fill` go straight to their existing DOM fallback and report the reason, or reject with `domFallback:false`. Hard background mode is unchanged: nothing is activated or focused.
|
|
@@ -2293,14 +2293,22 @@ async function unregisterInitScript(tabId) {
|
|
|
2293
2293
|
await cdp(tabId, "Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => undefined);
|
|
2294
2294
|
}
|
|
2295
2295
|
|
|
2296
|
-
//
|
|
2297
|
-
//
|
|
2298
|
-
//
|
|
2299
|
-
//
|
|
2300
|
-
// installPiChromeInstrumentation() call is idempotent.
|
|
2296
|
+
// Inject early console/network capture at document_start, but only into tabs Pi owns or has used
|
|
2297
|
+
// (its automation tab and tabs tracked for a session). Your other tabs are never patched. Catches
|
|
2298
|
+
// console messages, errors, and network requests that fire during page load, before chrome_snapshot
|
|
2299
|
+
// or chrome_evaluate install the instrumentation normally. installEarlyCapture sets __piChromeWrapped
|
|
2300
|
+
// flags so the post-hoc installPiChromeInstrumentation() call is idempotent.
|
|
2301
|
+
async function isPiTrackedTab(tabId) {
|
|
2302
|
+
await Promise.all([hydrateAutomationTargets(), hydrateSessionTabs()]);
|
|
2303
|
+
if (isPiChromeOwnedTarget(tabId)) return true;
|
|
2304
|
+
for (const tabs of sessionTabs.values()) if (tabs.has(tabId)) return true;
|
|
2305
|
+
return false;
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2301
2308
|
if (chrome.webNavigation && chrome.webNavigation.onCommitted) {
|
|
2302
|
-
chrome.webNavigation.onCommitted.addListener((details) => {
|
|
2309
|
+
chrome.webNavigation.onCommitted.addListener(async (details) => {
|
|
2303
2310
|
if (details.frameId !== 0) return;
|
|
2311
|
+
if (!(await isPiTrackedTab(details.tabId).catch(() => false))) return;
|
|
2304
2312
|
chrome.scripting.executeScript({
|
|
2305
2313
|
target: { tabId: details.tabId, frameIds: [0] },
|
|
2306
2314
|
world: "MAIN",
|
|
@@ -2592,15 +2600,9 @@ function installPiChromeInstrumentation() {
|
|
|
2592
2600
|
level,
|
|
2593
2601
|
timestamp: Date.now(),
|
|
2594
2602
|
url: location.href,
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
if (arg instanceof Error) return { name: arg.name, message: arg.message, stack: arg.stack };
|
|
2599
|
-
return JSON.parse(JSON.stringify(arg));
|
|
2600
|
-
} catch {
|
|
2601
|
-
return String(arg);
|
|
2602
|
-
}
|
|
2603
|
-
}),
|
|
2603
|
+
// Keep the raw values and serialize only when Pi lists messages. Serializing here reads every
|
|
2604
|
+
// logged object (getters, toString), which is exactly what anti-DevTools checks watch for.
|
|
2605
|
+
args: Array.from(args),
|
|
2604
2606
|
});
|
|
2605
2607
|
if (state.console.length > 500) state.console.splice(0, state.console.length - 500);
|
|
2606
2608
|
};
|
|
@@ -2715,15 +2717,7 @@ function installEarlyCapture() {
|
|
|
2715
2717
|
level: level,
|
|
2716
2718
|
timestamp: Date.now(),
|
|
2717
2719
|
url: location.href,
|
|
2718
|
-
args: Array.from(args)
|
|
2719
|
-
try {
|
|
2720
|
-
if (typeof arg === "string") return arg;
|
|
2721
|
-
if (arg instanceof Error) return { name: arg.name, message: arg.message, stack: arg.stack };
|
|
2722
|
-
return JSON.parse(JSON.stringify(arg));
|
|
2723
|
-
} catch (e) {
|
|
2724
|
-
return String(arg);
|
|
2725
|
-
}
|
|
2726
|
-
}),
|
|
2720
|
+
args: Array.from(args), // raw; serialized on read (see listConsoleMessages)
|
|
2727
2721
|
});
|
|
2728
2722
|
if (state.console.length > 500) state.console.splice(0, state.console.length - 500);
|
|
2729
2723
|
}
|
|
@@ -2917,7 +2911,7 @@ async function clickPage(selector, uid, x, y) {
|
|
|
2917
2911
|
// Inspect recent console errors for activation-gate rejections.
|
|
2918
2912
|
const recent = (state.console || []).slice(-8);
|
|
2919
2913
|
const hit = recent.find((e) => /NotAllowedError|Document is not focused|requires transient activation|gesture is required/.test(
|
|
2920
|
-
(e.args || []).map((a) => typeof a === "string" ? a :
|
|
2914
|
+
(e.args || []).map((a) => typeof a === "string" ? a : a instanceof Error ? a.message : "").join(" ")
|
|
2921
2915
|
));
|
|
2922
2916
|
if (hit) { suggestChromeInput = true; suggestReason = "recent console error indicates user-activation gate"; }
|
|
2923
2917
|
}
|
|
@@ -3285,7 +3279,85 @@ async function pressKeyInPage(key) {
|
|
|
3285
3279
|
function listConsoleMessages(clear) {
|
|
3286
3280
|
installPiChromeInstrumentation();
|
|
3287
3281
|
const state = getPiChromeState();
|
|
3288
|
-
|
|
3282
|
+
// Serialize without running page code. Anti-DevTools checks log objects with getters or a custom
|
|
3283
|
+
// toString and treat any call as "DevTools is open" (issue #9). Copy data properties only, report
|
|
3284
|
+
// accessors as "[getter]" without calling them, and describe built-ins through native getters.
|
|
3285
|
+
const nativeSource = Function.prototype.toString;
|
|
3286
|
+
const isNative = (fn) => { try { return typeof fn === "function" && nativeSource.call(fn).includes("[native code]"); } catch { return false; } };
|
|
3287
|
+
const protoGetter = (proto, key) => { try { return Object.getOwnPropertyDescriptor(proto, key)?.get; } catch { return undefined; } };
|
|
3288
|
+
const callGetter = (proto, key, value) => { const get = protoGetter(proto, key); return get ? get.call(value) : undefined; };
|
|
3289
|
+
const dataProp = (value, key) => {
|
|
3290
|
+
for (let obj = value, hops = 0; obj && hops < 20; obj = Object.getPrototypeOf(obj), hops++) {
|
|
3291
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
3292
|
+
if (!desc) continue;
|
|
3293
|
+
if ("value" in desc) return { ok: true, value: desc.value };
|
|
3294
|
+
return isNative(desc.get) ? { ok: true, value: desc.get.call(value) } : { ok: false };
|
|
3295
|
+
}
|
|
3296
|
+
return { ok: true, value: undefined };
|
|
3297
|
+
};
|
|
3298
|
+
const serialize = (value, depth = 0, seen = new Set()) => {
|
|
3299
|
+
try {
|
|
3300
|
+
const type = typeof value;
|
|
3301
|
+
if (value === null || type === "string" || type === "boolean") return value;
|
|
3302
|
+
if (type === "number") return Number.isFinite(value) ? value : String(value);
|
|
3303
|
+
if (type === "undefined") return "undefined";
|
|
3304
|
+
if (type === "bigint") return `${BigInt.prototype.toString.call(value)}n`;
|
|
3305
|
+
if (type === "symbol") return Symbol.prototype.toString.call(value);
|
|
3306
|
+
if (type === "function") {
|
|
3307
|
+
const name = dataProp(value, "name");
|
|
3308
|
+
return `[function ${name.ok && typeof name.value === "string" && name.value ? name.value : "anonymous"}]`;
|
|
3309
|
+
}
|
|
3310
|
+
if (seen.has(value)) return "[circular]";
|
|
3311
|
+
if (value instanceof Error) {
|
|
3312
|
+
const out = {};
|
|
3313
|
+
for (const key of ["name", "message"]) {
|
|
3314
|
+
const prop = dataProp(value, key);
|
|
3315
|
+
out[key] = prop.ok ? (typeof prop.value === "string" ? prop.value : serialize(prop.value, depth + 1, seen)) : "[getter]";
|
|
3316
|
+
}
|
|
3317
|
+
// V8 formats `stack` lazily from name/message, so only read it when both are plain data.
|
|
3318
|
+
const stack = out.name !== "[getter]" && out.message !== "[getter]" ? dataProp(value, "stack") : { ok: false };
|
|
3319
|
+
out.stack = stack.ok ? (typeof stack.value === "string" ? stack.value : undefined) : "[getter]";
|
|
3320
|
+
return out;
|
|
3321
|
+
}
|
|
3322
|
+
if (value instanceof Date) return Date.prototype.toISOString.call(value);
|
|
3323
|
+
if (value instanceof RegExp) return `/${callGetter(RegExp.prototype, "source", value)}/${callGetter(RegExp.prototype, "flags", value)}`;
|
|
3324
|
+
if (typeof Node !== "undefined" && value instanceof Node) {
|
|
3325
|
+
const name = String(callGetter(Node.prototype, "nodeName", value) || "node").toLowerCase();
|
|
3326
|
+
if (typeof Element === "undefined" || !(value instanceof Element)) return `<${name}>`;
|
|
3327
|
+
const id = callGetter(Element.prototype, "id", value);
|
|
3328
|
+
const cls = String(callGetter(Element.prototype, "className", value) || "").trim().split(/\s+/).filter(Boolean).slice(0, 3);
|
|
3329
|
+
return `<${name}${id ? `#${id}` : ""}${cls.map((c) => `.${c}`).join("")}>`;
|
|
3330
|
+
}
|
|
3331
|
+
if (value instanceof Map) return `[Map(${callGetter(Map.prototype, "size", value)})]`;
|
|
3332
|
+
if (value instanceof Set) return `[Set(${callGetter(Set.prototype, "size", value)})]`;
|
|
3333
|
+
if (depth >= 4) return Array.isArray(value) ? "[array]" : "[object]";
|
|
3334
|
+
seen.add(value);
|
|
3335
|
+
if (Array.isArray(value)) {
|
|
3336
|
+
const length = dataProp(value, "length");
|
|
3337
|
+
const n = length.ok ? Math.min(Number(length.value) || 0, 50) : 0;
|
|
3338
|
+
const out = [];
|
|
3339
|
+
for (let i = 0; i < n; i++) {
|
|
3340
|
+
const item = dataProp(value, String(i));
|
|
3341
|
+
out.push(item.ok ? serialize(item.value, depth + 1, seen) : "[getter]");
|
|
3342
|
+
}
|
|
3343
|
+
if (length.ok && length.value > 50) out.push(`[${length.value - 50} more]`);
|
|
3344
|
+
seen.delete(value);
|
|
3345
|
+
return out;
|
|
3346
|
+
}
|
|
3347
|
+
const out = {};
|
|
3348
|
+
const keys = Object.keys(value);
|
|
3349
|
+
for (const key of keys.slice(0, 50)) {
|
|
3350
|
+
const desc = Object.getOwnPropertyDescriptor(value, key);
|
|
3351
|
+
out[key] = desc && "value" in desc ? serialize(desc.value, depth + 1, seen) : "[getter]";
|
|
3352
|
+
}
|
|
3353
|
+
if (keys.length > 50) out["…"] = `${keys.length - 50} more keys`;
|
|
3354
|
+
seen.delete(value);
|
|
3355
|
+
return out;
|
|
3356
|
+
} catch {
|
|
3357
|
+
return "[unserializable]";
|
|
3358
|
+
}
|
|
3359
|
+
};
|
|
3360
|
+
const messages = state.console.map((entry) => ({ ...entry, args: Array.from(entry.args || [], (arg) => serialize(arg)) }));
|
|
3289
3361
|
if (clear) state.console = [];
|
|
3290
3362
|
return { messages, count: messages.length };
|
|
3291
3363
|
}
|
|
@@ -125,15 +125,7 @@
|
|
|
125
125
|
level,
|
|
126
126
|
timestamp: Date.now(),
|
|
127
127
|
url: location.href,
|
|
128
|
-
args: Array.from(args)
|
|
129
|
-
try {
|
|
130
|
-
if (typeof arg === "string") return arg;
|
|
131
|
-
if (arg instanceof Error) return { name: arg.name, message: arg.message, stack: arg.stack };
|
|
132
|
-
return JSON.parse(JSON.stringify(arg));
|
|
133
|
-
} catch {
|
|
134
|
-
return String(arg);
|
|
135
|
-
}
|
|
136
|
-
}),
|
|
128
|
+
args: Array.from(args), // raw; serialized on read by listConsoleMessages
|
|
137
129
|
});
|
|
138
130
|
if (state.console.length > 500) state.console.splice(0, state.console.length - 500);
|
|
139
131
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
2
3
|
import { Type } from "typebox";
|
|
3
4
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
4
5
|
import { mkdir, readdir, unlink, writeFile } from "node:fs/promises";
|
|
@@ -801,6 +802,14 @@ const CHROME_TOOL_NAMES = [
|
|
|
801
802
|
"chrome_cdp_targets",
|
|
802
803
|
] as const;
|
|
803
804
|
const CHROME_TOOL_NAME_SET = new Set<string>(CHROME_TOOL_NAMES);
|
|
805
|
+
const CHROME_TOOL_CHANGE_ENTRY = "pi-chrome-tool-change";
|
|
806
|
+
type ChromeToolChangeEntry = {
|
|
807
|
+
content: string;
|
|
808
|
+
action: "authorized" | "reauthorized" | "revoked" | "expired";
|
|
809
|
+
tools: string[];
|
|
810
|
+
authorizedUntil?: number | "indefinite";
|
|
811
|
+
at: number;
|
|
812
|
+
};
|
|
804
813
|
|
|
805
814
|
function StringEnum<T extends readonly [string, ...string[]]>(values: T) {
|
|
806
815
|
return Type.Union(values.map((value) => Type.Literal(value)) as [ReturnType<typeof Type.Literal>, ...ReturnType<typeof Type.Literal>[]]);
|
|
@@ -890,17 +899,15 @@ export default function (pi: ExtensionAPI): void {
|
|
|
890
899
|
: action === "expired"
|
|
891
900
|
? "Chrome tools disabled because /chrome authorize grant expired."
|
|
892
901
|
: "Chrome tools disabled by /chrome revoke.";
|
|
893
|
-
|
|
894
|
-
|
|
902
|
+
// Session-history log only (custom entry, not sent to the model). The model already learns about
|
|
903
|
+
// the change from pi's tool/prompt-section delta, so a model-facing message would be redundant.
|
|
904
|
+
pi.appendEntry<ChromeToolChangeEntry>(CHROME_TOOL_CHANGE_ENTRY, {
|
|
895
905
|
content,
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
at: Date.now(),
|
|
902
|
-
},
|
|
903
|
-
}, { triggerTurn: false });
|
|
906
|
+
action,
|
|
907
|
+
tools: [...CHROME_TOOL_NAMES],
|
|
908
|
+
authorizedUntil: options.authorizedUntil,
|
|
909
|
+
at: Date.now(),
|
|
910
|
+
});
|
|
904
911
|
};
|
|
905
912
|
|
|
906
913
|
// Bound the entire request, including shared-owner forwarding/takeover. Revoke can launch
|
|
@@ -1088,6 +1095,12 @@ export default function (pi: ExtensionAPI): void {
|
|
|
1088
1095
|
updateChromeStatus(ctx);
|
|
1089
1096
|
});
|
|
1090
1097
|
|
|
1098
|
+
// Render authorization log entries in the transcript. Custom entries never reach the model.
|
|
1099
|
+
pi.registerEntryRenderer?.<ChromeToolChangeEntry>(CHROME_TOOL_CHANGE_ENTRY, (entry, _options, theme) => {
|
|
1100
|
+
const content = entry.data?.content ?? "Chrome authorization changed.";
|
|
1101
|
+
return new Text(theme.fg("dim", `[pi-chrome] ${content}`), 1, 0);
|
|
1102
|
+
});
|
|
1103
|
+
|
|
1091
1104
|
pi.on("session_shutdown", async (event) => {
|
|
1092
1105
|
clearAuthExpiryTimer();
|
|
1093
1106
|
clearCountdownInterval();
|
|
@@ -1100,13 +1113,26 @@ export default function (pi: ExtensionAPI): void {
|
|
|
1100
1113
|
}
|
|
1101
1114
|
});
|
|
1102
1115
|
|
|
1116
|
+
// Contribute the primer as a named prompt section instead of returning `systemPrompt`.
|
|
1117
|
+
// Returning `systemPrompt` forces a whole-prompt override, which makes pi collapse every system
|
|
1118
|
+
// message into a new leading prompt each run (busting the provider prompt cache and disabling
|
|
1119
|
+
// pi's append-only section/tool deltas for all extensions). Mutating `systemPromptOptions.sections`
|
|
1120
|
+
// lets pi diff the section and append a small system-message delta when it appears/disappears.
|
|
1103
1121
|
pi.on("before_agent_start", (event) => {
|
|
1104
|
-
|
|
1105
|
-
|
|
1122
|
+
const active = chromeToolsRegistered && chromeControlAuthorized();
|
|
1123
|
+
const sections = (event as { systemPromptOptions?: { sections?: Record<string, string> } }).systemPromptOptions?.sections;
|
|
1124
|
+
if (sections) {
|
|
1125
|
+
if (active) sections[CHROME_PRIMER_SECTION] = CHROME_PRIMER;
|
|
1126
|
+
else delete sections[CHROME_PRIMER_SECTION];
|
|
1127
|
+
return undefined;
|
|
1106
1128
|
}
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1129
|
+
// Legacy pi without structured prompt sections: append the primer to the rendered prompt.
|
|
1130
|
+
if (!active) return undefined;
|
|
1131
|
+
return { systemPrompt: `${event.systemPrompt}\n<${CHROME_PRIMER_SECTION}>\n${CHROME_PRIMER}\n</${CHROME_PRIMER_SECTION}>` };
|
|
1132
|
+
});
|
|
1133
|
+
|
|
1134
|
+
const CHROME_PRIMER_SECTION = "chrome-profile-bridge";
|
|
1135
|
+
const CHROME_PRIMER = `Chrome control is available through the chrome_* tools via a companion Chrome extension installed in the user's normal Chrome profile. Tools target the existing signed-in profile: no remote-debug port, no throwaway profile.
|
|
1110
1136
|
|
|
1111
1137
|
Tab/window isolation (important):
|
|
1112
1138
|
- pi-chrome owns a dedicated automation window/tab. When a chrome_* tool runs with no explicit target, it acts on that pi-chrome-owned target — it never reuses or overwrites the user's currently active tab. The dedicated target is created on first use and reused afterward.
|
|
@@ -1130,10 +1156,7 @@ Usage rules:
|
|
|
1130
1156
|
5. \`chrome_navigate\` supports an optional \`initScript\` that runs at document_start in MAIN world for the next navigation (good for seeding localStorage or stubbing Date.now).
|
|
1131
1157
|
6. /chrome background on (default) is a hard policy: per-call \`background=false\` cannot override it, new tabs stay inactive, and \`chrome_tab activate\` is blocked. Ask the user to run /chrome background off when they want foreground/watch mode. With background off, per-call \`background=true\` still avoids explicit focus/tab activation. Screenshots use CDP without activating background tabs; debugger failures never fall back to tab activation. Page scripts, trusted input, native prompts, and Chrome/OS behavior can still affect focus.
|
|
1132
1158
|
7. If you hit a native file-picker or privileged browser prompt gate, tell the user; generic clicks/typing/CSP gates are handled by Chrome input.
|
|
1133
|
-
8. Run /chrome doctor when in doubt about connectivity or capabilities
|
|
1134
|
-
</chrome-profile-bridge>`;
|
|
1135
|
-
return { systemPrompt: event.systemPrompt + primer };
|
|
1136
|
-
});
|
|
1159
|
+
8. Run /chrome doctor when in doubt about connectivity or capabilities.`;
|
|
1137
1160
|
|
|
1138
1161
|
// Shared handlers, dispatched by the unified /chrome command below.
|
|
1139
1162
|
const doctorHandler = async (ctx: ExtensionContext) => {
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-chrome",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.55",
|
|
4
4
|
"scripts": {
|
|
5
|
-
"test": "node test-suite/unit/csp-eval.test.mjs && node test-suite/unit/automation-target.test.mjs && node test-suite/unit/session-cleanup.test.mjs && node test-suite/unit/background-policy.test.mjs && node test-suite/unit/input-reliability.test.mjs && node test-suite/unit/chrome-command.test.mjs && node test-suite/unit/bridge-resilience.test.mjs && node test-suite/unit/cdp-passthrough.test.mjs && node test-suite/unit/type-evidence.test.mjs && node test-suite/unit/hidden-input.test.mjs",
|
|
5
|
+
"test": "node test-suite/unit/csp-eval.test.mjs && node test-suite/unit/automation-target.test.mjs && node test-suite/unit/session-cleanup.test.mjs && node test-suite/unit/background-policy.test.mjs && node test-suite/unit/input-reliability.test.mjs && node test-suite/unit/chrome-command.test.mjs && node test-suite/unit/bridge-resilience.test.mjs && node test-suite/unit/cdp-passthrough.test.mjs && node test-suite/unit/type-evidence.test.mjs && node test-suite/unit/hidden-input.test.mjs && node test-suite/unit/console-capture.test.mjs && node test-suite/unit/prompt-section.test.mjs",
|
|
6
6
|
"version": "node scripts/sync-manifest-version.js",
|
|
7
7
|
"prepublishOnly": "node scripts/sync-manifest-version.js"
|
|
8
8
|
},
|
|
@@ -67,12 +67,16 @@
|
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
69
|
"@earendil-works/pi-coding-agent": "*",
|
|
70
|
+
"@earendil-works/pi-tui": "*",
|
|
70
71
|
"typebox": "*"
|
|
71
72
|
},
|
|
72
73
|
"peerDependenciesMeta": {
|
|
73
74
|
"@earendil-works/pi-coding-agent": {
|
|
74
75
|
"optional": true
|
|
75
76
|
},
|
|
77
|
+
"@earendil-works/pi-tui": {
|
|
78
|
+
"optional": true
|
|
79
|
+
},
|
|
76
80
|
"typebox": {
|
|
77
81
|
"optional": true
|
|
78
82
|
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Console capture must not trip anti-DevTools checks (issue #9) and must only touch Pi's tabs.
|
|
2
|
+
// Sites detect DevTools by logging an object whose getter/toString fires when something inspects
|
|
3
|
+
// it. Closed DevTools never does; our capture used to serialize every argument immediately.
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import vm from "node:vm";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
|
|
9
|
+
const workerSource = fs.readFileSync(new URL("../../extensions/chrome-profile-bridge/browser-extension/service_worker.js", import.meta.url), "utf8");
|
|
10
|
+
const snapshotSource = fs.readFileSync(new URL("../../extensions/chrome-profile-bridge/browser-extension/snapshot_injected.js", import.meta.url), "utf8");
|
|
11
|
+
|
|
12
|
+
function loadWorker() {
|
|
13
|
+
const navListeners = [];
|
|
14
|
+
const injected = [];
|
|
15
|
+
const noop = { addListener() {}, removeListener() {} };
|
|
16
|
+
const chrome = {
|
|
17
|
+
runtime: { id: "test", getManifest: () => ({ version: "0.0.0" }), onInstalled: noop, onStartup: noop },
|
|
18
|
+
alarms: { create() {}, onAlarm: noop }, action: { onClicked: noop },
|
|
19
|
+
webNavigation: { onCommitted: { addListener: (fn) => navListeners.push(fn) } },
|
|
20
|
+
debugger: { onDetach: noop, onEvent: noop },
|
|
21
|
+
storage: { session: { get: async () => ({}), set: async () => {} } },
|
|
22
|
+
scripting: { executeScript: async (options) => { injected.push(options); return []; } },
|
|
23
|
+
tabs: { get: async () => null },
|
|
24
|
+
};
|
|
25
|
+
const w = { chrome, console, setTimeout, clearTimeout, setInterval: () => 0, navigator: { userAgent: "unit-test" }, fetch: async () => { throw new Error("offline"); } };
|
|
26
|
+
w.self = w;
|
|
27
|
+
vm.runInNewContext(workerSource, w);
|
|
28
|
+
const commit = async (tabId, frameId = 0) => {
|
|
29
|
+
for (const fn of navListeners) await fn({ tabId, frameId, url: "https://site.test/" });
|
|
30
|
+
};
|
|
31
|
+
return { w, injected, commit };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A page world whose console records native calls and a DevTools trap object.
|
|
35
|
+
function pageWorld() {
|
|
36
|
+
const nativeCalls = [];
|
|
37
|
+
const trap = { tripped: 0 };
|
|
38
|
+
const page = vm.createContext({
|
|
39
|
+
console: Object.fromEntries(["debug", "log", "info", "warn", "error"].map((l) => [l, (...a) => nativeCalls.push([l, ...a])])),
|
|
40
|
+
location: { href: "https://site.test/" },
|
|
41
|
+
addEventListener() {},
|
|
42
|
+
fetch: undefined, XMLHttpRequest: undefined,
|
|
43
|
+
});
|
|
44
|
+
page.window = page;
|
|
45
|
+
page.trip = () => { trap.tripped++; };
|
|
46
|
+
vm.runInContext(`
|
|
47
|
+
var bait = { name: "bait" };
|
|
48
|
+
Object.defineProperty(bait, "id", { enumerable: true, get() { trip(); return "x"; } });
|
|
49
|
+
bait.toString = function toString() { trip(); return "bait"; };
|
|
50
|
+
var trapError = new Error("trap");
|
|
51
|
+
Object.defineProperty(trapError, "message", { get() { trip(); return "m"; } });
|
|
52
|
+
var trapRegex = /a+/g;
|
|
53
|
+
trapRegex.toString = function () { trip(); return "re"; };
|
|
54
|
+
Object.defineProperty(trapRegex, "source", { get() { trip(); return "x"; } });
|
|
55
|
+
var trapDate = new Date(0);
|
|
56
|
+
trapDate.toString = function () { trip(); return "d"; };
|
|
57
|
+
`, page);
|
|
58
|
+
return { page, trap, nativeCalls };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const fnSource = (name) => {
|
|
62
|
+
const start = workerSource.indexOf(`function ${name}(`);
|
|
63
|
+
let depth = 0;
|
|
64
|
+
for (let i = workerSource.indexOf("{", start); i < workerSource.length; i++) {
|
|
65
|
+
if (workerSource[i] === "{") depth++;
|
|
66
|
+
else if (workerSource[i] === "}" && --depth === 0) return workerSource.slice(start, i + 1);
|
|
67
|
+
}
|
|
68
|
+
throw new Error(`missing ${name}`);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
for (const [label, install] of [
|
|
72
|
+
["early capture", (page) => vm.runInContext(`(${fnSource("installEarlyCapture")})()`, page)],
|
|
73
|
+
["post-hoc instrumentation", (page) => vm.runInContext(`${fnSource("getPiChromeState")}\n(${fnSource("installPiChromeInstrumentation")})()`, page)],
|
|
74
|
+
["snapshot_injected instrumentation", (page) => { vm.runInContext(snapshotSource, page); }],
|
|
75
|
+
]) {
|
|
76
|
+
test(`${label}: logging an object does not read it until Pi lists messages`, () => {
|
|
77
|
+
const { page, trap, nativeCalls } = pageWorld();
|
|
78
|
+
install(page);
|
|
79
|
+
if (label.startsWith("snapshot")) {
|
|
80
|
+
// snapshot_injected installs lazily through its snapshot entry point; force the install.
|
|
81
|
+
assert.equal(typeof page.__piChromeSnapshotPage, "function");
|
|
82
|
+
try { page.__piChromeSnapshotPage({}); } catch {}
|
|
83
|
+
}
|
|
84
|
+
vm.runInContext("console.log('hello', bait); console.error(new Error('boom')); console.log(trapError, trapRegex, trapDate)", page);
|
|
85
|
+
assert.equal(trap.tripped, 0, "no getter/toString fired while the page runs");
|
|
86
|
+
assert.equal(nativeCalls.length, 3, "native console still receives the calls");
|
|
87
|
+
const listed = vm.runInContext(`${fnSource("getPiChromeState")}\n${fnSource("installPiChromeInstrumentation")}\n(${fnSource("listConsoleMessages")})(false)`, page);
|
|
88
|
+
assert.equal(trap.tripped, 0, "listing does not fire page getters or toString either");
|
|
89
|
+
assert.equal(listed.count, 3);
|
|
90
|
+
assert.equal(listed.messages[0].args[0], "hello");
|
|
91
|
+
assert.deepEqual(JSON.parse(JSON.stringify(listed.messages[0].args[1])), { name: "bait", id: "[getter]", toString: "[function toString]" });
|
|
92
|
+
assert.equal(listed.messages[1].args[0].message, "boom");
|
|
93
|
+
assert.match(listed.messages[1].args[0].stack, /boom/);
|
|
94
|
+
const [err, re, date] = listed.messages[2].args;
|
|
95
|
+
assert.equal(err.message, "[getter]");
|
|
96
|
+
assert.equal(re, "/a+/g", "regex described through native getters");
|
|
97
|
+
assert.equal(date, "1970-01-01T00:00:00.000Z");
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
test("listing survives values that cannot be serialized", () => {
|
|
102
|
+
const { page } = pageWorld();
|
|
103
|
+
vm.runInContext(`(${fnSource("installEarlyCapture")})()`, page);
|
|
104
|
+
vm.runInContext("const loop = { a: [1, 2n, undefined, Symbol('s')] }; loop.self = loop; console.log(loop); console.log(new Proxy({}, { ownKeys() { throw new Error('no'); } }), new Map([[1, 2]]), function named() {})", page);
|
|
105
|
+
const listed = vm.runInContext(`${fnSource("getPiChromeState")}\n${fnSource("installPiChromeInstrumentation")}\n(${fnSource("listConsoleMessages")})(true)`, page);
|
|
106
|
+
assert.equal(listed.count, 2);
|
|
107
|
+
assert.deepEqual(JSON.parse(JSON.stringify(listed.messages[0].args[0])), { a: [1, "2n", "undefined", "Symbol(s)"], self: "[circular]" });
|
|
108
|
+
assert.deepEqual(JSON.parse(JSON.stringify(listed.messages[1].args)), ["[unserializable]", "[Map(1)]", "[function named]"]);
|
|
109
|
+
assert.equal(vm.runInContext("window.__PI_CHROME_STATE__.console.length", page), 0, "clear still empties the buffer");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("early capture is injected only into tabs Pi owns or tracks", async () => {
|
|
113
|
+
const h = loadWorker();
|
|
114
|
+
await h.commit(10);
|
|
115
|
+
assert.equal(h.injected.length, 0, "a user tab is never patched");
|
|
116
|
+
vm.runInContext("automationTargets.set('s', { tabId: 11 }); sessionTabs.set('s', new Map([[12, { created: true }]]));", h.w);
|
|
117
|
+
await h.commit(11);
|
|
118
|
+
await h.commit(12);
|
|
119
|
+
await h.commit(11, 3); // subframe
|
|
120
|
+
assert.deepEqual(h.injected.map((o) => o.target.tabId), [11, 12]);
|
|
121
|
+
assert.ok(h.injected.every((o) => o.func.name === "installEarlyCapture" && o.injectImmediately === true));
|
|
122
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// The Chrome primer must be a structured prompt section, never a forced `systemPrompt` override.
|
|
2
|
+
// A forced override makes pi collapse all system messages into a new leading prompt every run,
|
|
3
|
+
// which busts the provider prompt cache.
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import vm from "node:vm";
|
|
7
|
+
import { stripTypeScriptTypes } from "node:module";
|
|
8
|
+
import { test } from "node:test";
|
|
9
|
+
|
|
10
|
+
const source = fs.readFileSync(new URL("../../extensions/chrome-profile-bridge/index.ts", import.meta.url), "utf8");
|
|
11
|
+
const from = source.indexOf('pi.on("before_agent_start",');
|
|
12
|
+
const to = source.indexOf("// Shared handlers,", from);
|
|
13
|
+
assert.ok(from >= 0 && to > from, "Missing before_agent_start section");
|
|
14
|
+
const handlerSource = stripTypeScriptTypes(source.slice(from, to));
|
|
15
|
+
|
|
16
|
+
function load({ registered = true, authorized = true } = {}) {
|
|
17
|
+
let handler;
|
|
18
|
+
const pi = { on: (name, fn) => { if (name === "before_agent_start") handler = fn; } };
|
|
19
|
+
vm.runInNewContext(`${handlerSource}`, {
|
|
20
|
+
pi,
|
|
21
|
+
chromeToolsRegistered: registered,
|
|
22
|
+
chromeControlAuthorized: () => authorized,
|
|
23
|
+
});
|
|
24
|
+
return handler;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
test("authorized: adds primer section and does not force systemPrompt", () => {
|
|
28
|
+
const event = { systemPrompt: "base", systemPromptOptions: { sections: {} } };
|
|
29
|
+
const result = load()(event);
|
|
30
|
+
assert.equal(result, undefined);
|
|
31
|
+
const primer = event.systemPromptOptions.sections["chrome-profile-bridge"];
|
|
32
|
+
assert.match(primer, /^Chrome control is available/);
|
|
33
|
+
assert.doesNotMatch(primer, /<\/?chrome-profile-bridge>/, "pi wraps sections in their tag");
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("locked: removes primer section and does not force systemPrompt", () => {
|
|
37
|
+
const event = { systemPrompt: "base", systemPromptOptions: { sections: { "chrome-profile-bridge": "stale", other: "keep" } } };
|
|
38
|
+
assert.equal(load({ authorized: false })(event), undefined);
|
|
39
|
+
assert.deepEqual(event.systemPromptOptions.sections, { other: "keep" });
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("tools not registered: no primer", () => {
|
|
43
|
+
const event = { systemPrompt: "base", systemPromptOptions: { sections: {} } };
|
|
44
|
+
assert.equal(load({ registered: false })(event), undefined);
|
|
45
|
+
assert.deepEqual(event.systemPromptOptions.sections, {});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("legacy pi without sections: appends only when authorized", () => {
|
|
49
|
+
assert.equal(load({ authorized: false })({ systemPrompt: "base" }), undefined);
|
|
50
|
+
const result = load()({ systemPrompt: "base" });
|
|
51
|
+
assert.match(result.systemPrompt, /^base\n<chrome-profile-bridge>\nChrome control is available[\s\S]*<\/chrome-profile-bridge>$/);
|
|
52
|
+
});
|