agents/openai.yaml
interface:
display_name: "SAP Browser Automation"
short_description: "Use when an agent must inspect or operate an authenticated SA..."
default_prompt: "Use $sap-browser-automation to work with SAP Browser Automation."
policy:
allow_implicit_invocation: true
README.md
# SAP Browser Automation
Authenticated SAP web interface automation through an in-app Browser, isolated Microsoft Edge CDP profiles, or an existing Playwright client.
## Capability Index
| Capability | Status |
| --- | --- |
| Commands | No |
| Agents | No |
| Hooks | No |
| MCP | No |
| LSP | No |
| Source Freshness | `last_verified`: 2026-07-14; public documentation review and local Edge/Node fixture evidence |
| Verification | Live SAP tenant, enterprise SSO, client certificates, MFA, and in-app Browser execution remain pending |
Primary resources:
- `SKILL.md`
- `references/auth-state-bootstrap.md`
- `references/edge-cdp-control.md`
- `references/in-app-browser-auth.md`
- `scripts/cdp-agent.mjs`
- `scripts/edge-profile.ps1`
The default workflow reuses authentication only through approved local browser mechanisms. It never accepts passwords or exports persistent authentication material to the repository.
references/auth-state-bootstrap.md
# Authenticated Edge Profile and State Bootstrap
Documentation Source: `docs/project/sap-browser-automation-source-review-2026-07-14.md`
Profile cloning is the durable base, but normal Edge may discard session cookies when it closes.
Therefore capture volatile state from the still-running authenticated source before shutdown, then clone,
launch, verify, and import only when necessary.
## 1. Confirm the source
Confirm the approved SAP tenant, normal Edge user-data root, selected `Default` or `Profile N`, target
host/path/title, required cookie origins, automation root, and temporary state-file path. The normal Edge
user-data root is usually `%LOCALAPPDATA%/Microsoft/Edge/User Data`; use `edge://version` to identify the
active profile.
## 2. Enable live source CDP
Keep normal Edge open on the visibly authenticated SAP page. Open
`edge://inspect/#remote-debugging`, enable **Allow remote debugging for this browser instance**, and wait
for `DevToolsActivePort` under the normal user-data root. Do not close Edge yet.
List and narrow targets until exactly one approved page matches:
```powershell
$skillRoot = 'plugins/sap-browser-automation/skills/sap-browser-automation'
$normalEdge = Join-Path $env:LOCALAPPDATA 'Microsoft/Edge/User Data'
$stateFile = Join-Path $env:LOCALAPPDATA 'Codex/SAP-Browser-Automation/auth-state.json'
node "$skillRoot/scripts/cdp-agent.mjs" targets `
--user-data-dir $normalEdge `
--host $env:SAP_TENANT_HOST `
--path-contains $env:SAP_TARGET_PATH
```
## 3. Export before closing Edge
Run `cdp-agent.mjs export-auth` while the authenticated source target is alive:
```powershell
node "$skillRoot/scripts/cdp-agent.mjs" export-auth `
--user-data-dir $normalEdge `
--host $env:SAP_TENANT_HOST `
--path-contains $env:SAP_TARGET_PATH `
--title-contains $env:SAP_TARGET_TITLE `
--origin $env:SAP_TENANT_ORIGIN `
--origin $env:SAP_IDP_ORIGIN `
--state-file $stateFile
```
The helper uses browser-level CDP `Storage.getCookies`, filters cookies to the repeated `--origin` and
optional `--cookie-domain` scopes, and captures the selected page's top-origin `localStorage` and
`sessionStorage`. The command prints counts and the state-file path, not cookie or storage values.
## 4. Close, clone, and launch
Close normal Edge completely. Then clone into a new or empty automation root:
```powershell
$automation = Join-Path $env:LOCALAPPDATA 'Codex/SAP-Automation-Edge-20260714'
powershell -NoProfile -ExecutionPolicy Bypass -File "$skillRoot/scripts/edge-profile.ps1" `
-Action CloneLaunch `
-SourceUserData $normalEdge `
-ProfileName 'Default' `
-AutomationRoot $automation `
-TargetUrl $env:SAP_TARGET_URL
```
`CloneLaunch` refuses a populated destination. To retain a previously authenticated isolated profile,
use `-Action LaunchExisting` instead of copying over it.
## 5. Verify and import if needed
Inspect the isolated target first because persistent profile state may already be sufficient:
```powershell
node "$skillRoot/scripts/cdp-agent.mjs" inspect `
--user-data-dir $automation `
--host $env:SAP_TENANT_HOST `
--path-contains $env:SAP_TARGET_PATH
```
If the target is not authenticated, run `cdp-agent.mjs import-auth` to inject the pre-close state:
```powershell
node "$skillRoot/scripts/cdp-agent.mjs" import-auth `
--user-data-dir $automation `
--host $env:SAP_TENANT_HOST `
--path-contains $env:SAP_TARGET_PATH `
--state-file $stateFile
```
Import maps exported cookies to CDP cookie parameters and applies them with `Storage.setCookies`. It
installs an origin-keyed preload for local/session storage, applies it immediately to the selected page,
reloads, and waits for readiness. Re-run `inspect` and verify a visible signed-in signal; successful
import is not itself authentication evidence.
## Optional existing Playwright
If Playwright is already installed, it may attach to the isolated Edge instance or consume an adapted
state object. Playwright storage state includes cookies, local storage, and optional IndexedDB but not
session storage, so retain the origin-keyed preload when the application uses session storage. Do not
install Playwright for this workflow.
## Final fallback and cleanup
If profile cloning plus state import still redirects to SSO, complete one manual login in the isolated
profile and reuse that profile with `LaunchExisting`. Delete the temporary state file after the isolated
session has been verified and no further import is needed. Keep the isolated profile only when the user
wants subsequent reuse.
references/edge-cdp-control.md
# Edge/CDP Control
Documentation Source: `docs/project/sap-browser-automation-source-review-2026-07-14.md`
Use the bundled helpers instead of generating one-off launch or WebSocket code. `edge-profile.ps1`
owns the isolated Edge lifecycle; `cdp-agent.mjs` owns target discovery and page control. Both scripts
are under `scripts/` relative to the skill root.
## Requirements
- Windows with Microsoft Edge Stable.
- Windows PowerShell 5.1 or newer.
- Node.js 22 or newer with global `fetch` and `WebSocket`; no npm package is required.
- A new/empty automation root for `CloneLaunch`, or an existing isolated root for `LaunchExisting`.
## Clone and launch
Run `scripts/edge-profile.ps1 -Action CloneLaunch` only after live volatile state has been exported and
normal Edge has been closed. Pass the exact selected profile name; this example deliberately uses
`Profile 2` rather than `Default`:
```powershell
$skillRoot = 'plugins/sap-browser-automation/skills/sap-browser-automation'
$normalEdge = Join-Path $env:LOCALAPPDATA 'Microsoft/Edge/User Data'
$automation = Join-Path $env:LOCALAPPDATA 'Codex/SAP-Automation-Edge-20260714'
powershell -NoProfile -ExecutionPolicy Bypass -File "$skillRoot/scripts/edge-profile.ps1" `
-Action CloneLaunch `
-SourceUserData $normalEdge `
-ProfileName 'Profile 2' `
-AutomationRoot $automation `
-TargetUrl $env:SAP_TARGET_URL
```
The helper refuses a non-empty destination, stages the copy before moving it into place, preserves the
selected profile directory, and launches Edge with `--remote-debugging-address=127.0.0.1` and
`--remote-debugging-port=0`. It then reads `DevToolsActivePort` and verifies that the loopback listener
belongs to a process using the requested automation root.
Reuse and lifecycle commands:
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File "$skillRoot/scripts/edge-profile.ps1" `
-Action LaunchExisting -ProfileName 'Profile 2' -AutomationRoot $automation `
-TargetUrl $env:SAP_TARGET_URL
powershell -NoProfile -ExecutionPolicy Bypass -File "$skillRoot/scripts/edge-profile.ps1" `
-Action Status -ProfileName 'Profile 2' -AutomationRoot $automation
powershell -NoProfile -ExecutionPolicy Bypass -File "$skillRoot/scripts/edge-profile.ps1" `
-Action Stop -AutomationRoot $automation
```
`Stop` matches the isolated user-data path and does not stop unrelated Edge processes.
## Deterministic target control
List page targets first:
```powershell
node "$skillRoot/scripts/cdp-agent.mjs" targets `
--user-data-dir $automation `
--host $env:SAP_TENANT_HOST
```
All action commands require filters that resolve exactly one page. Combine `--target-id`, `--host`,
`--path-contains`, and `--title-contains` as needed. Ambiguous or missing targets fail with the available
page summaries; the driver never picks the first tab.
Typical operations:
```powershell
node "$skillRoot/scripts/cdp-agent.mjs" inspect --user-data-dir $automation `
--host $env:SAP_TENANT_HOST --path-contains $env:SAP_TARGET_PATH
node "$skillRoot/scripts/cdp-agent.mjs" click --user-data-dir $automation `
--host $env:SAP_TENANT_HOST --path-contains $env:SAP_TARGET_PATH `
--selector '[data-testid="open-story"]'
node "$skillRoot/scripts/cdp-agent.mjs" type --user-data-dir $automation `
--host $env:SAP_TENANT_HOST --path-contains $env:SAP_TARGET_PATH `
--selector 'input[aria-label="Search"]' --text 'Revenue'
node "$skillRoot/scripts/cdp-agent.mjs" screenshot --user-data-dir $automation `
--host $env:SAP_TENANT_HOST --path-contains $env:SAP_TARGET_PATH `
--output (Join-Path $env:TEMP 'sap-evidence.png')
```
Run `node scripts/cdp-agent.mjs help` from the skill root for navigation, evaluation, coordinate click,
key, snapshot, export, and import syntax.
## Failure recovery
| Symptom | Recovery |
| --- | --- |
| Automation root is non-empty | Use `LaunchExisting` or choose a new clone destination. |
| Source profile is running | Export volatile state first, close normal Edge, then retry `CloneLaunch`. |
| Missing/stale `DevToolsActivePort` | `LaunchExisting` removes the stale file and waits for a new verified listener. |
| Target selection is ambiguous | Add host, path, title, or target-ID filters until exactly one page matches. |
| No authenticated SAP page | Import the pre-close auth state, reload, and inspect again. |
| Imported state still redirects to SSO | Complete one manual login in the isolated profile and reuse it later. |
| Edge policy blocks debugging | Use the approved desktop/manual path; do not report the SAP action complete. |
## Reporting
Report the browser version, automation-root path, selected profile, loopback status, selected target,
authentication result, visible errors, evidence paths, and cleanup result. Browser startup or a CDP
connection alone is not completion evidence.
references/in-app-browser-auth.md
# In-App Browser Authentication
Documentation Source: `docs/project/sap-browser-automation-source-review-2026-07-14.md`
Use the installed in-app Browser skill for the first visible authentication attempt. Follow its
bootstrap and documentation requirements before selecting a tab or interacting with the page.
## Validation status
This route executes inside Codex or Claude Desktop. Its runtime validation is deferred to those desktop
applications and is not part of the standalone Edge/CDP test suite. Keep it as the first supported
manual-login route without inferring availability from terminal-only tests.
## Manual login flow
1. Navigate to the approved SAC or Datasphere target.
2. Inspect visible state. If the target shows SSO or another sign-in page, tell the user that manual
sign-in is required and invoke the supported secure browser-auth capability.
3. Never ask the user to paste a password, OTP, passkey, recovery code, or token into chat.
4. After each authentication transition, inspect the visible page for the next step, CAPTCHA, error,
or success signal.
5. Verify the target domain shows a positive signed-in signal. A closed popup, blank page, spinner,
login redirect, or stale tab is an unknown result.
## Capability boundary
The in-app Browser is a separate session. Do not read, export, or import its cookies, local storage,
session storage, passwords, profiles, or session stores. Do not assume that an Edge login is available
inside it. If manual login succeeds, use that session for visible in-app work; seed fresh Edge from
the normal Edge profile separately when CDP automation is required.
If browser bootstrap fails, read the installed browser troubleshooting guidance before changing
surfaces. If the in-app Browser remains unusable, continue with the consent-gated fresh Edge path and
record the in-app failure. Never report the SAP task complete because authentication alone succeeded.
## Evidence
Capture only approved screenshots or equivalent visible evidence. Redact tenant IDs, story IDs,
session-like URL parameters, user names, unrelated tabs, and authentication screens. Keep the
authentication result separate from the business-task result.
scripts/cdp-agent.mjs
#!/usr/bin/env node
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const DEFAULT_TIMEOUT_MS = 15_000;
const REPEATABLE_OPTIONS = new Set(['origin', 'cookieDomain']);
// Options shared by every command (connection + target selection + help).
const COMMON_OPTIONS = new Set([
'help',
'userDataDir',
'port',
'endpoint',
'targetId',
'host',
'pathContains',
'titleContains',
]);
// Per-command additional options beyond the common set.
const COMMAND_OPTIONS = {
targets: new Set(),
inspect: new Set(),
snapshot: new Set(),
navigate: new Set(['url', 'timeout']),
evaluate: new Set(['expression', 'expressionFile']),
click: new Set(['selector']),
'click-point': new Set(['x', 'y']),
type: new Set(['selector', 'text']),
key: new Set(['key']),
screenshot: new Set(['output', 'fullPage']),
'export-auth': new Set(['origin', 'cookieDomain', 'stateFile']),
'import-auth': new Set(['stateFile', 'timeout']),
};
function optionName(name) {
return name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}
export function parseCliArguments(argv) {
const [command, ...tokens] = argv;
const options = {};
for (let index = 0; index < tokens.length; index += 1) {
const token = tokens[index];
if (!token.startsWith('--')) {
throw new Error(`Unexpected argument: ${token}`);
}
const equals = token.indexOf('=');
const rawName = token.slice(2, equals >= 0 ? equals : undefined);
const name = optionName(rawName);
let value;
if (equals >= 0) {
value = token.slice(equals + 1);
} else if (tokens[index + 1] && !tokens[index + 1].startsWith('--')) {
value = tokens[index + 1];
index += 1;
} else {
value = true;
}
if (REPEATABLE_OPTIONS.has(name)) {
options[name] = [...(options[name] ?? []), value];
} else {
options[name] = value;
}
}
const allowed = Object.hasOwn(COMMAND_OPTIONS, command) ? COMMAND_OPTIONS[command] : null;
if (allowed) {
const known = new Set([...COMMON_OPTIONS, ...allowed]);
const unknown = Object.keys(options).filter((key) => !known.has(key));
if (unknown.length > 0) {
throw new Error(`Unknown option(s) for "${command}": ${unknown.map((n) => `--${n.replace(/([A-Z])/g, '-$1').toLowerCase()}`).join(', ')}`);
}
}
return { command, options };
}
function targetPath(target) {
try {
const url = new URL(target.url);
return `${url.pathname}${url.search}${url.hash}`;
} catch {
return target.url ?? '';
}
}
function targetHost(target) {
try {
return new URL(target.url).hostname.toLowerCase();
} catch {
return '';
}
}
export function filterTargets(targets, filters = {}) {
return targets.filter((target) => {
if (target.type !== 'page') return false;
if (filters.targetId && target.id !== filters.targetId) return false;
if (filters.host && targetHost(target) !== String(filters.host).toLowerCase()) return false;
if (
filters.pathContains
&& !targetPath(target).toLowerCase().includes(String(filters.pathContains).toLowerCase())
) return false;
if (
filters.titleContains
&& !String(target.title ?? '').toLowerCase().includes(String(filters.titleContains).toLowerCase())
) return false;
return true;
});
}
function summarizeTarget(target) {
return {
id: target.id,
type: target.type,
title: target.title,
url: target.url,
};
}
export function selectTarget(targets, filters = {}) {
const matches = filterTargets(targets, filters);
if (matches.length === 0) {
throw new Error(`Target selection matched no page targets. Available: ${JSON.stringify(
targets.filter((target) => target.type === 'page').map(summarizeTarget),
)}`);
}
if (matches.length > 1) {
throw new Error(`Target selection matched ${matches.length} page targets. Add --target-id, --host, --path-contains, or --title-contains. Matches: ${JSON.stringify(
matches.map(summarizeTarget),
)}`);
}
return matches[0];
}
function normalizeAllowedHosts(origins) {
return origins.map((origin) => {
try {
return new URL(origin).hostname.toLowerCase();
} catch {
return String(origin).replace(/^\./, '').toLowerCase();
}
});
}
const PUBLIC_SUFFIXES = new Set([
'com', 'net', 'org', 'io', 'de', 'co.uk', 'co.jp', 'com.au', 'co.kr',
'cloud', 'local', 'gov', 'edu', 'mil', 'info', 'biz', 'me', 'app',
]);
export function filterCookiesForOrigins(cookies, origins) {
const hosts = normalizeAllowedHosts(origins);
return cookies.filter((cookie) => {
const domain = String(cookie.domain ?? '').replace(/^\./, '').toLowerCase();
if (!domain || PUBLIC_SUFFIXES.has(domain)) return false;
// Require at least 2 dot-separated labels so bare TLDs cannot match.
if (domain.split('.').length < 2) return false;
return hosts.some((host) => host === domain || host.endsWith(`.${domain}`));
});
}
export function toCookieParams(cookies) {
const allowed = [
'name',
'value',
'url',
'domain',
'path',
'secure',
'httpOnly',
'sameSite',
'priority',
'sameParty',
'sourceScheme',
'sourcePort',
'partitionKey',
];
return cookies.map((cookie) => {
const result = {};
for (const key of allowed) {
if (cookie[key] !== undefined) result[key] = cookie[key];
}
if (Number.isFinite(cookie.expires) && cookie.expires > 0) result.expires = cookie.expires;
return result;
});
}
class CdpConnection {
constructor(url, timeoutMs = DEFAULT_TIMEOUT_MS) {
this.url = url;
this.timeoutMs = timeoutMs;
this.nextId = 1;
this.pending = new Map();
}
async connect() {
if (typeof WebSocket !== 'function') {
throw new Error('Node.js 22 or newer is required because global WebSocket is unavailable.');
}
this.socket = new WebSocket(this.url);
this.socket.addEventListener('message', (event) => this.#onMessage(event));
this.socket.addEventListener('close', () => this.#rejectPending(new Error('CDP connection closed.')));
this.socket.addEventListener('error', () => this.#rejectPending(new Error('CDP WebSocket error.')));
await new Promise((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`Timed out connecting to CDP after ${this.timeoutMs} ms.`)),
this.timeoutMs,
);
this.socket.addEventListener('open', () => {
clearTimeout(timeout);
resolve();
}, { once: true });
this.socket.addEventListener('error', () => {
clearTimeout(timeout);
reject(new Error('Could not connect to the CDP WebSocket.'));
}, { once: true });
});
return this;
}
#onMessage(event) {
const message = JSON.parse(String(event.data));
if (!message.id || !this.pending.has(message.id)) return;
const pending = this.pending.get(message.id);
this.pending.delete(message.id);
clearTimeout(pending.timeout);
if (message.error) {
pending.reject(new Error(`${pending.method}: ${message.error.message}`));
} else {
pending.resolve(message.result ?? {});
}
}
#rejectPending(error) {
for (const pending of this.pending.values()) {
clearTimeout(pending.timeout);
pending.reject(error);
}
this.pending.clear();
}
send(method, params = {}) {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
throw new Error('CDP connection is not open.');
}
const id = this.nextId;
this.nextId += 1;
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`${method} timed out after ${this.timeoutMs} ms.`));
}, this.timeoutMs);
this.pending.set(id, { method, resolve, reject, timeout });
this.socket.send(JSON.stringify({ id, method, params }));
});
}
close() {
if (this.socket && this.socket.readyState < WebSocket.CLOSING) this.socket.close();
}
}
async function connectionInfo(options) {
let port = options.port ? Number(options.port) : undefined;
let browserWebSocketUrl = options.endpoint;
if (options.userDataDir) {
const activePortPath = path.join(path.resolve(options.userDataDir), 'DevToolsActivePort');
const lines = (await readFile(activePortPath, 'utf8')).trim().split(/\r?\n/);
port = Number(lines[0]);
if (!Number.isInteger(port) || port <= 0 || !lines[1]) {
throw new Error(`Invalid DevToolsActivePort file: ${activePortPath}`);
}
browserWebSocketUrl = `ws://127.0.0.1:${port}${lines[1]}`;
}
let endpointHost = '127.0.0.1';
if (!port && browserWebSocketUrl) {
const endpoint = new URL(browserWebSocketUrl);
port = Number(endpoint.port);
endpointHost = endpoint.hostname || endpointHost;
}
if (!port) {
throw new Error('Provide --user-data-dir, --port, or --endpoint.');
}
const baseUrl = `http://${endpointHost}:${port}`;
if (!browserWebSocketUrl) {
const response = await fetch(`${baseUrl}/json/version`);
if (!response.ok) throw new Error(`CDP version endpoint returned ${response.status}.`);
browserWebSocketUrl = (await response.json()).webSocketDebuggerUrl;
}
return { baseUrl, browserWebSocketUrl, port };
}
async function listTargets(info) {
const response = await fetch(`${info.baseUrl}/json/list`);
if (!response.ok) throw new Error(`CDP target endpoint returned ${response.status}.`);
return response.json();
}
function targetFilters(options) {
return {
targetId: options.targetId,
host: options.host,
pathContains: options.pathContains,
titleContains: options.titleContains,
};
}
async function openPage(info, options) {
const targets = await listTargets(info);
const target = selectTarget(targets, targetFilters(options));
if (!target.webSocketDebuggerUrl) {
throw new Error(`Target ${target.id} has no page WebSocket endpoint.`);
}
const connection = await new CdpConnection(target.webSocketDebuggerUrl).connect();
return { connection, target };
}
async function evaluate(connection, expression) {
const result = await connection.send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
userGesture: true,
});
if (result.exceptionDetails) {
throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text);
}
return result.result?.value;
}
async function waitForReady(connection, timeoutMs = DEFAULT_TIMEOUT_MS) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const state = await evaluate(connection, 'document.readyState');
if (state === 'interactive' || state === 'complete') return state;
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(`Page did not become ready within ${timeoutMs} ms.`);
}
async function clickSelector(connection, selector) {
const expression = `(() => {
const selector = ${JSON.stringify(selector)};
const find = (root) => {
const direct = root.querySelector(selector);
if (direct) return direct;
for (const element of root.querySelectorAll('*')) {
if (element.shadowRoot) {
const nested = find(element.shadowRoot);
if (nested) return nested;
}
}
return null;
};
const element = find(document);
if (!element) return { error: 'Selector did not match an element.' };
element.scrollIntoView({ block: 'center', inline: 'center' });
const rect = element.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2,
width: rect.width, height: rect.height, disabled: Boolean(element.disabled) };
})()`;
const location = await evaluate(connection, expression);
if (location?.error) throw new Error(`${location.error} Selector: ${selector}`);
if (location.disabled) throw new Error(`Element is disabled. Selector: ${selector}`);
if (!(location.width > 0 && location.height > 0)) {
throw new Error(`Element has no clickable area. Selector: ${selector}`);
}
await clickPoint(connection, location.x, location.y);
return location;
}
async function clickPoint(connection, x, y) {
const point = { x: Number(x), y: Number(y), button: 'left', clickCount: 1 };
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
throw new Error('click-point requires numeric --x and --y values.');
}
await connection.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...point });
await connection.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point });
await connection.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point });
}
function storageExpression() {
return `(() => {
const read = (storage) => {
const values = {};
for (let index = 0; index < storage.length; index += 1) {
const key = storage.key(index);
values[key] = storage.getItem(key);
}
return values;
};
return { origin: location.origin, localStorage: read(localStorage), sessionStorage: read(sessionStorage) };
})()`;
}
function storageBootstrapSource(origins) {
const serialized = JSON.stringify(Object.fromEntries(
origins.map((entry) => [entry.origin, entry]),
)).replaceAll('<', '\\u003c');
return `(() => {
const entries = ${serialized};
const current = entries[location.origin];
if (!current) return false;
for (const [key, value] of Object.entries(current.localStorage || {})) localStorage.setItem(key, value);
for (const [key, value] of Object.entries(current.sessionStorage || {})) sessionStorage.setItem(key, value);
return true;
})()`;
}
async function commandTargets(info, options) {
const targets = await listTargets(info);
return filterTargets(targets, targetFilters(options)).map(summarizeTarget);
}
async function commandInspect(info, options) {
const { connection, target } = await openPage(info, options);
try {
const page = await evaluate(connection, `(() => ({
title: document.title,
url: location.href,
readyState: document.readyState,
text: (document.body?.innerText || '').slice(0, 30000),
interactive: [...document.querySelectorAll('a,button,input,select,textarea,[role],[tabindex]')]
.filter((element) => {
const style = getComputedStyle(element);
const rect = element.getBoundingClientRect();
return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
})
.slice(0, 500)
.map((element) => ({
tag: element.tagName.toLowerCase(), id: element.id || undefined,
role: element.getAttribute('role') || undefined,
name: element.getAttribute('aria-label') || element.innerText?.trim() || element.value || undefined,
disabled: Boolean(element.disabled),
})),
}))()`);
const accessibility = await connection.send('Accessibility.getFullAXTree');
const ax = (accessibility.nodes ?? []).filter((node) => !node.ignored).slice(0, 500).map((node) => ({
role: node.role?.value,
name: node.name?.value,
value: node.value?.value,
}));
return { target: summarizeTarget(target), page, accessibility: ax };
} finally {
connection.close();
}
}
async function commandEvaluate(info, options) {
let expression = options.expression;
if (options.expressionFile) expression = await readFile(path.resolve(options.expressionFile), 'utf8');
if (!expression) throw new Error('evaluate requires --expression or --expression-file.');
const { connection } = await openPage(info, options);
try {
return { value: await evaluate(connection, expression) };
} finally {
connection.close();
}
}
async function commandNavigate(info, options) {
if (!options.url) throw new Error('navigate requires --url.');
const { connection, target } = await openPage(info, options);
try {
await connection.send('Page.enable');
const result = await connection.send('Page.navigate', { url: options.url });
if (result.errorText) throw new Error(`Navigation failed: ${result.errorText}`);
await waitForReady(connection, Number(options.timeout ?? DEFAULT_TIMEOUT_MS));
return { targetId: target.id, url: await evaluate(connection, 'location.href') };
} finally {
connection.close();
}
}
async function commandClick(info, options) {
if (!options.selector) throw new Error('click requires --selector.');
const { connection } = await openPage(info, options);
try {
return await clickSelector(connection, options.selector);
} finally {
connection.close();
}
}
async function commandClickPoint(info, options) {
const { connection } = await openPage(info, options);
try {
await clickPoint(connection, options.x, options.y);
return { x: Number(options.x), y: Number(options.y) };
} finally {
connection.close();
}
}
async function commandType(info, options) {
if (options.text === undefined || options.text === true) throw new Error('type requires --text.');
const { connection } = await openPage(info, options);
try {
if (options.selector) await clickSelector(connection, options.selector);
await connection.send('Input.insertText', { text: String(options.text) });
return { insertedCharacters: String(options.text).length };
} finally {
connection.close();
}
}
const SPECIAL_KEY_CODES = new Set([
'Enter', 'Tab', 'Escape', 'Space', 'Backspace', 'Delete', 'Insert', 'Home',
'End', 'PageUp', 'PageDown', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
]);
function keyToCode(key) {
if (SPECIAL_KEY_CODES.has(key)) return key;
// Single lowercase letter: a -> KeyA
if (/^[a-z]$/i.test(key)) return `Key${key.toUpperCase()}`;
// Single digit: 1 -> Digit1
if (/^[0-9]$/.test(key)) return `Digit${key}`;
// Function keys and other known multi-name codes pass through.
return key;
}
async function commandKey(info, options) {
if (!options.key || options.key === true) throw new Error('key requires --key.');
const { connection } = await openPage(info, options);
try {
const key = String(options.key);
const code = keyToCode(key);
await connection.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key, code });
await connection.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code });
return { key };
} finally {
connection.close();
}
}
async function commandScreenshot(info, options) {
if (!options.output) throw new Error('screenshot requires --output.');
const output = path.resolve(options.output);
const { connection } = await openPage(info, options);
try {
await connection.send('Page.enable');
const capture = await connection.send('Page.captureScreenshot', {
format: 'png',
fromSurface: true,
captureBeyondViewport: options.fullPage === true,
});
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, Buffer.from(capture.data, 'base64'));
return { output };
} finally {
connection.close();
}
}
async function commandExportAuth(info, options) {
if (!options.stateFile) throw new Error('export-auth requires --state-file.');
const origins = (options.origin ?? []).map((origin) => new URL(origin).origin);
if (origins.length === 0) throw new Error('export-auth requires at least one --origin.');
const allowedCookieScopes = [...origins, ...(options.cookieDomain ?? [])];
const browser = await new CdpConnection(info.browserWebSocketUrl).connect();
let connection;
let target;
try {
({ connection, target } = await openPage(info, options));
const cookieResult = await browser.send('Storage.getCookies');
const cookies = filterCookiesForOrigins(cookieResult.cookies ?? [], allowedCookieScopes);
const storage = await evaluate(connection, storageExpression());
if (!origins.includes(storage.origin)) {
throw new Error(`Selected target origin ${storage.origin} is not included in --origin.`);
}
const state = {
version: 1,
capturedAt: new Date().toISOString(),
target: summarizeTarget(target),
cookies,
origins: [storage],
};
const stateFile = path.resolve(options.stateFile);
await mkdir(path.dirname(stateFile), { recursive: true });
await writeFile(stateFile, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
return {
stateFile,
cookieCount: cookies.length,
originCount: state.origins.length,
localStorageEntries: Object.keys(storage.localStorage).length,
sessionStorageEntries: Object.keys(storage.sessionStorage).length,
};
} finally {
connection?.close();
browser.close();
}
}
async function commandImportAuth(info, options) {
if (!options.stateFile) throw new Error('import-auth requires --state-file.');
const stateFile = path.resolve(options.stateFile);
const state = JSON.parse(await readFile(stateFile, 'utf8'));
if (state.version !== 1 || !Array.isArray(state.cookies) || !Array.isArray(state.origins)) {
throw new Error(`Unsupported auth-state file: ${stateFile}`);
}
const browser = await new CdpConnection(info.browserWebSocketUrl).connect();
let connection;
try {
({ connection } = await openPage(info, options));
const cookies = toCookieParams(state.cookies);
if (cookies.length > 0) await browser.send('Storage.setCookies', { cookies });
const bootstrap = storageBootstrapSource(state.origins);
await connection.send('Page.enable');
await connection.send('Page.addScriptToEvaluateOnNewDocument', { source: bootstrap });
await evaluate(connection, bootstrap);
await connection.send('Page.reload', { ignoreCache: true });
await waitForReady(connection, Number(options.timeout ?? DEFAULT_TIMEOUT_MS));
return {
stateFile,
cookieCount: cookies.length,
originCount: state.origins.length,
url: await evaluate(connection, 'location.href'),
};
} finally {
connection?.close();
browser.close();
}
}
function help() {
return `Usage: node scripts/cdp-agent.mjs <command> [options]
Connection: --user-data-dir <path> | --port <number> | --endpoint <browser-ws-url>
Target: --target-id <id> --host <host> --path-contains <text> --title-contains <text>
Commands:
targets
inspect | snapshot
navigate --url <url>
evaluate (--expression <js> | --expression-file <path>)
click --selector <css>
click-point --x <number> --y <number>
type [--selector <css>] --text <text>
key --key <key>
screenshot --output <png> [--full-page]
export-auth --origin <origin> [--origin <origin>] --state-file <json>
import-auth --state-file <json>`;
}
export async function runCli(argv = process.argv.slice(2)) {
const { command, options } = parseCliArguments(argv);
if (!command || command === 'help' || options.help) return help();
const major = Number(process.versions.node.split('.')[0]);
if (major < 22 || typeof fetch !== 'function' || typeof WebSocket !== 'function') {
throw new Error('cdp-agent.mjs requires Node.js 22 or newer with global fetch and WebSocket.');
}
const info = await connectionInfo(options);
switch (command) {
case 'targets': return commandTargets(info, options);
case 'inspect':
case 'snapshot': return commandInspect(info, options);
case 'navigate': return commandNavigate(info, options);
case 'evaluate': return commandEvaluate(info, options);
case 'click': return commandClick(info, options);
case 'click-point': return commandClickPoint(info, options);
case 'type': return commandType(info, options);
case 'key': return commandKey(info, options);
case 'screenshot': return commandScreenshot(info, options);
case 'export-auth': return commandExportAuth(info, options);
case 'import-auth': return commandImportAuth(info, options);
default: throw new Error(`Unknown command: ${command}\n${help()}`);
}
}
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isMain) {
runCli()
.then((result) => {
if (typeof result === 'string') process.stdout.write(`${result}\n`);
else process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
})
.catch((error) => {
process.stderr.write(`${error.message}\n`);
process.exitCode = 1;
});
}
scripts/edge-profile.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('CloneLaunch', 'LaunchExisting', 'Status', 'Stop')]
[string]$Action,
[string]$SourceUserData = (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\User Data'),
[ValidatePattern('^(Default|Profile [0-9]+)$')]
[string]$ProfileName = 'Default',
[string]$AutomationRoot = (Join-Path $env:LOCALAPPDATA 'Codex\SAP-Automation-Edge'),
[string]$TargetUrl,
[string]$EdgeExecutable,
[ValidateRange(2, 120)]
[int]$StartupTimeoutSeconds = 20,
[switch]$Headless
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 2.0
function Get-FullPath {
param([Parameter(Mandatory = $true)][string]$Path)
return [System.IO.Path]::GetFullPath([Environment]::ExpandEnvironmentVariables($Path))
}
function Get-EdgeExecutable {
param([string]$RequestedPath)
if ($RequestedPath) {
$explicitPath = Get-FullPath $RequestedPath
if (-not (Test-Path -LiteralPath $explicitPath -PathType Leaf)) {
throw "Requested Microsoft Edge executable was not found: $explicitPath"
}
return $explicitPath
}
$candidates = @()
if (${env:ProgramFiles(x86)}) {
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe')
}
if ($env:ProgramFiles) {
$candidates += (Join-Path $env:ProgramFiles 'Microsoft\Edge\Application\msedge.exe')
}
if ($env:LOCALAPPDATA) {
$candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\Application\msedge.exe')
}
foreach ($candidate in $candidates) {
if (Test-Path -LiteralPath $candidate -PathType Leaf) { return (Get-FullPath $candidate) }
}
throw "Microsoft Edge was not found. Checked: $($candidates -join ', ')"
}
function Get-EdgeProcessesForRoot {
param([Parameter(Mandatory = $true)][string]$Root)
$fullRoot = Get-FullPath $Root
$escapedRoot = [Regex]::Escape($fullRoot)
# Anchor on the closing quote (or whitespace/end) immediately after the path
# so a profile root that is a prefix of another cannot match the wrong process.
$pattern = "$escapedRoot[`"'](?:\s|$)"
return @(Get-CimInstance Win32_Process -Filter "Name = 'msedge.exe'" -ErrorAction SilentlyContinue |
Where-Object { $_.CommandLine -and $_.CommandLine -match $pattern })
}
function Assert-SourceProfileClosed {
param([Parameter(Mandatory = $true)][string]$Root)
$fullRoot = Get-FullPath $Root
$normalRoot = Get-FullPath (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\User Data')
if ([string]::Equals($fullRoot, $normalRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
if (Get-Process msedge -ErrorAction SilentlyContinue) {
throw 'Close all Microsoft Edge windows before cloning the normal Edge profile.'
}
return
}
$sourceProcesses = @(Get-EdgeProcessesForRoot $fullRoot)
if ($sourceProcesses.Count -gt 0) {
throw "Close the Edge instance using source profile: $fullRoot"
}
}
function Assert-AutomationProfileStopped {
param([Parameter(Mandatory = $true)][string]$Root)
$automationProcesses = @(Get-EdgeProcessesForRoot $Root)
if ($automationProcesses.Count -gt 0) {
throw "An Edge process is already using the automation profile: $Root"
}
}
function Copy-ProfileToEmptyDestination {
param(
[Parameter(Mandatory = $true)][string]$SourceRoot,
[Parameter(Mandatory = $true)][string]$SourceProfileName,
[Parameter(Mandatory = $true)][string]$DestinationRoot
)
$source = Get-FullPath $SourceRoot
$destination = Get-FullPath $DestinationRoot
if ([string]::Equals($source, $destination, [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'Source and destination user-data directories must be different.'
}
$localState = Join-Path $source 'Local State'
$sourceProfile = Join-Path $source $SourceProfileName
if (-not (Test-Path -LiteralPath $localState -PathType Leaf)) {
throw "Missing Edge Local State: $localState"
}
if (-not (Test-Path -LiteralPath $sourceProfile -PathType Container)) {
throw "Missing Edge profile: $sourceProfile"
}
Assert-SourceProfileClosed $source
Assert-AutomationProfileStopped $destination
if (Test-Path -LiteralPath $destination) {
$existing = @(Get-ChildItem -LiteralPath $destination -Force -ErrorAction Stop | Select-Object -First 1)
if ($existing.Count -gt 0) {
throw "AutomationRoot is non-empty. Use -Action LaunchExisting or choose a new destination: $destination"
}
}
$staging = "$destination.clone-$([Guid]::NewGuid().ToString('N'))"
try {
New-Item -ItemType Directory -Path $staging -Force | Out-Null
Copy-Item -LiteralPath $localState -Destination (Join-Path $staging 'Local State') -Force
Copy-Item -LiteralPath $sourceProfile -Destination (Join-Path $staging $SourceProfileName) -Recurse -Force
if (Test-Path -LiteralPath $destination) {
Remove-Item -LiteralPath $destination -Force
} else {
$parent = Split-Path -Parent $destination
if ($parent) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
}
Move-Item -LiteralPath $staging -Destination $destination
} finally {
if (Test-Path -LiteralPath $staging) {
Remove-Item -LiteralPath $staging -Recurse -Force
}
}
}
function Get-ProfileStatus {
param([Parameter(Mandatory = $true)][string]$Root)
$fullRoot = Get-FullPath $Root
$activePortFile = Join-Path $fullRoot 'DevToolsActivePort'
if (-not (Test-Path -LiteralPath $activePortFile -PathType Leaf)) {
return [pscustomobject]@{
running = $false
loopback = $false
port = $null
processId = $null
profileRoot = $fullRoot
}
}
$lines = @(Get-Content -LiteralPath $activePortFile -ErrorAction Stop)
$port = 0
if ($lines.Count -lt 2 -or -not [int]::TryParse($lines[0], [ref]$port) -or $port -le 0) {
return [pscustomobject]@{
running = $false
loopback = $false
port = $null
processId = $null
profileRoot = $fullRoot
}
}
$listener = @(Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue |
Where-Object { $_.LocalAddress -eq '127.0.0.1' -or $_.LocalAddress -eq '::1' } |
Select-Object -First 1)
if ($listener.Count -eq 0) {
return [pscustomobject]@{
running = $false
loopback = $false
port = $port
processId = $null
profileRoot = $fullRoot
}
}
$owner = Get-CimInstance Win32_Process -Filter "ProcessId = $($listener[0].OwningProcess)" -ErrorAction SilentlyContinue
$statusEscapedRoot = [Regex]::Escape($fullRoot)
$statusPattern = "$statusEscapedRoot[`"'](?:\s|$)"
$belongsToProfile = $owner -and $owner.CommandLine -and $owner.CommandLine -match $statusPattern
return [pscustomobject]@{
running = [bool]$belongsToProfile
loopback = [bool]$belongsToProfile
port = $port
processId = if ($belongsToProfile) { [int]$listener[0].OwningProcess } else { $null }
profileRoot = $fullRoot
}
}
function Start-AutomationEdge {
param(
[Parameter(Mandatory = $true)][string]$Root,
[Parameter(Mandatory = $true)][string]$SelectedProfile,
[string]$Url,
[string]$RequestedEdge,
[int]$TimeoutSeconds,
[switch]$UseHeadless
)
$fullRoot = Get-FullPath $Root
$profilePath = Join-Path $fullRoot $SelectedProfile
if (-not (Test-Path -LiteralPath $profilePath -PathType Container)) {
throw "Missing automation Edge profile: $profilePath"
}
Assert-AutomationProfileStopped $fullRoot
$activePortFile = Join-Path $fullRoot 'DevToolsActivePort'
if (Test-Path -LiteralPath $activePortFile) {
Remove-Item -LiteralPath $activePortFile -Force
}
$edge = Get-EdgeExecutable $RequestedEdge
$arguments = @(
'--remote-debugging-address=127.0.0.1',
'--remote-debugging-port=0',
"--user-data-dir=`"$fullRoot`"",
"--profile-directory=`"$SelectedProfile`"",
'--no-first-run',
'--no-default-browser-check'
)
if ($UseHeadless) {
$arguments += '--headless=new'
$arguments += '--disable-gpu'
}
if ($Url) { $arguments += "`"$Url`"" }
$argumentLine = $arguments -join ' '
if ($UseHeadless) {
Start-Process -FilePath $edge -ArgumentList $argumentLine -WindowStyle Hidden | Out-Null
} else {
Start-Process -FilePath $edge -ArgumentList $argumentLine | Out-Null
}
$deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)
do {
Start-Sleep -Milliseconds 250
$status = Get-ProfileStatus $fullRoot
if ($status.running) {
return [pscustomobject]@{
action = $Action
running = $true
loopback = $status.loopback
port = $status.port
processId = $status.processId
profileRoot = $fullRoot
profileName = $SelectedProfile
targetUrl = $Url
}
}
} while ([DateTime]::UtcNow -lt $deadline)
throw "Edge did not expose a verified loopback DevToolsActivePort within $TimeoutSeconds seconds: $fullRoot"
}
function Stop-AutomationEdge {
param([Parameter(Mandatory = $true)][string]$Root)
$fullRoot = Get-FullPath $Root
$processes = @(Get-EdgeProcessesForRoot $fullRoot)
foreach ($process in $processes) {
Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue
}
$deadline = [DateTime]::UtcNow.AddSeconds(10)
while ([DateTime]::UtcNow -lt $deadline) {
$remaining = @(Get-EdgeProcessesForRoot $fullRoot)
if ($remaining.Count -eq 0) { break }
Start-Sleep -Milliseconds 200
}
$activePortFile = Join-Path $fullRoot 'DevToolsActivePort'
if (Test-Path -LiteralPath $activePortFile) {
Remove-Item -LiteralPath $activePortFile -Force -ErrorAction SilentlyContinue
}
return [pscustomobject]@{
action = 'Stop'
running = $false
loopback = $false
port = $null
processId = $null
profileRoot = $fullRoot
profileName = $ProfileName
targetUrl = $null
}
}
$AutomationRoot = Get-FullPath $AutomationRoot
switch ($Action) {
'CloneLaunch' {
Copy-ProfileToEmptyDestination -SourceRoot $SourceUserData -SourceProfileName $ProfileName -DestinationRoot $AutomationRoot
$result = Start-AutomationEdge -Root $AutomationRoot -SelectedProfile $ProfileName -Url $TargetUrl -RequestedEdge $EdgeExecutable -TimeoutSeconds $StartupTimeoutSeconds -UseHeadless:$Headless
}
'LaunchExisting' {
$result = Start-AutomationEdge -Root $AutomationRoot -SelectedProfile $ProfileName -Url $TargetUrl -RequestedEdge $EdgeExecutable -TimeoutSeconds $StartupTimeoutSeconds -UseHeadless:$Headless
}
'Status' {
$status = Get-ProfileStatus $AutomationRoot
$result = [pscustomobject]@{
action = 'Status'
running = $status.running
loopback = $status.loopback
port = $status.port
processId = $status.processId
profileRoot = $status.profileRoot
profileName = $ProfileName
targetUrl = $null
}
}
'Stop' {
$result = Stop-AutomationEdge $AutomationRoot
}
}
$result | ConvertTo-Json -Depth 5 -Compress
scripts/tests/cdp-agent.test.mjs
import assert from 'node:assert/strict';
import test from 'node:test';
import {
filterCookiesForOrigins,
parseCliArguments,
selectTarget,
toCookieParams,
} from '../cdp-agent.mjs';
const targets = [
{
id: 'sac-story',
type: 'page',
title: 'Quarterly Story - SAP Analytics Cloud',
url: 'https://tenant.example.com/sap/fpa/ui/app.html#/story/42',
},
{
id: 'sac-home',
type: 'page',
title: 'Home - SAP Analytics Cloud',
url: 'https://tenant.example.com/sap/fpa/ui/app.html#/home',
},
{
id: 'extension',
type: 'background_page',
title: 'Extension',
url: 'chrome-extension://example/background.html',
},
];
test('selectTarget requires host, path, and title filters to resolve one page', () => {
const selected = selectTarget(targets, {
host: 'tenant.example.com',
pathContains: '#/story/42',
titleContains: 'quarterly story',
});
assert.equal(selected.id, 'sac-story');
});
test('selectTarget rejects ambiguous matches', () => {
assert.throws(
() => selectTarget(targets, { host: 'tenant.example.com' }),
/matched 2 page targets/i,
);
});
test('selectTarget reports a missing approved target', () => {
assert.throws(
() => selectTarget(targets, { host: 'other.example.com' }),
/matched no page targets/i,
);
});
test('filterCookiesForOrigins keeps tenant and identity-provider cookies only', () => {
const cookies = [
{ name: 'tenant', domain: '.tenant.example.com' },
{ name: 'idp', domain: 'login.example.net' },
{ name: 'unrelated', domain: '.unrelated.example.org' },
];
const filtered = filterCookiesForOrigins(cookies, [
'https://tenant.example.com',
'https://login.example.net',
]);
assert.deepEqual(filtered.map((cookie) => cookie.name), ['tenant', 'idp']);
});
test('toCookieParams strips read-only CDP cookie fields', () => {
const [cookie] = toCookieParams([
{
name: 'session',
value: 'value',
domain: '.tenant.example.com',
path: '/',
expires: -1,
httpOnly: true,
secure: true,
sameSite: 'None',
priority: 'Medium',
sourceScheme: 'Secure',
sourcePort: 443,
size: 12,
session: true,
},
]);
assert.equal(cookie.name, 'session');
assert.equal(cookie.expires, undefined);
assert.equal('size' in cookie, false);
assert.equal('session' in cookie, false);
});
test('parseCliArguments preserves repeated origin options', () => {
const parsed = parseCliArguments([
'export-auth',
'--origin',
'https://tenant.example.com',
'--origin=https://login.example.net',
'--state-file',
'state.json',
]);
assert.equal(parsed.command, 'export-auth');
assert.deepEqual(parsed.options.origin, [
'https://tenant.example.com',
'https://login.example.net',
]);
});
scripts/tests/edge-cdp.integration.test.mjs
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
const scriptsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const cdpScript = path.join(scriptsRoot, 'cdp-agent.mjs');
const profileScript = path.join(scriptsRoot, 'edge-profile.ps1');
const powershell = path.join(
process.env.SystemRoot ?? 'C:\\Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
async function run(command, args, { expectFailure = false } = {}) {
try {
const result = await execFileAsync(command, args, {
maxBuffer: 10 * 1024 * 1024,
windowsHide: true,
});
if (expectFailure) assert.fail(`expected ${path.basename(command)} to fail`);
return result;
} catch (error) {
if (!expectFailure) throw error;
return error;
}
}
function profileArgs(args) {
return ['-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', profileScript, ...args];
}
async function prepareProfile(root) {
await mkdir(path.join(root, 'Default'), { recursive: true });
await writeFile(path.join(root, 'Local State'), '{}', 'utf8');
}
test('standalone Edge/CDP supports interaction, evidence, and volatile auth transfer', async (t) => {
if (process.platform !== 'win32') return t.skip('Windows Edge integration');
const root = await mkdtemp(path.join(tmpdir(), 'Codex Edge CDP Integration '));
const sourceProfile = path.join(root, 'source profile');
const destinationProfile = path.join(root, 'destination profile');
const screenshot = path.join(root, 'evidence.png');
const stateFile = path.join(root, 'auth-state.json');
await prepareProfile(sourceProfile);
await prepareProfile(destinationProfile);
const server = createServer((request, response) => {
response.setHeader('content-type', 'text/html; charset=utf-8');
if (request.url?.startsWith('/fixture')) {
response.end(`<!doctype html>
<html><body>
<button id="go" onclick="document.querySelector('#status').textContent='clicked'">Go</button>
<input id="name" aria-label="Name">
<div id="status">idle</div>
<script>
localStorage.setItem('local-auth', 'local-value');
sessionStorage.setItem('session-auth', 'session-value');
document.cookie = 'persistent_fixture=present; Max-Age=3600; Path=/';
document.cookie = 'session_fixture=present; Path=/';
</script>
</body></html>`);
return;
}
response.end('<!doctype html><html><body><div id="blank">blank</div></body></html>');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
const origin = `http://127.0.0.1:${address.port}`;
t.after(async () => {
server.close();
for (const profile of [sourceProfile, destinationProfile]) {
await run(powershell, profileArgs(['-Action', 'Stop', '-AutomationRoot', profile])).catch(() => {});
}
await rm(root, { recursive: true, force: true });
});
await run(powershell, profileArgs([
'-Action', 'LaunchExisting',
'-AutomationRoot', sourceProfile,
'-ProfileName', 'Default',
'-TargetUrl', `${origin}/fixture`,
'-Headless',
]));
const targetArgs = [
'--user-data-dir', sourceProfile,
'--host', '127.0.0.1',
'--path-contains', '/fixture',
];
const targetsResult = await run(process.execPath, [cdpScript, 'targets', ...targetArgs]);
const targets = JSON.parse(targetsResult.stdout);
assert.equal(targets.length, 1);
await run(process.execPath, [cdpScript, 'click', ...targetArgs, '--selector', '#go']);
await run(process.execPath, [cdpScript, 'type', ...targetArgs, '--selector', '#name', '--text', 'Alice']);
const evaluated = await run(process.execPath, [
cdpScript,
'evaluate',
...targetArgs,
'--expression',
"({status:document.querySelector('#status').textContent,name:document.querySelector('#name').value})",
]);
assert.deepEqual(JSON.parse(evaluated.stdout).value, { status: 'clicked', name: 'Alice' });
await run(process.execPath, [cdpScript, 'screenshot', ...targetArgs, '--output', screenshot]);
assert.ok((await stat(screenshot)).size > 100);
assert.deepEqual([...await readFile(screenshot)].slice(0, 8), [137, 80, 78, 71, 13, 10, 26, 10]);
await run(process.execPath, [
cdpScript,
'export-auth',
...targetArgs,
'--origin', origin,
'--state-file', stateFile,
]);
const exported = JSON.parse(await readFile(stateFile, 'utf8'));
assert.equal(exported.version, 1);
assert.deepEqual(exported.origins[0].localStorage, { 'local-auth': 'local-value' });
assert.deepEqual(exported.origins[0].sessionStorage, { 'session-auth': 'session-value' });
assert.ok(exported.cookies.some((cookie) => cookie.name === 'session_fixture'));
await run(powershell, profileArgs(['-Action', 'Stop', '-AutomationRoot', sourceProfile]));
await run(powershell, profileArgs([
'-Action', 'LaunchExisting',
'-AutomationRoot', destinationProfile,
'-ProfileName', 'Default',
'-TargetUrl', `${origin}/blank`,
'-Headless',
]));
const destinationArgs = [
'--user-data-dir', destinationProfile,
'--host', '127.0.0.1',
'--path-contains', '/blank',
];
await run(process.execPath, [
cdpScript,
'import-auth',
...destinationArgs,
'--state-file', stateFile,
]);
const restored = await run(process.execPath, [
cdpScript,
'evaluate',
...destinationArgs,
'--expression',
"({local:localStorage.getItem('local-auth'),session:sessionStorage.getItem('session-auth'),cookies:document.cookie})",
]);
const restoredValue = JSON.parse(restored.stdout).value;
assert.equal(restoredValue.local, 'local-value');
assert.equal(restoredValue.session, 'session-value');
assert.match(restoredValue.cookies, /persistent_fixture=present/);
assert.match(restoredValue.cookies, /session_fixture=present/);
const wrongTarget = await run(process.execPath, [
cdpScript,
'evaluate',
'--user-data-dir', destinationProfile,
'--host', 'wrong.example.com',
'--expression', 'document.title',
], { expectFailure: true });
assert.match(`${wrongTarget.stderr ?? ''}${wrongTarget.stdout ?? ''}`, /matched no page targets/i);
});
scripts/tests/edge-profile.test.mjs
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
const powershell = path.join(
process.env.SystemRoot ?? 'C:\\Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
const script = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'..',
'edge-profile.ps1',
);
async function runProfile(args, { expectFailure = false } = {}) {
try {
const result = await execFileAsync(
powershell,
['-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, ...args],
{ windowsHide: true },
);
if (expectFailure) assert.fail('expected edge-profile.ps1 to fail');
return result;
} catch (error) {
if (!expectFailure) throw error;
return error;
}
}
async function prepareProfile(root, profileName) {
await mkdir(path.join(root, profileName), { recursive: true });
await writeFile(path.join(root, 'Local State'), '{}', 'utf8');
}
test('CloneLaunch preserves Profile 2 and refuses a non-empty destination', async (t) => {
if (process.platform !== 'win32') return t.skip('Windows Edge helper');
const root = await mkdtemp(path.join(tmpdir(), 'Codex Edge Profile Test '));
const source = path.join(root, 'source');
const destination = path.join(root, 'automation profile');
await prepareProfile(source, 'Profile 2');
await writeFile(path.join(source, 'Profile 2', 'marker.txt'), 'profile-two', 'utf8');
t.after(async () => {
await runProfile(['-Action', 'Stop', '-AutomationRoot', destination], { expectFailure: false }).catch(() => {});
await rm(root, { recursive: true, force: true });
});
const launched = await runProfile([
'-Action', 'CloneLaunch',
'-SourceUserData', source,
'-ProfileName', 'Profile 2',
'-AutomationRoot', destination,
'-TargetUrl', 'about:blank',
'-Headless',
]);
const status = JSON.parse(launched.stdout);
assert.equal(status.profileName, 'Profile 2');
assert.equal(status.loopback, true);
assert.ok(status.port > 0);
assert.equal(await readFile(path.join(destination, 'Profile 2', 'marker.txt'), 'utf8'), 'profile-two');
await assert.rejects(access(path.join(destination, 'Profile 2', 'Profile 2')));
await runProfile(['-Action', 'Stop', '-AutomationRoot', destination]);
const repeated = await runProfile([
'-Action', 'CloneLaunch',
'-SourceUserData', source,
'-ProfileName', 'Profile 2',
'-AutomationRoot', destination,
'-TargetUrl', 'about:blank',
'-Headless',
], { expectFailure: true });
assert.match(`${repeated.stderr ?? ''}${repeated.stdout ?? ''}`, /non-empty|LaunchExisting/i);
});
test('LaunchExisting replaces a stale DevToolsActivePort and can be stopped', async (t) => {
if (process.platform !== 'win32') return t.skip('Windows Edge helper');
const root = await mkdtemp(path.join(tmpdir(), 'Codex Edge Existing Test '));
const profile = path.join(root, 'automation profile');
await prepareProfile(profile, 'Default');
await writeFile(path.join(profile, 'DevToolsActivePort'), '9\n/devtools/browser/stale', 'utf8');
t.after(async () => {
await runProfile(['-Action', 'Stop', '-AutomationRoot', profile], { expectFailure: false }).catch(() => {});
await rm(root, { recursive: true, force: true });
});
const launched = await runProfile([
'-Action', 'LaunchExisting',
'-ProfileName', 'Default',
'-AutomationRoot', profile,
'-TargetUrl', 'about:blank',
'-Headless',
]);
const status = JSON.parse(launched.stdout);
assert.notEqual(status.port, 9);
assert.equal(status.running, true);
const stopped = await runProfile(['-Action', 'Stop', '-AutomationRoot', profile]);
assert.equal(JSON.parse(stopped.stdout).running, false);
});
test('CloneLaunch rejects a running source profile', async (t) => {
if (process.platform !== 'win32') return t.skip('Windows Edge helper');
const root = await mkdtemp(path.join(tmpdir(), 'Codex Edge Running Source Test '));
const source = path.join(root, 'source profile');
const destination = path.join(root, 'destination profile');
await prepareProfile(source, 'Default');
t.after(async () => {
for (const profile of [source, destination]) {
await runProfile(['-Action', 'Stop', '-AutomationRoot', profile]).catch(() => {});
}
await rm(root, { recursive: true, force: true });
});
await runProfile([
'-Action', 'LaunchExisting',
'-ProfileName', 'Default',
'-AutomationRoot', source,
'-TargetUrl', 'about:blank',
'-Headless',
]);
const cloning = await runProfile([
'-Action', 'CloneLaunch',
'-SourceUserData', source,
'-ProfileName', 'Default',
'-AutomationRoot', destination,
'-TargetUrl', 'about:blank',
'-Headless',
], { expectFailure: true });
assert.match(`${cloning.stderr ?? ''}${cloning.stdout ?? ''}`, /close.*source profile|using source profile/i);
});
test('an explicit missing Edge executable fails instead of silently using another installation', async (t) => {
if (process.platform !== 'win32') return t.skip('Windows Edge helper');
const root = await mkdtemp(path.join(tmpdir(), 'Codex Edge Missing Executable Test '));
const profile = path.join(root, 'automation profile');
await prepareProfile(profile, 'Default');
t.after(async () => {
await runProfile(['-Action', 'Stop', '-AutomationRoot', profile]).catch(() => {});
await rm(root, { recursive: true, force: true });
});
const missing = await runProfile([
'-Action', 'LaunchExisting',
'-ProfileName', 'Default',
'-AutomationRoot', profile,
'-EdgeExecutable', path.join(root, 'missing-msedge.exe'),
'-TargetUrl', 'about:blank',
'-Headless',
], { expectFailure: true });
assert.match(`${missing.stderr ?? ''}${missing.stdout ?? ''}`, /requested Microsoft Edge executable was not found/i);
});
scripts/tests/skill-contract.test.mjs
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
const skillRoot = new URL('../../', import.meta.url);
async function read(relativePath) {
return readFile(new URL(relativePath, skillRoot), 'utf8');
}
test('main skill routes standalone automation through bundled helpers', async () => {
const skill = await read('SKILL.md');
assert.match(skill, /scripts\/edge-profile\.ps1/);
assert.match(skill, /scripts\/cdp-agent\.mjs/);
assert.match(skill, /Node(?:\.js)? 22/i);
});
test('auth workflow captures volatile state before closing and cloning Edge', async () => {
const skill = await read('SKILL.md');
const capture = skill.indexOf('export-auth');
const close = skill.indexOf('Close normal Edge', capture);
const clone = skill.indexOf('CloneLaunch', close);
assert.ok(capture >= 0, 'missing export-auth step');
assert.ok(close > capture, 'normal Edge must close after auth export');
assert.ok(clone > close, 'profile cloning must follow normal Edge shutdown');
});
test('auth reference uses current CDP cookie methods and executable commands', async () => {
const auth = await read('references/auth-state-bootstrap.md');
assert.match(auth, /Storage\.getCookies/);
assert.match(auth, /Storage\.setCookies/);
assert.doesNotMatch(auth, /Network\.getAllCookies/);
assert.match(auth, /cdp-agent\.mjs export-auth/);
assert.match(auth, /cdp-agent\.mjs import-auth/);
});
test('Edge reference preserves a selected profile and uses dynamic ports', async () => {
const edge = await read('references/edge-cdp-control.md');
assert.match(edge, /edge-profile\.ps1 -Action CloneLaunch/);
assert.match(edge, /-ProfileName ['"]Profile 2['"]/);
assert.match(edge, /remote-debugging-port=0/);
assert.doesNotMatch(edge, /--profile-directory=Default/);
});
test('in-app validation is explicitly deferred to desktop runtime', async () => {
const inApp = await read('references/in-app-browser-auth.md');
assert.match(inApp, /Codex or Claude Desktop/i);
assert.match(inApp, /runtime validation is deferred/i);
});
test('explicit browser requests stay on the requested surface and require a live MCP check', async () => {
const skill = await read('SKILL.md');
assert.match(skill, /use only that\s+browser and connection method/i);
assert.match(skill, /active tool registry/i);
assert.match(skill, /live .*handshake/i);
assert.match(skill, /restart Codex|open a new task/i);
assert.match(skill, /Do not silently switch to the In-app Browser/i);
});
test('SAC test automation preserves the same browser routing contract', async () => {
const skill = await readFile(
new URL('../../../../../../plugins/sap-sac-test-automation/skills/sap-sac-test-automation/SKILL.md', import.meta.url),
'utf8',
);
const chromeReference = await readFile(
new URL('../../../../../../plugins/sap-sac-test-automation/skills/sap-sac-test-automation/references/chrome-devtools-mcp.md', import.meta.url),
'utf8',
);
assert.match(skill, /explicitly named.*do not switch to another browser surface/i);
assert.match(skill, /active registry/i);
assert.match(skill, /live `list_pages`.*handshake/i);
assert.match(chromeReference, /DevToolsActivePort.*browser window alone is\s+not proof/i);
assert.match(chromeReference, /NPM_CONFIG_CACHE/);
assert.match(chromeReference, /RemoteDebuggingAllowed/);
});
SKILL.md
---
name: sap-browser-automation
description: Use when an agent must inspect or operate an authenticated SAP web UI through an in-app Browser, Microsoft Edge CDP, or an existing Playwright client, especially when SAP SSO reuse, isolated Edge profiles, deterministic target selection, screenshots, or browser bootstrap recovery is required.
license: GPL-3.0
metadata:
maintainer: "Eduard Jiglau"
maintainer_email: "hello@sap-ai-skills.com"
website: "https://sap-ai-skills.com"
version: "2.4.1"
last_verified: 2026-07-14
documentation_source: "docs/project/sap-browser-automation-source-review-2026-07-14.md"
status: docs_audited_runtime_pending
known_issues:
- In-app Browser authentication is desktop-runtime-dependent and its validation is deferred to Codex or Claude Desktop.
- SAC and Datasphere SSO, cross-domain cookies, client certificates, MFA, and enterprise Edge policy require tenant-specific verification.
---
# SAP Browser Automation
Use this skill as the shared browser layer for SAP-specific skills. It owns surface selection,
authentication bootstrap, isolated Edge/CDP startup, state reuse, target verification, evidence,
recovery, and cleanup. The consuming skill still owns the SAP action boundaries: story edits,
planning writeback, model changes, Datasphere deployment, SQL execution, and test acceptance.
## Related Skills
- **sap-sac-scripting**: SAC story/runtime scripting and reporting-story implementation.
- **sap-sac-test-automation**: SAC acceptance, discovery packets, Playwright suites, and evidence.
- **sap-sac-planning**: SAC planning models, writeback, versions, data actions, and locks.
- **sap-datasphere**: Datasphere modeling, deployment, spaces, connections, and administration.
- **browser:control-in-app-browser**: Installed in-app Browser runtime and secure manual authentication.
## When to Use This Skill
Use this skill whenever an agent must interact with an authenticated SAP web UI, select or inspect a
browser target, start Edge with loopback CDP, reuse an approved Edge profile, transfer scoped browser
state to an already-installed compatible client, or recover from browser bootstrap/authentication
failure. Do not use it for code-only, API-only, CLI-only, or database-native tasks that do not need
visible browser state.
## Quick Reference
| Need | Route |
| --- | --- |
| Manual SSO in the current browser | In-app Browser, then visible signed-in verification |
| Enterprise Edge or no Playwright installation | Fresh isolated Edge with copied profile and loopback CDP |
| Independent compatible browser context | Existing Playwright plus scoped `storageState` or CDP state transfer |
| Missing auth or failed browser bootstrap | User-assisted login, recovery, or specification-only handoff |
## Requested browser and connection are binding
If the user names Chrome, Edge, Chrome DevTools MCP, CDP, or a local DevTools bridge, use only that
browser and connection method. Do not silently switch to the In-app Browser, a ChatGPT browser
extension, Playwright, Computer Use, another browser, or shell automation. If the requested surface is
not available, report the exact blocker and stop at that boundary.
## Operating contract
- Prefer a connector, API, CLI, or database-native check when it can answer the request without a browser.
- Use the in-app Browser first only when the user has not named a different browser or connection method.
- Ask the user to authenticate manually in the in-app Browser when its target redirects to SSO. Use its secure authentication capability; never ask for passwords or OTPs in chat.
- After in-app verification, use the fresh Edge path for reliable automation when the task needs CDP, enterprise extensions, or a reusable profile.
- Treat MCP configuration and MCP availability as separate checks. After configuration, verify that the server tools are present in the active tool registry. A successful `codex mcp get` check alone does not make the MCP usable.
- Require a live handshake, such as `list_pages`, and verify that the returned pages belong to the requested browser. If the tools are missing after configuration, ask the user to restart Codex or open a new task before continuing.
- Ask explicit permission before reusing the user's authenticated normal Edge profile or closing Edge.
- Copy only after Edge is closed, and copy to an isolated profile path. Treat the copy, cookies, tokens, local storage, and storage-state files as credentials.
- Bind CDP to `127.0.0.1`; never expose the port, WebSocket endpoint, profile, or auth state to a network, repository, log, screenshot, or Oracle review.
- Verify the tenant, host, path, title, authenticated DOM, and target page before interaction. Never guess the first tab or target ID.
- Default to read-only actions. The consuming SAP skill must explicitly authorize writes, publishing, deployment, planning, model, permission, or destructive actions.
- Browser startup, CDP attachment, or a successful login redirect is not evidence that the requested SAP task completed.
Load the focused references only when needed:
- `references/edge-cdp-control.md` for Edge launch, CDP discovery, target selection, and recovery.
- `references/auth-state-bootstrap.md` for copying an authenticated Edge profile, exporting scoped state when available, and injecting it into compatible clients.
- `references/in-app-browser-auth.md` for manual in-app authentication and capability boundaries.
- Run `scripts/edge-profile.ps1` for deterministic profile cloning, launch, status, and stop operations.
- Run `scripts/cdp-agent.mjs` for target discovery, inspection, interaction, screenshots, and authentication-state transfer. It requires Node.js 22 or newer and no npm packages.
## Standard workflow
### 1. Classify the task and choose a surface
Record the target application, tenant/host, requested URL, read/write intent, evidence required, and
whether the user approved profile reuse. Use this order:
1. Existing non-browser tool if sufficient.
2. The explicitly requested browser and connection method, after active-tool and live-handshake checks.
3. In-app Browser for visible authenticated UI and manual SSO when no other browser or connection was requested.
4. Fresh isolated Edge with loopback CDP for enterprise browser behavior and reusable authentication.
5. Already-installed Playwright connected over CDP or using local storage state.
6. Approved desktop/manual assistance or a specification-only handoff.
Do not install Playwright, browser binaries, MCP servers, or extensions in an enterprise environment
unless the user explicitly requests and approves that change. If Playwright is unavailable, Edge/CDP
remains the primary automation surface.
### 2. Authenticate in the in-app Browser
When no other browser or connection was requested, open the target using the installed Browser skill.
Inspect visible state. If the page requires SSO, pause for the user to complete the login manually
through the supported secure auth flow. Verify a positive signed-in signal on the target domain and
retain a screenshot or equivalent evidence when allowed.
Do not extract cookies, local storage, session storage, profile databases, passwords, or tokens from the
in-app Browser. Its session is independent from Edge. If it cannot expose an authenticated page after
manual login, record the failure and continue to the approved Edge path.
This route runs inside Codex or Claude Desktop. Its runtime validation is deferred to those desktop
environments and is not part of the standalone Edge/CDP acceptance tests.
### 3. Capture live Edge state, then bootstrap fresh Edge
Before touching the user's normal Edge profile, state the intended scope and ask for confirmation:
> I will capture the approved SAP session from the currently authenticated Edge target, close normal Edge, and clone its selected profile into an isolated automation directory. May I continue?
If the user declines, ask them to authenticate once in the isolated profile. If they approve:
1. Identify the normal Edge user-data root, selected `Default` or `Profile N`, target URL, tenant host,
target path/title, approved SAP origin, and local temporary state-file path.
2. While normal Edge is still running and visibly authenticated, open
`edge://inspect/#remote-debugging` and enable **Allow remote debugging for this browser instance**.
3. Run `scripts/cdp-agent.mjs export-auth` against the normal user-data directory. Require host, path,
and/or title filters that resolve exactly one approved page. Repeat `--origin` for approved SAP or
identity-provider cookie scopes.
4. Close normal Edge and verify no `msedge.exe` process still owns the source profile.
5. Run `scripts/edge-profile.ps1 -Action CloneLaunch` with the selected profile name and a new or empty
automation root. The helper preserves `Profile N`, refuses non-empty clone destinations, launches
with `--remote-debugging-port=0`, and verifies the listener discovered through `DevToolsActivePort`.
6. Run `scripts/cdp-agent.mjs inspect` and verify tenant, path, title, visible signed-in state, and page readiness.
7. If cloning lost volatile state, run `scripts/cdp-agent.mjs import-auth` against the isolated target,
reload, and repeat the authenticated-state inspection.
8. If authentication still fails, ask the user to log in once in the isolated profile. Reuse it later
with `scripts/edge-profile.ps1 -Action LaunchExisting`; never clone over a populated automation root.
The complete Windows commands, path checks, CDP probes, and recovery matrix are in
`references/edge-cdp-control.md` and `references/auth-state-bootstrap.md`.
### 4. Operate the verified target
Use the isolated Edge instance directly. Run `scripts/cdp-agent.mjs --help` for the complete command
surface. The bundled driver supports deterministic targets, inspection/snapshot, navigation,
evaluation, selector or coordinate clicks, text entry, key presses, screenshots, and auth-state
export/import without Playwright. Use an existing Playwright installation only when the consuming task
needs it; do not install it for this workflow.
Authentication transfer uses CDP `Storage.getCookies` and `Storage.setCookies` plus page-scoped
`localStorage` and `sessionStorage`. Recheck SSO redirects, SameSite behavior, certificates, and visible
readiness after import. The in-app Browser remains a separate session.
### 5. Verify readiness and perform the domain action
Before changing anything, verify:
- tenant and application identity;
- authenticated state, not merely a non-login URL;
- correct Story Designer, Modeler, Data Builder, SQL editor, or test target area;
- visible readiness markers and absence of blocking errors;
- approved host/path and selected target page;
- current model/story/widget metadata when the consuming skill requires it.
Capture page-specific evidence and explicit no-data/error states. Do not treat a spinner disappearing,
CDP connecting, or a browser window opening as task completion.
### 6. Recover or hand off honestly
Use the following fallback sequence:
1. Retry the selected browser using its documented troubleshooting guidance.
2. Use the Edge/CDP recovery and `DevToolsActivePort` fallback.
3. Ask for one-time manual authentication in the isolated Edge profile.
4. Use approved desktop/manual assistance if the environment supports it.
5. If no authenticated target can be verified, stop and provide an implementation-ready specification, the exact missing evidence, and the next manual action.
When the user explicitly named a browser or connection method, do not use this sequence to switch to a
different surface. Stop when the requested surface is unavailable or its live handshake fails.
Report authentication as `verified`, `missing`, `expired`, `blocked`, or `unknown`; never infer success
from browser bootstrap alone.
## Troubleshooting
Common failures are handled in the shared Edge reference: refused or missing CDP endpoints, `404`
discovery responses, wrong targets, SSO redirects, copied profiles that are not authenticated, policy
blocks, and runtime/widget errors. When recovery cannot establish a verified authenticated target,
stop and hand off the missing evidence rather than guessing or claiming completion.
## Sources and Verification
The public-source review and the distinction between documented behavior and unverified tenant behavior
are recorded in `docs/project/sap-browser-automation-source-review-2026-07-14.md`.
## Safety and evidence
Profile copies and auth-state files may contain cookies, refresh tokens, saved passwords, history,
extensions, and enterprise session data. Keep them in a user-local path with restricted access. Do not
place them under the repository, commit them, send them to Oracle, include them in bug reports, or
paste their contents into chat. Redact tenant IDs, story IDs, query strings, session-like URL values,
cookie values, WebSocket endpoints, and unrelated tabs from evidence.
For any write-capable action, record the approving user, target, intended mutation, before/after
verification, and rollback or cleanup status. The consuming SAP skill remains authoritative for
whether the action itself is allowed.