@deepraxis/sdk 0.1.1-dev.1a4524d → 0.1.1-dev.1ae4311
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/METHODS.md +909 -26
- package/README.md +2 -2
- package/dist/core/binary-operations.d.ts +3 -0
- package/dist/core/binary-operations.js +14 -0
- package/dist/core/credentials.d.ts +22 -3
- package/dist/core/credentials.js +44 -5
- package/dist/core/transport.d.ts +1 -1
- package/dist/core/transport.js +8 -4
- package/dist/generated/binary-operations.gen.d.ts +3 -0
- package/dist/generated/binary-operations.gen.js +14 -0
- package/dist/generated/index.d.ts +2 -2
- package/dist/generated/index.js +1 -1
- package/dist/generated/sdk.gen.d.ts +2014 -275
- package/dist/generated/sdk.gen.js +8476 -3321
- package/dist/generated/types.gen.d.ts +88745 -56886
- package/dist/helpers/browser-actions.d.ts +102 -0
- package/dist/helpers/browser-actions.js +146 -0
- package/dist/helpers/browser-connect-error.d.ts +28 -0
- package/dist/helpers/browser-connect-error.js +74 -0
- package/dist/helpers/browser-connect.d.ts +21 -2
- package/dist/helpers/browser-connect.js +133 -5
- package/dist/helpers/browser-decisions.d.ts +15 -0
- package/dist/helpers/browser-decisions.js +14 -0
- package/dist/helpers/browser-documentation.d.ts +1 -1
- package/dist/helpers/browser-documentation.js +20 -11
- package/dist/operations.generated.d.ts +36 -17857
- package/dist/operations.generated.js +17460 -6998
- package/dist/resources.generated.d.ts +2425 -152
- package/dist/resources.generated.js +558 -20
- package/package.json +1 -1
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ticket-944 — the `actions` driver: the Browser service driven over the public HTTP faces, with no Playwright and
|
|
3
|
+
* no `node:child_process`. A light machine cannot install `playwright-core` at all, so instead of asking to be
|
|
4
|
+
* upgraded it drives the same cloud session through:
|
|
5
|
+
*
|
|
6
|
+
* GET /browser/v1/sessions?name=<name>&status=RUNNING the live session this agent session already has
|
|
7
|
+
* POST /browser/v1/sessions open one under that name when there is none
|
|
8
|
+
* POST /browser/v1/sessions/<id>/actions run one page action (#942)
|
|
9
|
+
*
|
|
10
|
+
* The service executes each action on the session's own CDP control connection, so `open` / `click` / `fill` / …
|
|
11
|
+
* keep working on a machine with no browser stack of its own
|
|
12
|
+
* (`services/browser/src/domain/page-actions.ts`).
|
|
13
|
+
*/
|
|
14
|
+
/** Where screenshots land, matching the Playwright driver's directory. */
|
|
15
|
+
export declare const SCREENSHOT_DIR = ".praxis/screenshots";
|
|
16
|
+
/** The two `fs/promises` members this driver uses; the light isolate provides `fs/promises`, never sync `fs`. */
|
|
17
|
+
export interface FsPromisesLike {
|
|
18
|
+
mkdir(path: string, options: {
|
|
19
|
+
recursive: true;
|
|
20
|
+
}): Promise<unknown>;
|
|
21
|
+
writeFile(path: string, data: Uint8Array): Promise<unknown>;
|
|
22
|
+
}
|
|
23
|
+
/** What the actions driver needs from the platform and the process. All of it is injectable for tests. */
|
|
24
|
+
export interface BrowserActionsDeps {
|
|
25
|
+
api: string;
|
|
26
|
+
token: string;
|
|
27
|
+
/** The cloud session name — the agent session id, exactly as the Playwright path's connect URL uses it. */
|
|
28
|
+
name: string;
|
|
29
|
+
labels: Record<string, string>;
|
|
30
|
+
/** Browser context id (bsc_…) carrying saved sign-ins; omitted without one. */
|
|
31
|
+
context?: string;
|
|
32
|
+
home: string;
|
|
33
|
+
fetch: typeof globalThis.fetch;
|
|
34
|
+
fs: FsPromisesLike;
|
|
35
|
+
now: () => number;
|
|
36
|
+
}
|
|
37
|
+
/** An existing tab as `tabs.list` reports it. */
|
|
38
|
+
export interface ActionTabInfo {
|
|
39
|
+
id: string;
|
|
40
|
+
url: string;
|
|
41
|
+
title: string;
|
|
42
|
+
active: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* One option to select on a `<select>`, Playwright's own vocabulary: a string matches the option's value or its
|
|
46
|
+
* visible text, and an object matches by any of `value`, visible `label`, or 0-based `index` (every property it
|
|
47
|
+
* names must match).
|
|
48
|
+
*/
|
|
49
|
+
export type SelectOptionTarget = string | {
|
|
50
|
+
value?: string;
|
|
51
|
+
label?: string;
|
|
52
|
+
index?: number;
|
|
53
|
+
};
|
|
54
|
+
/** A page action's answer, structurally: every result kind carries at least `type`. */
|
|
55
|
+
type ActionAnswer = Record<string, unknown> & {
|
|
56
|
+
type?: unknown;
|
|
57
|
+
};
|
|
58
|
+
/** `~/.praxis/screenshots/<timestamp>-<tab>.png`, the Playwright driver's own naming. */
|
|
59
|
+
export declare const screenshotPath: (home: string, tab: string, now: number) => string;
|
|
60
|
+
/**
|
|
61
|
+
* base64 → bytes, without Buffer or atob: the light machine's isolate is promised neither, and the screenshot is
|
|
62
|
+
* the one binary this file writes. Characters outside the alphabet are ignored, as base64 decoders do.
|
|
63
|
+
*/
|
|
64
|
+
export declare function decodeBase64(text: string): Uint8Array;
|
|
65
|
+
/** One tab handle: every method is one page action on the resolved session. */
|
|
66
|
+
export interface ActionsTab {
|
|
67
|
+
readonly id: string;
|
|
68
|
+
snapshot(): Promise<string>;
|
|
69
|
+
click(ref: string): Promise<void>;
|
|
70
|
+
fill(ref: string, text: string): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* A native `<select>`: choose the options named here — Playwright's `locator.selectOption` vocabulary. A string
|
|
73
|
+
* matches the option's value or its visible text; `{ value }`, `{ label }` and `{ index }` match that property
|
|
74
|
+
* alone, and an object naming several properties must match all of them. Pass one item or a list of them; the answer
|
|
75
|
+
* is the values of the options selected (a single `<select>` keeps only the first match, a `multiple` keeps every
|
|
76
|
+
* one).
|
|
77
|
+
*/
|
|
78
|
+
selectOption(ref: string, values: SelectOptionTarget | readonly SelectOptionTarget[]): Promise<string[]>;
|
|
79
|
+
press(key: string): Promise<void>;
|
|
80
|
+
scroll(direction: 'up' | 'down', pixels?: number): Promise<void>;
|
|
81
|
+
evaluate(expression: string): Promise<unknown>;
|
|
82
|
+
screenshot(options?: {
|
|
83
|
+
fullPage?: boolean;
|
|
84
|
+
}): Promise<{
|
|
85
|
+
path: string;
|
|
86
|
+
hint: string;
|
|
87
|
+
}>;
|
|
88
|
+
}
|
|
89
|
+
/** The page-action client: session resolution, one request per action, one tab handle per tab id. */
|
|
90
|
+
export interface BrowserActions {
|
|
91
|
+
sessionId(): Promise<string>;
|
|
92
|
+
list(): Promise<ActionTabInfo[]>;
|
|
93
|
+
tab(id: string): ActionsTab;
|
|
94
|
+
/** One already-built action, for the shapes no tab method covers. */
|
|
95
|
+
action(body: Record<string, unknown>): Promise<ActionAnswer>;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Builds the actions client. It never opens a connection, imports Playwright, or reads a Node builtin: a session
|
|
99
|
+
* id is resolved once per call from the name, and every action is a request that returns its own answer.
|
|
100
|
+
*/
|
|
101
|
+
export declare function createBrowserActions(deps: BrowserActionsDeps): BrowserActions;
|
|
102
|
+
export {};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ticket-944 — the `actions` driver: the Browser service driven over the public HTTP faces, with no Playwright and
|
|
3
|
+
* no `node:child_process`. A light machine cannot install `playwright-core` at all, so instead of asking to be
|
|
4
|
+
* upgraded it drives the same cloud session through:
|
|
5
|
+
*
|
|
6
|
+
* GET /browser/v1/sessions?name=<name>&status=RUNNING the live session this agent session already has
|
|
7
|
+
* POST /browser/v1/sessions open one under that name when there is none
|
|
8
|
+
* POST /browser/v1/sessions/<id>/actions run one page action (#942)
|
|
9
|
+
*
|
|
10
|
+
* The service executes each action on the session's own CDP control connection, so `open` / `click` / `fill` / …
|
|
11
|
+
* keep working on a machine with no browser stack of its own
|
|
12
|
+
* (`services/browser/src/domain/page-actions.ts`).
|
|
13
|
+
*/
|
|
14
|
+
import { PraxisError } from "../core/errors.js";
|
|
15
|
+
/** The public own-face path prefix — the same one this SDK's connect URL is built on. */
|
|
16
|
+
const BROWSER_V1 = '/browser/v1';
|
|
17
|
+
/** Where screenshots land, matching the Playwright driver's directory. */
|
|
18
|
+
export const SCREENSHOT_DIR = '.praxis/screenshots';
|
|
19
|
+
/**
|
|
20
|
+
* A refusal becomes an error here and nowhere else: the server's own code, status and message travel unchanged,
|
|
21
|
+
* so ACTION_REF_STALE stays distinguishable from an outage (ticket-834's rule, for the actions door).
|
|
22
|
+
*/
|
|
23
|
+
function failure(status, body) {
|
|
24
|
+
const record = body;
|
|
25
|
+
const code = typeof record?.code === 'string' ? record.code : undefined;
|
|
26
|
+
const message = typeof record?.message === 'string' ? record.message
|
|
27
|
+
: typeof record?.error === 'string' ? record.error
|
|
28
|
+
: `The browser action failed with HTTP ${status}.`;
|
|
29
|
+
return new PraxisError({ status, ...(code === undefined ? {} : { code }), message, raw: body });
|
|
30
|
+
}
|
|
31
|
+
/** `~/.praxis/screenshots/<timestamp>-<tab>.png`, the Playwright driver's own naming. */
|
|
32
|
+
export const screenshotPath = (home, tab, now) => `${home}/${SCREENSHOT_DIR}/${now}-${tab.slice(0, 8)}.png`;
|
|
33
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
34
|
+
/**
|
|
35
|
+
* base64 → bytes, without Buffer or atob: the light machine's isolate is promised neither, and the screenshot is
|
|
36
|
+
* the one binary this file writes. Characters outside the alphabet are ignored, as base64 decoders do.
|
|
37
|
+
*/
|
|
38
|
+
export function decodeBase64(text) {
|
|
39
|
+
const clean = text.replace(/[^A-Za-z0-9+/]/g, '');
|
|
40
|
+
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
|
|
41
|
+
let byte = 0;
|
|
42
|
+
let bits = 0;
|
|
43
|
+
let written = 0;
|
|
44
|
+
for (const character of clean) {
|
|
45
|
+
const value = ALPHABET.indexOf(character);
|
|
46
|
+
if (value < 0)
|
|
47
|
+
continue;
|
|
48
|
+
byte = (byte << 6) | value;
|
|
49
|
+
bits += 6;
|
|
50
|
+
if (bits >= 8) {
|
|
51
|
+
bits -= 8;
|
|
52
|
+
out[written++] = (byte >> bits) & 0xff;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return out.subarray(0, written);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Builds the actions client. It never opens a connection, imports Playwright, or reads a Node builtin: a session
|
|
59
|
+
* id is resolved once per call from the name, and every action is a request that returns its own answer.
|
|
60
|
+
*/
|
|
61
|
+
export function createBrowserActions(deps) {
|
|
62
|
+
const request = async (path, init = {}) => {
|
|
63
|
+
const headers = {
|
|
64
|
+
Authorization: `Bearer ${deps.token}`,
|
|
65
|
+
...(init.body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
66
|
+
...(init.headers ?? {}),
|
|
67
|
+
};
|
|
68
|
+
let response;
|
|
69
|
+
try {
|
|
70
|
+
response = await deps.fetch(`${deps.api}${BROWSER_V1}${path}`, { ...init, headers });
|
|
71
|
+
}
|
|
72
|
+
catch (cause) {
|
|
73
|
+
throw new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message: `Reaching the cloud browser failed: ${cause.message.split('\n')[0]}` });
|
|
74
|
+
}
|
|
75
|
+
const text = await response.text();
|
|
76
|
+
let body;
|
|
77
|
+
try {
|
|
78
|
+
body = text ? JSON.parse(text) : undefined;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
body = text;
|
|
82
|
+
}
|
|
83
|
+
if (!response.ok)
|
|
84
|
+
throw failure(response.status, body);
|
|
85
|
+
return body;
|
|
86
|
+
};
|
|
87
|
+
/** Resolved once per client: one connect() is one program, and the session it named does not change inside it. */
|
|
88
|
+
let resolved;
|
|
89
|
+
/** The live session named for this agent session, else a new one under that name. */
|
|
90
|
+
const sessionId = async () => {
|
|
91
|
+
resolved ??= (async () => {
|
|
92
|
+
const found = (await request(`/sessions?name=${encodeURIComponent(deps.name)}&status=RUNNING`));
|
|
93
|
+
// A page holds only this account's sessions, but a name is what identifies ours: anything else is not it.
|
|
94
|
+
const live = (found?.data ?? []).find(row => typeof row.id === 'string' && row.name === deps.name);
|
|
95
|
+
if (live?.id)
|
|
96
|
+
return live.id;
|
|
97
|
+
const created = (await request('/sessions', {
|
|
98
|
+
method: 'POST',
|
|
99
|
+
body: JSON.stringify({
|
|
100
|
+
name: deps.name,
|
|
101
|
+
labels: deps.labels,
|
|
102
|
+
...(deps.context === undefined ? {} : { browserSettings: { context: { id: deps.context, persist: true } } }),
|
|
103
|
+
}),
|
|
104
|
+
}));
|
|
105
|
+
if (typeof created?.id !== 'string')
|
|
106
|
+
throw new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message: 'The cloud browser session could not be opened.' });
|
|
107
|
+
return created.id;
|
|
108
|
+
})();
|
|
109
|
+
// A failed resolution is not cached: the next action may find the service again.
|
|
110
|
+
return await resolved.catch(cause => { resolved = undefined; throw cause; });
|
|
111
|
+
};
|
|
112
|
+
const action = async (body) => {
|
|
113
|
+
const id = await sessionId();
|
|
114
|
+
return (await request(`/sessions/${encodeURIComponent(id)}/actions`, { method: 'POST', body: JSON.stringify(body) }));
|
|
115
|
+
};
|
|
116
|
+
const list = async () => {
|
|
117
|
+
const answer = await action({ type: 'tabs.list' });
|
|
118
|
+
return (answer.tabs ?? []).map(tab => ({ id: tab.id, url: tab.url, title: tab.title, active: tab.active }));
|
|
119
|
+
};
|
|
120
|
+
const tab = (id) => {
|
|
121
|
+
const on = (type, extra = {}) => action({ type, tab: id, ...extra });
|
|
122
|
+
return {
|
|
123
|
+
id,
|
|
124
|
+
// The server's own rendering; same reading model as the Playwright driver's ariaSnapshot({ mode: "ai" }).
|
|
125
|
+
snapshot: async () => String((await on('snapshot')).snapshot ?? ''),
|
|
126
|
+
click: async (ref) => { await on('click', { ref }); },
|
|
127
|
+
fill: async (ref, text) => { await on('fill', { ref, text }); },
|
|
128
|
+
selectOption: async (ref, values) => {
|
|
129
|
+
// Playwright takes one item or a list; the wire always carries the list.
|
|
130
|
+
const answer = await on('select', { ref, values: Array.isArray(values) ? values : [values] });
|
|
131
|
+
return (answer.values ?? []).filter((value) => typeof value === 'string');
|
|
132
|
+
},
|
|
133
|
+
press: async (key) => { await on('press', { key }); },
|
|
134
|
+
scroll: async (direction, pixels) => { await on('scroll', { direction, ...(pixels === undefined ? {} : { pixels }) }); },
|
|
135
|
+
evaluate: async (expression) => (await on('evaluate', { expression })).value,
|
|
136
|
+
screenshot: async (options) => {
|
|
137
|
+
const answer = await on('screenshot', options?.fullPage === true ? { fullPage: true } : {});
|
|
138
|
+
const path = screenshotPath(deps.home, id, deps.now());
|
|
139
|
+
await deps.fs.mkdir(`${deps.home}/${SCREENSHOT_DIR}`, { recursive: true });
|
|
140
|
+
await deps.fs.writeFile(path, decodeBase64(String(answer.data ?? '')));
|
|
141
|
+
return { path, hint: 'View this PNG with the Read tool.' };
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
return { sessionId, list, tab, action };
|
|
146
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ticket-3252 — the function core for a refused CDP connect (ADR-024): one pure classification, the code the
|
|
3
|
+
* server named travels unchanged, and no refusal collapses into a generic one on the way out.
|
|
4
|
+
*
|
|
5
|
+
* Playwright's transport rejects with `WebSocket error: <url> <status> <statusWord>\n<body>` when the CDP upgrade
|
|
6
|
+
* is answered (ticket-834), and the body is the server's problem document — but the body does not always survive
|
|
7
|
+
* the handshake (`WebSocket error: wss://…/browser/v1/connect 409 Conflict`). The old fallback read only the body,
|
|
8
|
+
* so every body-less refusal became a 503 BROWSER_UNAVAILABLE: an agent met the retryable CONTEXT_LOCKED the
|
|
9
|
+
* service was holding (services/browser/src/api/rpc-contract.ts:208) as an outage it cannot act on.
|
|
10
|
+
*
|
|
11
|
+
* Owner of the status -> code mapping is the domain exit (services/browser/src/api/rpc-contract.ts), which the
|
|
12
|
+
* SDK mirrors by status only where the status is unambiguous on the connect path: 409 there is CONTEXT_LOCKED
|
|
13
|
+
* alone, 503 alone is SERVICE_UNAVAILABLE (:219). A body that names a code always wins over that mirror.
|
|
14
|
+
*/
|
|
15
|
+
/** A refusal read as the fields the SDK raises it with. */
|
|
16
|
+
export interface ConnectRefusal {
|
|
17
|
+
readonly status: number;
|
|
18
|
+
readonly code: string;
|
|
19
|
+
readonly message: string;
|
|
20
|
+
/** The refusal body, when the handshake carried a readable one. */
|
|
21
|
+
readonly raw?: unknown;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The refusal a Playwright connect failure stands for. Total and pure: the same message always yields the same
|
|
25
|
+
* classification. The body's own code wins (the domain code crosses the boundary unchanged); with no readable
|
|
26
|
+
* body the status line names it, so a 409 arrives as CONTEXT_LOCKED rather than a 503.
|
|
27
|
+
*/
|
|
28
|
+
export declare function classifyConnectRefusal(message: string): ConnectRefusal;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ticket-3252 — the function core for a refused CDP connect (ADR-024): one pure classification, the code the
|
|
3
|
+
* server named travels unchanged, and no refusal collapses into a generic one on the way out.
|
|
4
|
+
*
|
|
5
|
+
* Playwright's transport rejects with `WebSocket error: <url> <status> <statusWord>\n<body>` when the CDP upgrade
|
|
6
|
+
* is answered (ticket-834), and the body is the server's problem document — but the body does not always survive
|
|
7
|
+
* the handshake (`WebSocket error: wss://…/browser/v1/connect 409 Conflict`). The old fallback read only the body,
|
|
8
|
+
* so every body-less refusal became a 503 BROWSER_UNAVAILABLE: an agent met the retryable CONTEXT_LOCKED the
|
|
9
|
+
* service was holding (services/browser/src/api/rpc-contract.ts:208) as an outage it cannot act on.
|
|
10
|
+
*
|
|
11
|
+
* Owner of the status -> code mapping is the domain exit (services/browser/src/api/rpc-contract.ts), which the
|
|
12
|
+
* SDK mirrors by status only where the status is unambiguous on the connect path: 409 there is CONTEXT_LOCKED
|
|
13
|
+
* alone, 503 alone is SERVICE_UNAVAILABLE (:219). A body that names a code always wins over that mirror.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* What a status line alone names, when the refusal body carried no code. Only statuses that the connect path
|
|
17
|
+
* answers with one unambiguous domain code belong here; anything else stays the outage.
|
|
18
|
+
*/
|
|
19
|
+
const CODE_BY_STATUS = {
|
|
20
|
+
400: 'INVALID_PARAMS',
|
|
21
|
+
401: 'UNAUTHENTICATED',
|
|
22
|
+
402: 'QUOTA_EXHAUSTED',
|
|
23
|
+
403: 'FORBIDDEN',
|
|
24
|
+
404: 'NOT_FOUND',
|
|
25
|
+
409: 'CONTEXT_LOCKED',
|
|
26
|
+
429: 'RATE_LIMITED',
|
|
27
|
+
};
|
|
28
|
+
/** The only useful thing to say about a locked sign-in context: wait for the lease, or leave it alone. */
|
|
29
|
+
const CONTEXT_LOCKED_MESSAGE = "The agent's saved sign-in context is locked by another session; retry shortly, or mount it read-only (persist:false).";
|
|
30
|
+
/** 503 is the outage: the service answered 503, or the SDK holds nothing that names the failure. */
|
|
31
|
+
const outage = (message) => ({ status: 503, code: 'BROWSER_UNAVAILABLE', message });
|
|
32
|
+
/** The object a body text parses to, or undefined when it is not a JSON object. */
|
|
33
|
+
function jsonObject(text) {
|
|
34
|
+
try {
|
|
35
|
+
const value = JSON.parse(text);
|
|
36
|
+
return value !== null && typeof value === 'object' ? value : undefined;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** The status line and body a handshake answer carries, or null when the message is not that shape (a DNS or connect error, a timeout). */
|
|
43
|
+
function refusalFromMessage(message) {
|
|
44
|
+
const line = /WebSocket error: \S+ (\d{3})(?:[^\n]*)/.exec(message);
|
|
45
|
+
if (!line)
|
|
46
|
+
return null;
|
|
47
|
+
const status = Number(line[1]);
|
|
48
|
+
if (!Number.isInteger(status))
|
|
49
|
+
return null;
|
|
50
|
+
const at = message.indexOf('\n');
|
|
51
|
+
return { status, body: at < 0 ? undefined : jsonObject(message.slice(at + 1)) };
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The refusal a Playwright connect failure stands for. Total and pure: the same message always yields the same
|
|
55
|
+
* classification. The body's own code wins (the domain code crosses the boundary unchanged); with no readable
|
|
56
|
+
* body the status line names it, so a 409 arrives as CONTEXT_LOCKED rather than a 503.
|
|
57
|
+
*/
|
|
58
|
+
export function classifyConnectRefusal(message) {
|
|
59
|
+
const firstLine = message.split('\n')[0] ?? message;
|
|
60
|
+
const refusal = refusalFromMessage(message);
|
|
61
|
+
if (!refusal)
|
|
62
|
+
return outage(`Connecting to the cloud browser failed: ${firstLine}`);
|
|
63
|
+
const body = refusal.body;
|
|
64
|
+
const code = typeof body?.code === 'string' ? body.code : undefined;
|
|
65
|
+
if (code !== undefined && body) {
|
|
66
|
+
const retryAfter = typeof body.retryAfter === 'number' && Number.isFinite(body.retryAfter) ? body.retryAfter : null;
|
|
67
|
+
const text = typeof body.message === 'string' ? body.message : undefined;
|
|
68
|
+
return { status: refusal.status, code, message: `${text ?? code}${retryAfter === null ? '' : ` Retry after ${retryAfter} s.`}`, raw: body };
|
|
69
|
+
}
|
|
70
|
+
const byStatus = CODE_BY_STATUS[refusal.status];
|
|
71
|
+
if (byStatus === undefined)
|
|
72
|
+
return outage(`Connecting to the cloud browser failed: ${firstLine}`);
|
|
73
|
+
return { status: refusal.status, code: byStatus, message: refusal.status === 409 ? CONTEXT_LOCKED_MESSAGE : firstLine };
|
|
74
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PraxisError } from '../core/errors.js';
|
|
2
|
+
import { type SelectOptionTarget } from './browser-actions.js';
|
|
2
3
|
import { type BrowserTabInfo, type ContextLike } from './browser-decisions.js';
|
|
3
4
|
/** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
|
|
4
5
|
export declare const PLAYWRIGHT_CORE_VERSION = "1.63.0";
|
|
@@ -6,7 +7,7 @@ export declare const PLAYWRIGHT_CORE_VERSION = "1.63.0";
|
|
|
6
7
|
export type PlaywrightPage = any;
|
|
7
8
|
export interface BrowserTab {
|
|
8
9
|
readonly id: string;
|
|
9
|
-
/** The Playwright Page for locators and waits. */
|
|
10
|
+
/** The Playwright Page for locators and waits. Absent in the `actions` driver, where reading it throws. */
|
|
10
11
|
readonly playwright: PlaywrightPage;
|
|
11
12
|
goto(url: string): Promise<void>;
|
|
12
13
|
back(): Promise<void>;
|
|
@@ -15,8 +16,24 @@ export interface BrowserTab {
|
|
|
15
16
|
close(): Promise<void>;
|
|
16
17
|
url(): Promise<string>;
|
|
17
18
|
title(): Promise<string>;
|
|
18
|
-
/** The page as
|
|
19
|
+
/** The page as an accessibility snapshot with [ref=eN] marks: Playwright's, or the server's own text. */
|
|
19
20
|
snapshot(): Promise<string>;
|
|
21
|
+
/** Clicks the element a snapshot marked `[ref=eN]`. */
|
|
22
|
+
click(ref: string): Promise<void>;
|
|
23
|
+
/** Fills the element a snapshot marked `[ref=eN]`. */
|
|
24
|
+
fill(ref: string, text: string): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Chooses the options of the native `<select>` a snapshot marked `[ref=eN]` — Playwright's `locator.selectOption`:
|
|
27
|
+
* a string matches a value or a visible label, an object matches by `value` / `label` / `index`, and a list selects
|
|
28
|
+
* every match. Answers the values selected.
|
|
29
|
+
*/
|
|
30
|
+
selectOption(ref: string, values: SelectOptionTarget | readonly SelectOptionTarget[]): Promise<string[]>;
|
|
31
|
+
/** Presses one key (Enter, Tab, a single character). */
|
|
32
|
+
press(key: string): Promise<void>;
|
|
33
|
+
/** Scrolls the page by `pixels` (default 800) in one direction. */
|
|
34
|
+
scroll(direction: 'up' | 'down', pixels?: number): Promise<void>;
|
|
35
|
+
/** Evaluates an expression in the page and returns its value. */
|
|
36
|
+
evaluate(expression: string): Promise<unknown>;
|
|
20
37
|
/** Writes a PNG under ~/.praxis/screenshots and returns its path; view it with the Read tool. */
|
|
21
38
|
screenshot(options?: {
|
|
22
39
|
fullPage?: boolean;
|
|
@@ -80,6 +97,8 @@ export interface BrowserConnectDeps {
|
|
|
80
97
|
now?: () => number;
|
|
81
98
|
/** An already-loaded playwright-core; the real loader finds or installs one and imports it. */
|
|
82
99
|
playwright?: PlaywrightModule;
|
|
100
|
+
/** The fetch the actions driver sends its requests with; globalThis.fetch by default. */
|
|
101
|
+
fetch?: typeof globalThis.fetch;
|
|
83
102
|
}
|
|
84
103
|
export declare const unavailable: (message: string) => PraxisError;
|
|
85
104
|
/** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
|
|
@@ -7,12 +7,16 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
7
7
|
return path;
|
|
8
8
|
};
|
|
9
9
|
import { PraxisError } from "../core/errors.js";
|
|
10
|
+
import { classifyConnectRefusal } from "./browser-connect-error.js";
|
|
10
11
|
import { BROWSER_DOCUMENTATION } from "./browser-documentation.js";
|
|
11
|
-
import {
|
|
12
|
+
import { createBrowserActions } from "./browser-actions.js";
|
|
13
|
+
import { agentContextName, buildConnectUrl, decideBrowserDriver, decideTabReuse, isDuplicateNameError, matchTargetsToPages, pickAgentContext, pickContextByName } from "./browser-decisions.js";
|
|
12
14
|
/** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
|
|
13
15
|
export const PLAYWRIGHT_CORE_VERSION = '1.63.0';
|
|
14
16
|
const GLOBAL_PLAYWRIGHT = '/usr/local/lib/node_modules/playwright-core';
|
|
15
17
|
const IDLE_MS = 300_000;
|
|
18
|
+
/** A scroll without a distance moves this far, the server's own default (PAGE_ACTION_LIMITS.scrollPixelsDefault). */
|
|
19
|
+
const SCROLL_PIXELS_DEFAULT = 800;
|
|
16
20
|
export const unavailable = (message) => new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message });
|
|
17
21
|
/** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
|
|
18
22
|
export const needsFullMachine = () => Object.assign(new Error('The cloud browser needs a full sandbox — upgrade this instance'), { code: 'PROGRAM_NEEDS_FULL_MACHINE' });
|
|
@@ -32,6 +36,31 @@ function node(deps, name) {
|
|
|
32
36
|
}
|
|
33
37
|
throw needsFullMachine();
|
|
34
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Whether this runtime can load `node:child_process` — the one capability the Playwright driver needs and the
|
|
41
|
+
* actions driver does not. A refusal is a fact about the machine, never an error: it selects the driver.
|
|
42
|
+
*/
|
|
43
|
+
function hasChildProcess(deps) {
|
|
44
|
+
if (!deps.builtin)
|
|
45
|
+
return false;
|
|
46
|
+
try {
|
|
47
|
+
return Boolean(deps.builtin('node:child_process'));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** An optional builtin: absent (or refused) answers undefined instead of throwing, for modules a driver may not need. */
|
|
54
|
+
function optionalNode(deps, name) {
|
|
55
|
+
if (!deps.builtin)
|
|
56
|
+
return undefined;
|
|
57
|
+
try {
|
|
58
|
+
return deps.builtin(name) ?? undefined;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
35
64
|
async function loadPlaywright(deps, home) {
|
|
36
65
|
if (deps.playwright)
|
|
37
66
|
return deps.playwright;
|
|
@@ -96,6 +125,89 @@ async function ensureContext(deps, agentId) {
|
|
|
96
125
|
}
|
|
97
126
|
}
|
|
98
127
|
const bounded = (work, ms) => Promise.race([work, new Promise((_, reject) => setTimeout(() => reject(new Error('timed out')), ms))]);
|
|
128
|
+
/**
|
|
129
|
+
* The light machine's browser: every call is one page action over HTTP, so nothing here loads playwright-core,
|
|
130
|
+
* reads `node:child_process`, or keeps a connection open. Tabs are addressed by the CDP target id the service
|
|
131
|
+
* reports, which is the same id the Playwright driver hands out.
|
|
132
|
+
*/
|
|
133
|
+
async function connectActions(deps, settings) {
|
|
134
|
+
// fs/promises is what the light isolate provides (sync fs is refused there); screenshots go through it.
|
|
135
|
+
const fs = optionalNode(deps, 'node:fs/promises');
|
|
136
|
+
if (!fs)
|
|
137
|
+
throw unavailable('praxis.browser.connect() needs node:fs/promises on the session machine to save screenshots.');
|
|
138
|
+
const client = createBrowserActions({
|
|
139
|
+
api: settings.api, token: settings.token, name: settings.name,
|
|
140
|
+
labels: { agent_session: settings.name, agent: settings.agentId },
|
|
141
|
+
context: settings.context, home: settings.home, fs, now: settings.now,
|
|
142
|
+
// Bound: a Worker isolate (the light machine) throws "Illegal invocation" when fetch is called as a method of another object.
|
|
143
|
+
fetch: deps.fetch ?? globalThis.fetch.bind(globalThis),
|
|
144
|
+
});
|
|
145
|
+
const noPlaywright = () => new PraxisError({
|
|
146
|
+
status: 501, code: 'BROWSER_DRIVER_ACTIONS',
|
|
147
|
+
message: 'This machine drives the cloud browser through server-side page actions, so tab.playwright is not available. '
|
|
148
|
+
+ 'Available: goto, back, forward, reload, url, title, snapshot, click(ref), fill(ref, text), selectOption(ref, values), press(key), scroll(direction, pixels), evaluate(expression), screenshot, close. '
|
|
149
|
+
+ 'Run this program on an environment with the heavy machine template when a Playwright Page is required.',
|
|
150
|
+
});
|
|
151
|
+
/** One tab: the actions client plus the navigation shapes it does not own. */
|
|
152
|
+
const wrap = async (id) => {
|
|
153
|
+
const tab = client.tab(id);
|
|
154
|
+
/** Where the tab is now, in one action: evaluate answers url and title together. */
|
|
155
|
+
const located = () => tab.evaluate('({ url: location.href, title: document.title })');
|
|
156
|
+
return {
|
|
157
|
+
id,
|
|
158
|
+
get playwright() { throw noPlaywright(); },
|
|
159
|
+
goto: async (target) => { await client.action({ type: 'open', url: target, tab: id }); },
|
|
160
|
+
back: async () => { await client.action({ type: 'back', tab: id }); },
|
|
161
|
+
forward: async () => { await client.action({ type: 'forward', tab: id }); },
|
|
162
|
+
reload: async () => { await client.action({ type: 'reload', tab: id }); },
|
|
163
|
+
// The actions face has no close: report it, and leave the tab for the session to release.
|
|
164
|
+
close: async () => { throw unavailable('The server-side page actions have no close-tab action; leave the tab open and the cloud session releases it when it idles out.'); },
|
|
165
|
+
url: async () => String((await located()).url ?? ''),
|
|
166
|
+
title: async () => String((await located()).title ?? ''),
|
|
167
|
+
snapshot: () => tab.snapshot(),
|
|
168
|
+
click: ref => tab.click(ref),
|
|
169
|
+
fill: (ref, text) => tab.fill(ref, text),
|
|
170
|
+
selectOption: (ref, values) => tab.selectOption(ref, values),
|
|
171
|
+
press: key => tab.press(key),
|
|
172
|
+
scroll: (direction, pixels) => tab.scroll(direction, pixels ?? SCROLL_PIXELS_DEFAULT),
|
|
173
|
+
evaluate: expression => tab.evaluate(expression),
|
|
174
|
+
screenshot: options => tab.screenshot(options),
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
const ids = async () => (await client.list()).map(entry => entry.id);
|
|
178
|
+
const openTab = async (target, options) => {
|
|
179
|
+
const tabs = await client.list();
|
|
180
|
+
if (options?.reuseTab !== false) {
|
|
181
|
+
const reuse = decideTabReuse(target, tabs);
|
|
182
|
+
if (reuse) {
|
|
183
|
+
const tab = await wrap(reuse.id);
|
|
184
|
+
await tab.goto(target);
|
|
185
|
+
return tab;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const answer = await client.action({ type: 'open', url: target, ...(tabs.length === 0 ? {} : { newTab: true }) });
|
|
189
|
+
return await wrap(String(answer.tab ?? ''));
|
|
190
|
+
};
|
|
191
|
+
return {
|
|
192
|
+
tabs: {
|
|
193
|
+
list: () => client.list(),
|
|
194
|
+
get: async (id) => {
|
|
195
|
+
if (!(await ids()).includes(id))
|
|
196
|
+
throw new PraxisError({ status: 404, code: 'TAB_NOT_FOUND', message: `No tab with id ${id}; call browser.tabs.list() for the current tabs.` });
|
|
197
|
+
return await wrap(id);
|
|
198
|
+
},
|
|
199
|
+
new: async () => {
|
|
200
|
+
// `open` with `newTab` is the only way the actions face creates a page.
|
|
201
|
+
const answer = await client.action({ type: 'open', url: 'about:blank', newTab: true });
|
|
202
|
+
return await wrap(String(answer.tab ?? ''));
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
open: openTab,
|
|
206
|
+
documentation: () => BROWSER_DOCUMENTATION,
|
|
207
|
+
/** Drops this connection's session id only; the cloud session is left to idle out, as in the Playwright path. */
|
|
208
|
+
disconnect: async () => undefined,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
99
211
|
export async function connectBrowser(deps, options = {}) {
|
|
100
212
|
const { PRAXIS_API: api, PRAXIS_RUN_TOKEN: token, PRAXIS_AGENT_ID: agentId, PRAXIS_SESSION_ID: sessionId } = deps.env;
|
|
101
213
|
const missing = ['PRAXIS_API', 'PRAXIS_RUN_TOKEN', 'PRAXIS_AGENT_ID', 'PRAXIS_SESSION_ID'].filter(name => !deps.env[name]);
|
|
@@ -103,18 +215,25 @@ export async function connectBrowser(deps, options = {}) {
|
|
|
103
215
|
throw unavailable(`praxis.browser.connect() runs inside an agent session; ${missing.join(', ')} ${missing.length > 1 ? 'are' : 'is'} not set. Use praxis.browser.sessions.create() for a standalone cloud browser.`);
|
|
104
216
|
}
|
|
105
217
|
const home = deps.env.HOME ?? '/home/user';
|
|
106
|
-
const
|
|
218
|
+
const now = deps.now ?? Date.now;
|
|
219
|
+
const driver = decideBrowserDriver({ override: deps.env.PRAXIS_BROWSER_DRIVER, childProcessAvailable: hasChildProcess(deps) });
|
|
107
220
|
const context = options.context === false ? undefined : await ensureContext(deps, agentId);
|
|
221
|
+
// The light machine drives the browser the service already runs; it never asks to be upgraded.
|
|
222
|
+
if (driver === 'actions')
|
|
223
|
+
return await connectActions(deps, { api, token, name: sessionId, agentId, home, context, now });
|
|
224
|
+
const playwright = await loadPlaywright(deps, home);
|
|
108
225
|
const url = buildConnectUrl({ api, name: sessionId, context, idleMs: IDLE_MS, labels: { agent_session: sessionId, agent: agentId } });
|
|
109
226
|
let browser;
|
|
110
227
|
try {
|
|
111
228
|
browser = await playwright.chromium.connectOverCDP(url, { headers: { Authorization: `Bearer ${token}` }, timeout: 60_000 });
|
|
112
229
|
}
|
|
113
230
|
catch (cause) {
|
|
114
|
-
|
|
231
|
+
// A refusal that named itself travels as itself (ADR-024: a locked context is 409 CONTEXT_LOCKED, not a 503);
|
|
232
|
+
// only a real 503, or a failure with no status to read, is the outage it looks like (ticket-834, ticket-3252).
|
|
233
|
+
const refusal = classifyConnectRefusal(cause instanceof Error ? cause.message : String(cause));
|
|
234
|
+
throw new PraxisError({ status: refusal.status, code: refusal.code, message: refusal.message, raw: refusal.raw });
|
|
115
235
|
}
|
|
116
236
|
const fs = node(deps, 'node:fs');
|
|
117
|
-
const now = deps.now ?? Date.now;
|
|
118
237
|
const pages = () => browser.contexts().flatMap((c) => c.pages());
|
|
119
238
|
const ids = new WeakMap();
|
|
120
239
|
/** One browser-level CDP session for the connection: `Target.getTargets` answers for every tab in one round trip. */
|
|
@@ -189,6 +308,14 @@ export async function connectBrowser(deps, options = {}) {
|
|
|
189
308
|
url: async () => page.url(),
|
|
190
309
|
title: async () => page.title(),
|
|
191
310
|
snapshot: async () => page.ariaSnapshot({ mode: 'ai' }),
|
|
311
|
+
// `aria-ref=` is Playwright's own spelling of a snapshot ref, so the two drivers act on the same handle.
|
|
312
|
+
click: async (ref) => { await page.locator(`aria-ref=${ref}`).click(); },
|
|
313
|
+
fill: async (ref, text) => { await page.locator(`aria-ref=${ref}`).fill(text); },
|
|
314
|
+
// Playwright's own locator.selectOption takes exactly these matchers, and answers the values it selected.
|
|
315
|
+
selectOption: async (ref, values) => await page.locator(`aria-ref=${ref}`).selectOption(values),
|
|
316
|
+
press: async (key) => { await page.keyboard.press(key); },
|
|
317
|
+
scroll: async (direction, pixels) => { await page.mouse.wheel(0, direction === 'down' ? pixels ?? SCROLL_PIXELS_DEFAULT : -(pixels ?? SCROLL_PIXELS_DEFAULT)); },
|
|
318
|
+
evaluate: async (expression) => await page.evaluate(expression),
|
|
192
319
|
screenshot: async (shot) => {
|
|
193
320
|
const dir = `${home}/.praxis/screenshots`;
|
|
194
321
|
fs.mkdirSync(dir, { recursive: true });
|
|
@@ -238,7 +365,8 @@ export async function connectBrowser(deps, options = {}) {
|
|
|
238
365
|
documentation: () => BROWSER_DOCUMENTATION,
|
|
239
366
|
/** Drops this connection only; the cloud session and its tabs stay until it idles out. */
|
|
240
367
|
disconnect: async () => {
|
|
241
|
-
|
|
368
|
+
// browser.close() drops the whole CDP connection, the browser-level session with it; detaching
|
|
369
|
+
// it first only added one more cross-region round trip (+0.6–0.8 s on the #829 LAB).
|
|
242
370
|
cdp = undefined;
|
|
243
371
|
await browser.close();
|
|
244
372
|
},
|
|
@@ -71,3 +71,18 @@ export declare function pickContextByName<T extends ContextLike & {
|
|
|
71
71
|
}>(contexts: readonly T[], agentId: string): T | undefined;
|
|
72
72
|
/** A context name is unique per account, so a create that loses a race answers INVALID_PARAMS with this phrase. */
|
|
73
73
|
export declare function isDuplicateNameError(error: unknown): boolean;
|
|
74
|
+
/** How this run drives the cloud browser: Playwright over CDP, or the service's own page actions over HTTP. */
|
|
75
|
+
export type BrowserDriver = "playwright" | "actions";
|
|
76
|
+
export interface BrowserDriverInput {
|
|
77
|
+
/** `PRAXIS_BROWSER_DRIVER`; anything other than `actions` / `playwright` is not an instruction. */
|
|
78
|
+
readonly override?: string;
|
|
79
|
+
/** Whether this runtime can load `node:child_process` — the one thing the actions driver does not need. */
|
|
80
|
+
readonly childProcessAvailable: boolean;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Which driver `praxis.browser.connect()` uses. The explicit override wins, so a full machine can exercise the
|
|
84
|
+
* actions path and a light machine can be told to try Playwright anyway. Without one, a runtime that cannot load
|
|
85
|
+
* `node:child_process` — the light machine, where installing playwright-core is impossible — drives the browser
|
|
86
|
+
* through the service's page actions instead of asking for an upgrade; everything else keeps Playwright.
|
|
87
|
+
*/
|
|
88
|
+
export declare function decideBrowserDriver(input: BrowserDriverInput): BrowserDriver;
|
|
@@ -121,3 +121,17 @@ export function isDuplicateNameError(error) {
|
|
|
121
121
|
const problem = error;
|
|
122
122
|
return problem?.code === 'INVALID_PARAMS' && typeof problem.message === 'string' && problem.message.includes('already exists');
|
|
123
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Which driver `praxis.browser.connect()` uses. The explicit override wins, so a full machine can exercise the
|
|
126
|
+
* actions path and a light machine can be told to try Playwright anyway. Without one, a runtime that cannot load
|
|
127
|
+
* `node:child_process` — the light machine, where installing playwright-core is impossible — drives the browser
|
|
128
|
+
* through the service's page actions instead of asking for an upgrade; everything else keeps Playwright.
|
|
129
|
+
*/
|
|
130
|
+
export function decideBrowserDriver(input) {
|
|
131
|
+
const override = input.override?.trim().toLowerCase();
|
|
132
|
+
if (override === "actions")
|
|
133
|
+
return "actions";
|
|
134
|
+
if (override === "playwright")
|
|
135
|
+
return "playwright";
|
|
136
|
+
return input.childProcessAvailable ? "playwright" : "actions";
|
|
137
|
+
}
|