@deepraxis/sdk 0.1.1 → 0.2.0-dev.af2cf98
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 +1958 -224
- package/README.md +10 -9
- package/dist/automation.d.ts +61 -0
- package/dist/core/binary-operations.d.ts +3 -0
- package/dist/core/binary-operations.js +14 -0
- package/dist/core/client.d.ts +11 -1
- package/dist/core/client.js +13 -0
- package/dist/core/credentials.d.ts +22 -3
- package/dist/core/credentials.js +44 -5
- package/dist/core/deprecation.d.ts +11 -0
- package/dist/core/deprecation.js +20 -0
- package/dist/core/errors.d.ts +6 -0
- package/dist/core/errors.js +8 -0
- package/dist/core/transport.d.ts +14 -1
- package/dist/core/transport.js +24 -6
- 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 +3961 -436
- package/dist/generated/sdk.gen.js +12309 -2283
- package/dist/generated/types.gen.d.ts +107107 -47137
- package/dist/helpers/application-build.d.ts +10 -0
- package/dist/helpers/application-build.js +98 -0
- package/dist/helpers/application-publish.d.ts +8 -0
- package/dist/helpers/application-publish.js +42 -11
- 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 +111 -0
- package/dist/helpers/browser-connect.js +396 -0
- package/dist/helpers/browser-decisions.d.ts +101 -0
- package/dist/helpers/browser-decisions.js +148 -0
- package/dist/helpers/browser-documentation.d.ts +2 -0
- package/dist/helpers/browser-documentation.js +66 -0
- package/dist/helpers/file-upload.d.ts +2 -2
- package/dist/helpers/sandbox-templates.d.ts +121 -0
- package/dist/helpers/sandbox-templates.js +60 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/operations.generated.d.ts +37 -13482
- package/dist/operations.generated.js +27399 -7229
- package/dist/resources.generated.d.ts +3884 -287
- package/dist/resources.generated.js +1255 -60
- package/package.json +2 -2
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { PraxisError } from '../core/errors.js';
|
|
2
|
+
import { type SelectOptionTarget } from './browser-actions.js';
|
|
3
|
+
import { type BrowserTabInfo, type ContextLike } from './browser-decisions.js';
|
|
4
|
+
/** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
|
|
5
|
+
export declare const PLAYWRIGHT_CORE_VERSION = "1.63.0";
|
|
6
|
+
/** Playwright's Page, kept structural: the SDK does not depend on playwright-core. */
|
|
7
|
+
export type PlaywrightPage = any;
|
|
8
|
+
export interface BrowserTab {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
/** The Playwright Page for locators and waits. Absent in the `actions` driver, where reading it throws. */
|
|
11
|
+
readonly playwright: PlaywrightPage;
|
|
12
|
+
goto(url: string): Promise<void>;
|
|
13
|
+
back(): Promise<void>;
|
|
14
|
+
forward(): Promise<void>;
|
|
15
|
+
reload(): Promise<void>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
url(): Promise<string>;
|
|
18
|
+
title(): Promise<string>;
|
|
19
|
+
/** The page as an accessibility snapshot with [ref=eN] marks: Playwright's, or the server's own text. */
|
|
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>;
|
|
37
|
+
/** Writes a PNG under ~/.praxis/screenshots and returns its path; view it with the Read tool. */
|
|
38
|
+
screenshot(options?: {
|
|
39
|
+
fullPage?: boolean;
|
|
40
|
+
}): Promise<{
|
|
41
|
+
path: string;
|
|
42
|
+
hint: string;
|
|
43
|
+
}>;
|
|
44
|
+
}
|
|
45
|
+
export interface PraxisBrowser {
|
|
46
|
+
readonly tabs: {
|
|
47
|
+
list(): Promise<BrowserTabInfo[]>;
|
|
48
|
+
get(id: string): Promise<BrowserTab>;
|
|
49
|
+
'new'(): Promise<BrowserTab>;
|
|
50
|
+
};
|
|
51
|
+
open(url: string, options?: {
|
|
52
|
+
reuseTab?: boolean;
|
|
53
|
+
}): Promise<BrowserTab>;
|
|
54
|
+
documentation(): string;
|
|
55
|
+
/** Drops this connection only; the cloud session and its tabs stay until it idles out. */
|
|
56
|
+
disconnect(): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
export interface BrowserConnectOptions {
|
|
59
|
+
/** false skips the agent's saved sign-in context. */
|
|
60
|
+
context?: false;
|
|
61
|
+
}
|
|
62
|
+
interface ContextsApi {
|
|
63
|
+
list(args?: {
|
|
64
|
+
query?: {
|
|
65
|
+
limit?: number;
|
|
66
|
+
cursor?: string;
|
|
67
|
+
name?: string;
|
|
68
|
+
};
|
|
69
|
+
}): Promise<{
|
|
70
|
+
data: (ContextLike & {
|
|
71
|
+
name?: unknown;
|
|
72
|
+
})[];
|
|
73
|
+
nextCursor: string | null;
|
|
74
|
+
}>;
|
|
75
|
+
create(args: {
|
|
76
|
+
body: {
|
|
77
|
+
name: string;
|
|
78
|
+
labels: Record<string, string>;
|
|
79
|
+
};
|
|
80
|
+
}): Promise<ContextLike>;
|
|
81
|
+
}
|
|
82
|
+
/** The playwright-core module shape the helper uses. */
|
|
83
|
+
export interface PlaywrightModule {
|
|
84
|
+
chromium: {
|
|
85
|
+
connectOverCDP(url: string, options: {
|
|
86
|
+
headers: Record<string, string>;
|
|
87
|
+
timeout?: number;
|
|
88
|
+
}): Promise<unknown>;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** What connect() needs from the platform client and the process. All of it is injectable for tests. */
|
|
92
|
+
export interface BrowserConnectDeps {
|
|
93
|
+
contexts: ContextsApi;
|
|
94
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
95
|
+
/** process.getBuiltinModule; undefined on runtimes without it. */
|
|
96
|
+
builtin: ((name: string) => unknown) | undefined;
|
|
97
|
+
now?: () => number;
|
|
98
|
+
/** An already-loaded playwright-core; the real loader finds or installs one and imports it. */
|
|
99
|
+
playwright?: PlaywrightModule;
|
|
100
|
+
/** The fetch the actions driver sends its requests with; globalThis.fetch by default. */
|
|
101
|
+
fetch?: typeof globalThis.fetch;
|
|
102
|
+
}
|
|
103
|
+
export declare const unavailable: (message: string) => PraxisError;
|
|
104
|
+
/** The validated tab id, or INVALID_PARAMS naming the method, before any round trip. */
|
|
105
|
+
export declare const requireTabId: (method: string, id: unknown) => string;
|
|
106
|
+
/** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
|
|
107
|
+
export declare const needsFullMachine: () => Error & {
|
|
108
|
+
code: string;
|
|
109
|
+
};
|
|
110
|
+
export declare function connectBrowser(deps: BrowserConnectDeps, options?: BrowserConnectOptions): Promise<PraxisBrowser>;
|
|
111
|
+
export {};
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { PraxisError } from "../core/errors.js";
|
|
10
|
+
import { classifyConnectRefusal } from "./browser-connect-error.js";
|
|
11
|
+
import { BROWSER_DOCUMENTATION } from "./browser-documentation.js";
|
|
12
|
+
import { createBrowserActions } from "./browser-actions.js";
|
|
13
|
+
import { agentContextName, browserSessionName, buildConnectUrl, decideBrowserDriver, decideTabReuse, isDuplicateNameError, matchTargetsToPages, pickAgentContext, pickContextByName } from "./browser-decisions.js";
|
|
14
|
+
/** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
|
|
15
|
+
export const PLAYWRIGHT_CORE_VERSION = '1.63.0';
|
|
16
|
+
const GLOBAL_PLAYWRIGHT = '/usr/local/lib/node_modules/playwright-core';
|
|
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;
|
|
20
|
+
export const unavailable = (message) => new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message });
|
|
21
|
+
/** The shape of a tab-id argument that is not a non-empty string, in the words the message uses. */
|
|
22
|
+
const argumentShape = (value) => typeof value === 'string' ? 'an empty string'
|
|
23
|
+
: value === null ? 'null'
|
|
24
|
+
: Array.isArray(value) ? 'an array'
|
|
25
|
+
: typeof value === 'object' ? 'an object'
|
|
26
|
+
: typeof value;
|
|
27
|
+
/** A tab method takes the id string. A wrong argument shape is the caller's mistake (400 INVALID_PARAMS),
|
|
28
|
+
* reported as the shape it is — never as a missing tab (404 TAB_NOT_FOUND), which is what passing the object
|
|
29
|
+
* `{ id }` / `{ tabId }` used to look like (ticket #3330). */
|
|
30
|
+
function tabIdArgument(method, value) {
|
|
31
|
+
const inner = value !== null && typeof value === 'object' ? value : undefined;
|
|
32
|
+
const named = typeof inner?.id === 'string' && inner.id ? inner.id : typeof inner?.tabId === 'string' && inner.tabId ? inner.tabId : undefined;
|
|
33
|
+
return new PraxisError({
|
|
34
|
+
status: 400, code: 'INVALID_PARAMS',
|
|
35
|
+
message: `${method}(id: string) takes the tab id string, e.g. ${method}(tab.id); got ${argumentShape(value)}${named ? `; pass ${method}(${JSON.stringify(named)})` : ''}`,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/** The validated tab id, or INVALID_PARAMS naming the method, before any round trip. */
|
|
39
|
+
export const requireTabId = (method, id) => typeof id === 'string' && id.length > 0 ? id : (() => { throw tabIdArgument(method, id); })();
|
|
40
|
+
/** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
|
|
41
|
+
export const needsFullMachine = () => Object.assign(new Error('The cloud browser needs a full sandbox — upgrade this instance'), { code: 'PROGRAM_NEEDS_FULL_MACHINE' });
|
|
42
|
+
/** Reads a Node builtin; a light machine's isolate refuses child_process, which is the signal to upgrade. */
|
|
43
|
+
function node(deps, name) {
|
|
44
|
+
if (!deps.builtin)
|
|
45
|
+
throw unavailable('praxis.browser.connect() needs Node.js 22.3 or newer on the session machine.');
|
|
46
|
+
try {
|
|
47
|
+
const module = deps.builtin(name);
|
|
48
|
+
if (module)
|
|
49
|
+
return module;
|
|
50
|
+
}
|
|
51
|
+
catch (cause) {
|
|
52
|
+
if (cause?.code === 'PROGRAM_NEEDS_FULL_MACHINE')
|
|
53
|
+
throw cause;
|
|
54
|
+
throw needsFullMachine();
|
|
55
|
+
}
|
|
56
|
+
throw needsFullMachine();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Whether this runtime can load `node:child_process` — the one capability the Playwright driver needs and the
|
|
60
|
+
* actions driver does not. A refusal is a fact about the machine, never an error: it selects the driver.
|
|
61
|
+
*/
|
|
62
|
+
function hasChildProcess(deps) {
|
|
63
|
+
if (!deps.builtin)
|
|
64
|
+
return false;
|
|
65
|
+
try {
|
|
66
|
+
return Boolean(deps.builtin('node:child_process'));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** An optional builtin: absent (or refused) answers undefined instead of throwing, for modules a driver may not need. */
|
|
73
|
+
function optionalNode(deps, name) {
|
|
74
|
+
if (!deps.builtin)
|
|
75
|
+
return undefined;
|
|
76
|
+
try {
|
|
77
|
+
return deps.builtin(name) ?? undefined;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function loadPlaywright(deps, home) {
|
|
84
|
+
if (deps.playwright)
|
|
85
|
+
return deps.playwright;
|
|
86
|
+
node(deps, 'node:child_process'); // fails fast on a light machine, before any network work
|
|
87
|
+
const fs = node(deps, 'node:fs');
|
|
88
|
+
const entry = (root) => `${root}/index.mjs`;
|
|
89
|
+
const cache = `${home}/.cache/praxis-browser`;
|
|
90
|
+
const cached = `${cache}/node_modules/playwright-core`;
|
|
91
|
+
let root = [GLOBAL_PLAYWRIGHT, cached].find(candidate => fs.existsSync(entry(candidate)));
|
|
92
|
+
if (!root) {
|
|
93
|
+
fs.mkdirSync(cache, { recursive: true });
|
|
94
|
+
if (!fs.existsSync(`${cache}/package.json`))
|
|
95
|
+
fs.writeFileSync(`${cache}/package.json`, '{"private":true}');
|
|
96
|
+
const cp = node(deps, 'node:child_process');
|
|
97
|
+
await new Promise((resolve, reject) => cp.execFile('npm', ['install', '--prefix', cache, '--no-save', '--no-audit', '--no-fund', `playwright-core@${PLAYWRIGHT_CORE_VERSION}`], { timeout: 180_000, env: { ...deps.env } }, error => error ? reject(unavailable(`Installing playwright-core@${PLAYWRIGHT_CORE_VERSION} failed: ${error.message.split('\n')[0]}`)) : resolve()));
|
|
98
|
+
root = cached;
|
|
99
|
+
}
|
|
100
|
+
return await import(__rewriteRelativeImportExtension(/* @vite-ignore */ `file://${entry(root)}`));
|
|
101
|
+
}
|
|
102
|
+
/** The agent's own context, in one name-filtered request; the paged scan is only the pre-`name` server fallback. */
|
|
103
|
+
async function ensureContext(deps, agentId) {
|
|
104
|
+
const name = agentContextName(agentId);
|
|
105
|
+
const byNameQuery = () => deps.contexts.list({ query: { name, limit: 1 } });
|
|
106
|
+
// A server that knows `name` answers with this agent's context or nothing; a non-empty answer of other rows means
|
|
107
|
+
// it ignored the filter, and only then is the paged scan worth its round trips.
|
|
108
|
+
const paged = async () => {
|
|
109
|
+
const seen = [];
|
|
110
|
+
let cursor;
|
|
111
|
+
for (let page = 0; page < 20; page++) {
|
|
112
|
+
const result = await deps.contexts.list({ query: { limit: 100, ...(cursor ? { cursor } : {}) } });
|
|
113
|
+
seen.push(...result.data);
|
|
114
|
+
const own = pickAgentContext(seen, agentId);
|
|
115
|
+
if (own)
|
|
116
|
+
return own.id;
|
|
117
|
+
if (!result.nextCursor)
|
|
118
|
+
break;
|
|
119
|
+
cursor = result.nextCursor;
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
};
|
|
123
|
+
const find = async () => {
|
|
124
|
+
const answer = (await byNameQuery()).data;
|
|
125
|
+
const byName = pickContextByName(answer, agentId);
|
|
126
|
+
if (byName)
|
|
127
|
+
return byName.id;
|
|
128
|
+
return answer.length > 0 ? paged() : undefined;
|
|
129
|
+
};
|
|
130
|
+
const existing = await find();
|
|
131
|
+
if (existing)
|
|
132
|
+
return existing;
|
|
133
|
+
try {
|
|
134
|
+
return (await deps.contexts.create({ body: { name, labels: { agent: agentId } } })).id;
|
|
135
|
+
}
|
|
136
|
+
catch (cause) {
|
|
137
|
+
// Names are unique per account, so this is a concurrent run winning the create: reuse what it made.
|
|
138
|
+
if (!isDuplicateNameError(cause))
|
|
139
|
+
throw cause;
|
|
140
|
+
const raced = await find();
|
|
141
|
+
if (raced)
|
|
142
|
+
return raced;
|
|
143
|
+
throw cause;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const bounded = (work, ms) => Promise.race([work, new Promise((_, reject) => setTimeout(() => reject(new Error('timed out')), ms))]);
|
|
147
|
+
/**
|
|
148
|
+
* The light machine's browser: every call is one page action over HTTP, so nothing here loads playwright-core,
|
|
149
|
+
* reads `node:child_process`, or keeps a connection open. Tabs are addressed by the CDP target id the service
|
|
150
|
+
* reports, which is the same id the Playwright driver hands out.
|
|
151
|
+
*/
|
|
152
|
+
async function connectActions(deps, settings) {
|
|
153
|
+
// fs/promises is what the light isolate provides (sync fs is refused there); screenshots go through it.
|
|
154
|
+
const fs = optionalNode(deps, 'node:fs/promises');
|
|
155
|
+
if (!fs)
|
|
156
|
+
throw unavailable('praxis.browser.connect() needs node:fs/promises on the session machine to save screenshots.');
|
|
157
|
+
const client = createBrowserActions({
|
|
158
|
+
api: settings.api, token: settings.token, name: settings.name,
|
|
159
|
+
labels: { agent_session: settings.sessionId, agent: settings.agentId },
|
|
160
|
+
context: settings.context, home: settings.home, fs, now: settings.now,
|
|
161
|
+
// Bound: a Worker isolate (the light machine) throws "Illegal invocation" when fetch is called as a method of another object.
|
|
162
|
+
fetch: deps.fetch ?? globalThis.fetch.bind(globalThis),
|
|
163
|
+
});
|
|
164
|
+
const noPlaywright = () => new PraxisError({
|
|
165
|
+
status: 501, code: 'BROWSER_DRIVER_ACTIONS',
|
|
166
|
+
message: 'This machine drives the cloud browser through server-side page actions, so tab.playwright is not available. '
|
|
167
|
+
+ '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. '
|
|
168
|
+
+ 'Run this program on an environment with the heavy machine template when a Playwright Page is required.',
|
|
169
|
+
});
|
|
170
|
+
/** One tab: the actions client plus the navigation shapes it does not own. */
|
|
171
|
+
const wrap = async (id) => {
|
|
172
|
+
const tab = client.tab(id);
|
|
173
|
+
/** Where the tab is now, in one action: evaluate answers url and title together. */
|
|
174
|
+
const located = () => tab.evaluate('({ url: location.href, title: document.title })');
|
|
175
|
+
return {
|
|
176
|
+
id,
|
|
177
|
+
get playwright() { throw noPlaywright(); },
|
|
178
|
+
goto: async (target) => { await client.action({ type: 'open', url: target, tab: id }); },
|
|
179
|
+
back: async () => { await client.action({ type: 'back', tab: id }); },
|
|
180
|
+
forward: async () => { await client.action({ type: 'forward', tab: id }); },
|
|
181
|
+
reload: async () => { await client.action({ type: 'reload', tab: id }); },
|
|
182
|
+
// The actions face has no close: report it, and leave the tab for the session to release.
|
|
183
|
+
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.'); },
|
|
184
|
+
url: async () => String((await located()).url ?? ''),
|
|
185
|
+
title: async () => String((await located()).title ?? ''),
|
|
186
|
+
snapshot: () => tab.snapshot(),
|
|
187
|
+
click: ref => tab.click(ref),
|
|
188
|
+
fill: (ref, text) => tab.fill(ref, text),
|
|
189
|
+
selectOption: (ref, values) => tab.selectOption(ref, values),
|
|
190
|
+
press: key => tab.press(key),
|
|
191
|
+
scroll: (direction, pixels) => tab.scroll(direction, pixels ?? SCROLL_PIXELS_DEFAULT),
|
|
192
|
+
evaluate: expression => tab.evaluate(expression),
|
|
193
|
+
screenshot: options => tab.screenshot(options),
|
|
194
|
+
};
|
|
195
|
+
};
|
|
196
|
+
const ids = async () => (await client.list()).map(entry => entry.id);
|
|
197
|
+
const openTab = async (target, options) => {
|
|
198
|
+
const tabs = await client.list();
|
|
199
|
+
if (options?.reuseTab !== false) {
|
|
200
|
+
const reuse = decideTabReuse(target, tabs);
|
|
201
|
+
if (reuse) {
|
|
202
|
+
const tab = await wrap(reuse.id);
|
|
203
|
+
await tab.goto(target);
|
|
204
|
+
return tab;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const answer = await client.action({ type: 'open', url: target, ...(tabs.length === 0 ? {} : { newTab: true }) });
|
|
208
|
+
return await wrap(String(answer.tab ?? ''));
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
tabs: {
|
|
212
|
+
list: () => client.list(),
|
|
213
|
+
get: async (id) => {
|
|
214
|
+
const tabId = requireTabId('tabs.get', id);
|
|
215
|
+
if (!(await ids()).includes(tabId))
|
|
216
|
+
throw new PraxisError({ status: 404, code: 'TAB_NOT_FOUND', message: `No tab with id ${tabId}; call browser.tabs.list() for the current tabs.` });
|
|
217
|
+
return await wrap(tabId);
|
|
218
|
+
},
|
|
219
|
+
new: async () => {
|
|
220
|
+
// `open` with `newTab` is the only way the actions face creates a page.
|
|
221
|
+
const answer = await client.action({ type: 'open', url: 'about:blank', newTab: true });
|
|
222
|
+
return await wrap(String(answer.tab ?? ''));
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
open: openTab,
|
|
226
|
+
documentation: () => BROWSER_DOCUMENTATION,
|
|
227
|
+
/** Drops this connection's session id only; the cloud session is left to idle out, as in the Playwright path. */
|
|
228
|
+
disconnect: async () => undefined,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
export async function connectBrowser(deps, options = {}) {
|
|
232
|
+
const { PRAXIS_API: api, PRAXIS_RUN_TOKEN: token, PRAXIS_AGENT_ID: agentId, PRAXIS_SESSION_ID: sessionId } = deps.env;
|
|
233
|
+
const missing = ['PRAXIS_API', 'PRAXIS_RUN_TOKEN', 'PRAXIS_AGENT_ID', 'PRAXIS_SESSION_ID'].filter(name => !deps.env[name]);
|
|
234
|
+
if (missing.length || !api || !token || !agentId || !sessionId) {
|
|
235
|
+
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.`);
|
|
236
|
+
}
|
|
237
|
+
const home = deps.env.HOME ?? '/home/user';
|
|
238
|
+
const now = deps.now ?? Date.now;
|
|
239
|
+
const driver = decideBrowserDriver({ override: deps.env.PRAXIS_BROWSER_DRIVER, childProcessAvailable: hasChildProcess(deps) });
|
|
240
|
+
const context = options.context === false ? undefined : await ensureContext(deps, agentId);
|
|
241
|
+
const name = browserSessionName({ agentId, sessionId, withContext: context !== undefined });
|
|
242
|
+
// The light machine drives the browser the service already runs; it never asks to be upgraded.
|
|
243
|
+
if (driver === 'actions')
|
|
244
|
+
return await connectActions(deps, { api, token, name, sessionId, agentId, home, context, now });
|
|
245
|
+
const playwright = await loadPlaywright(deps, home);
|
|
246
|
+
const url = buildConnectUrl({ api, name, context, idleMs: IDLE_MS, labels: { agent_session: sessionId, agent: agentId } });
|
|
247
|
+
let browser;
|
|
248
|
+
try {
|
|
249
|
+
browser = await playwright.chromium.connectOverCDP(url, { headers: { Authorization: `Bearer ${token}` }, timeout: 60_000 });
|
|
250
|
+
}
|
|
251
|
+
catch (cause) {
|
|
252
|
+
// A refusal that named itself travels as itself (ADR-024: a locked context is 409 CONTEXT_LOCKED, not a 503);
|
|
253
|
+
// only a real 503, or a failure with no status to read, is the outage it looks like (ticket-834, ticket-3252).
|
|
254
|
+
const refusal = classifyConnectRefusal(cause instanceof Error ? cause.message : String(cause));
|
|
255
|
+
throw new PraxisError({ status: refusal.status, code: refusal.code, message: refusal.message, raw: refusal.raw });
|
|
256
|
+
}
|
|
257
|
+
const fs = node(deps, 'node:fs');
|
|
258
|
+
const pages = () => browser.contexts().flatMap((c) => c.pages());
|
|
259
|
+
const ids = new WeakMap();
|
|
260
|
+
/** One browser-level CDP session for the connection: `Target.getTargets` answers for every tab in one round trip. */
|
|
261
|
+
let cdp;
|
|
262
|
+
const browserSession = async () => {
|
|
263
|
+
if (!browser.newBrowserCDPSession)
|
|
264
|
+
return undefined; // older playwright-core: every page keeps the per-page lookup
|
|
265
|
+
if (!cdp) {
|
|
266
|
+
try {
|
|
267
|
+
cdp = await browser.newBrowserCDPSession();
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
return undefined;
|
|
271
|
+
} // a browser that refuses the session lists tabs the old way, it does not fail
|
|
272
|
+
}
|
|
273
|
+
return cdp;
|
|
274
|
+
};
|
|
275
|
+
/** CDP's page targets, or nothing when the browser session is unavailable — never a thrown listing. */
|
|
276
|
+
const pageTargets = async () => {
|
|
277
|
+
const session = await browserSession();
|
|
278
|
+
if (!session)
|
|
279
|
+
return undefined;
|
|
280
|
+
try {
|
|
281
|
+
return ((await session.send('Target.getTargets'))?.targetInfos ?? []);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
const idOf = async (page) => {
|
|
288
|
+
const known = ids.get(page);
|
|
289
|
+
if (known)
|
|
290
|
+
return known;
|
|
291
|
+
const session = await page.context().newCDPSession(page);
|
|
292
|
+
try {
|
|
293
|
+
const info = await session.send('Target.getTargetInfo');
|
|
294
|
+
ids.set(page, info.targetInfo.targetId);
|
|
295
|
+
return info.targetInfo.targetId;
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
await session.detach().catch(() => { });
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
/**
|
|
302
|
+
* Every page with its target id: the one `Target.getTargets` covers the pages it names unambiguously, and only
|
|
303
|
+
* the rest (another tab on the same url, a page it does not name) pay for their own `Target.getTargetInfo`.
|
|
304
|
+
* Matching itself makes no request, so `get` reads the map for free and only a miss asks the page again.
|
|
305
|
+
*/
|
|
306
|
+
const observed = async () => {
|
|
307
|
+
const all = pages();
|
|
308
|
+
const urls = all.map(page => page.url());
|
|
309
|
+
const targets = await pageTargets();
|
|
310
|
+
const { matched } = matchTargetsToPages(targets ?? [], urls);
|
|
311
|
+
return all.map((page, index) => {
|
|
312
|
+
const target = matched.get(index);
|
|
313
|
+
if (target)
|
|
314
|
+
ids.set(page, target.targetId);
|
|
315
|
+
return { page, id: target?.targetId, url: target?.url ?? urls[index] ?? '', title: target?.title };
|
|
316
|
+
});
|
|
317
|
+
};
|
|
318
|
+
/** A page's target id, from the map when it named it or from its own CDP session otherwise. */
|
|
319
|
+
const idOfObserved = async (tab) => tab.id ?? await bounded(idOf(tab.page), 2000).catch(() => '');
|
|
320
|
+
const wrap = async (page) => {
|
|
321
|
+
const id = await idOf(page);
|
|
322
|
+
return {
|
|
323
|
+
id, playwright: page,
|
|
324
|
+
goto: async (target) => { await page.goto(target, { waitUntil: 'domcontentloaded' }); },
|
|
325
|
+
back: async () => { await page.goBack({ waitUntil: 'domcontentloaded' }); },
|
|
326
|
+
forward: async () => { await page.goForward({ waitUntil: 'domcontentloaded' }); },
|
|
327
|
+
reload: async () => { await page.reload({ waitUntil: 'domcontentloaded' }); },
|
|
328
|
+
close: async () => { await page.close(); },
|
|
329
|
+
url: async () => page.url(),
|
|
330
|
+
title: async () => page.title(),
|
|
331
|
+
snapshot: async () => page.ariaSnapshot({ mode: 'ai' }),
|
|
332
|
+
// `aria-ref=` is Playwright's own spelling of a snapshot ref, so the two drivers act on the same handle.
|
|
333
|
+
click: async (ref) => { await page.locator(`aria-ref=${ref}`).click(); },
|
|
334
|
+
fill: async (ref, text) => { await page.locator(`aria-ref=${ref}`).fill(text); },
|
|
335
|
+
// Playwright's own locator.selectOption takes exactly these matchers, and answers the values it selected.
|
|
336
|
+
selectOption: async (ref, values) => await page.locator(`aria-ref=${ref}`).selectOption(values),
|
|
337
|
+
press: async (key) => { await page.keyboard.press(key); },
|
|
338
|
+
scroll: async (direction, pixels) => { await page.mouse.wheel(0, direction === 'down' ? pixels ?? SCROLL_PIXELS_DEFAULT : -(pixels ?? SCROLL_PIXELS_DEFAULT)); },
|
|
339
|
+
evaluate: async (expression) => await page.evaluate(expression),
|
|
340
|
+
screenshot: async (shot) => {
|
|
341
|
+
const dir = `${home}/.praxis/screenshots`;
|
|
342
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
343
|
+
const path = `${dir}/${now()}-${id.slice(0, 8)}.png`;
|
|
344
|
+
fs.writeFileSync(path, await page.screenshot({ type: 'png', fullPage: shot?.fullPage === true }));
|
|
345
|
+
return { path, hint: 'View this PNG with the Read tool.' };
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
};
|
|
349
|
+
const list = async () => Promise.all((await observed()).map(async (tab) => ({
|
|
350
|
+
id: await idOfObserved(tab), url: tab.url,
|
|
351
|
+
// A matched target already carries the title; an unmapped page keeps asking its own page, as before.
|
|
352
|
+
title: tab.title ?? await bounded(tab.page.title(), 2000).catch(() => ''),
|
|
353
|
+
active: await bounded(tab.page.evaluate(() => document.visibilityState === 'visible'), 2000).catch(() => false),
|
|
354
|
+
})));
|
|
355
|
+
const get = async (id) => {
|
|
356
|
+
const tabId = requireTabId('tabs.get', id);
|
|
357
|
+
for (const tab of await observed()) {
|
|
358
|
+
const known = await idOfObserved(tab);
|
|
359
|
+
if (known === tabId && known) {
|
|
360
|
+
await tab.page.bringToFront().catch(() => { });
|
|
361
|
+
return wrap(tab.page);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
throw new PraxisError({ status: 404, code: 'TAB_NOT_FOUND', message: `No tab with id ${tabId}; call browser.tabs.list() for the current tabs.` });
|
|
365
|
+
};
|
|
366
|
+
const create = async () => {
|
|
367
|
+
const owner = browser.contexts()[0];
|
|
368
|
+
if (!owner)
|
|
369
|
+
throw unavailable('The cloud browser has no browser context to open a tab in.');
|
|
370
|
+
return wrap(await owner.newPage());
|
|
371
|
+
};
|
|
372
|
+
return {
|
|
373
|
+
tabs: { list, get, new: create },
|
|
374
|
+
open: async (target, openOptions) => {
|
|
375
|
+
if (openOptions?.reuseTab !== false) {
|
|
376
|
+
const reuse = decideTabReuse(target, await list());
|
|
377
|
+
if (reuse) {
|
|
378
|
+
const tab = await get(reuse.id);
|
|
379
|
+
await tab.goto(target);
|
|
380
|
+
return tab;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
const tab = await create();
|
|
384
|
+
await tab.goto(target);
|
|
385
|
+
return tab;
|
|
386
|
+
},
|
|
387
|
+
documentation: () => BROWSER_DOCUMENTATION,
|
|
388
|
+
/** Drops this connection only; the cloud session and its tabs stay until it idles out. */
|
|
389
|
+
disconnect: async () => {
|
|
390
|
+
// browser.close() drops the whole CDP connection, the browser-level session with it; detaching
|
|
391
|
+
// it first only added one more cross-region round trip (+0.6–0.8 s on the #829 LAB).
|
|
392
|
+
cdp = undefined;
|
|
393
|
+
await browser.close();
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Pure decisions behind `praxis.browser.connect()`: total functions, no I/O, no mocks needed to test them. */
|
|
2
|
+
export interface BrowserTabInfo {
|
|
3
|
+
id: string;
|
|
4
|
+
url: string;
|
|
5
|
+
title: string;
|
|
6
|
+
active: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** 0 same page, 1 same path, 2 same hostname, 3 parent/child domain, undefined unrelated. */
|
|
9
|
+
export declare function urlMatchRank(target: URL, candidate: URL): number | undefined;
|
|
10
|
+
/** Highest rank (inclusive, counted from 0 = best) at which an open tab is navigated in place instead of a new tab opened. */
|
|
11
|
+
export declare const TAB_REUSE_MAX_RANK = 2;
|
|
12
|
+
/**
|
|
13
|
+
* Which open tab `open(url)` navigates in place: the best-ranked tab of the same hostname or closer.
|
|
14
|
+
* A parent/child domain (rank 3) may be a different site and is never reused. At equal rank the active tab wins,
|
|
15
|
+
* otherwise the later (newer) one in the list.
|
|
16
|
+
*/
|
|
17
|
+
export declare function decideTabReuse<T extends {
|
|
18
|
+
url: string;
|
|
19
|
+
active: boolean;
|
|
20
|
+
}>(targetUrl: string, tabs: readonly T[]): T | undefined;
|
|
21
|
+
export interface ConnectUrlParts {
|
|
22
|
+
/** Public API origin (PRAXIS_API), http(s). */
|
|
23
|
+
api: string;
|
|
24
|
+
/** Cloud session name: attaches to the live session with this name or opens one. */
|
|
25
|
+
name: string;
|
|
26
|
+
/** Browser context id (bsc_…) carrying saved sign-ins; omitted without one. */
|
|
27
|
+
context?: string;
|
|
28
|
+
/** Milliseconds after the last client disconnects before the cloud session is released. */
|
|
29
|
+
idleMs: number;
|
|
30
|
+
labels: Record<string, string>;
|
|
31
|
+
}
|
|
32
|
+
/** The `/browser/v1/connect` WebSocket URL. The token travels in a header, never in this URL. */
|
|
33
|
+
export declare function buildConnectUrl(parts: ConnectUrlParts): string;
|
|
34
|
+
export interface ContextLike {
|
|
35
|
+
id: string;
|
|
36
|
+
createdAt?: string;
|
|
37
|
+
labels?: Record<string, string>;
|
|
38
|
+
}
|
|
39
|
+
/** The context that belongs to this agent: label `agent` equals its id. With several, the oldest wins so every run agrees. */
|
|
40
|
+
export declare function pickAgentContext<T extends ContextLike>(contexts: readonly T[], agentId: string): T | undefined;
|
|
41
|
+
/** Context names accept ASCII letters, digits and . _ : - only. */
|
|
42
|
+
export declare const agentContextName: (agentId: string) => string;
|
|
43
|
+
/**
|
|
44
|
+
* #3325: the cloud browser belongs to the agent, not to one session. An agent has exactly one saved-sign-in
|
|
45
|
+
* Context and a Context has one writer, so naming the browser after the session made every new session of the
|
|
46
|
+
* same agent (each stateless assume-MCP call is one) open a second browser that superseded the first: the open
|
|
47
|
+
* tabs and a half-done sign-in were gone between two calls. Named after the agent, every session and every call
|
|
48
|
+
* attaches to the one live browser by name. A connect without the Context (`context: false`) keeps the session
|
|
49
|
+
* name: it shares nothing, so it must not attach to the agent's signed-in browser.
|
|
50
|
+
*/
|
|
51
|
+
export declare function browserSessionName(input: {
|
|
52
|
+
agentId: string;
|
|
53
|
+
sessionId: string;
|
|
54
|
+
withContext: boolean;
|
|
55
|
+
}): string;
|
|
56
|
+
/** Start pages are expendable only on Console hosts, never arbitrary sites' /start pages. */
|
|
57
|
+
export declare function isBlankTab(value: string): boolean;
|
|
58
|
+
/** One entry of a browser-level `Target.getTargets` answer, kept structural. */
|
|
59
|
+
export interface CdpPageTarget {
|
|
60
|
+
targetId: string;
|
|
61
|
+
type?: string;
|
|
62
|
+
url: string;
|
|
63
|
+
title?: string;
|
|
64
|
+
}
|
|
65
|
+
export interface TargetMatch<T extends CdpPageTarget> {
|
|
66
|
+
/** Page index → its CDP target, for every page a single target names unambiguously. */
|
|
67
|
+
matched: Map<number, T>;
|
|
68
|
+
/** Page indexes that still need their own `Target.getTargetInfo`: no target, or a url shared by several tabs. */
|
|
69
|
+
unmatched: number[];
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Matches the browser's page targets (a raw `Target.getTargets` answer) to the pages Playwright holds, by url.
|
|
73
|
+
* Non-page targets name no tab. A url naming more than one target, or more than one page, identifies nothing:
|
|
74
|
+
* both sides fall back to the per-page lookup, because a wrong tab id is worse than one extra round trip.
|
|
75
|
+
*/
|
|
76
|
+
export declare function matchTargetsToPages<T extends CdpPageTarget>(targets: readonly T[], pageUrls: readonly string[]): TargetMatch<T>;
|
|
77
|
+
/**
|
|
78
|
+
* The context a name-filtered lookup returned for this agent, or nothing when the entry is not it.
|
|
79
|
+
* An old server ignores `name` and answers with unrelated rows; adopting one of those would hand this run
|
|
80
|
+
* another agent's stored sign-ins.
|
|
81
|
+
*/
|
|
82
|
+
export declare function pickContextByName<T extends ContextLike & {
|
|
83
|
+
name?: unknown;
|
|
84
|
+
}>(contexts: readonly T[], agentId: string): T | undefined;
|
|
85
|
+
/** A context name is unique per account, so a create that loses a race answers INVALID_PARAMS with this phrase. */
|
|
86
|
+
export declare function isDuplicateNameError(error: unknown): boolean;
|
|
87
|
+
/** How this run drives the cloud browser: Playwright over CDP, or the service's own page actions over HTTP. */
|
|
88
|
+
export type BrowserDriver = "playwright" | "actions";
|
|
89
|
+
export interface BrowserDriverInput {
|
|
90
|
+
/** `PRAXIS_BROWSER_DRIVER`; anything other than `actions` / `playwright` is not an instruction. */
|
|
91
|
+
readonly override?: string;
|
|
92
|
+
/** Whether this runtime can load `node:child_process` — the one thing the actions driver does not need. */
|
|
93
|
+
readonly childProcessAvailable: boolean;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Which driver `praxis.browser.connect()` uses. The explicit override wins, so a full machine can exercise the
|
|
97
|
+
* actions path and a light machine can be told to try Playwright anyway. Without one, a runtime that cannot load
|
|
98
|
+
* `node:child_process` — the light machine, where installing playwright-core is impossible — drives the browser
|
|
99
|
+
* through the service's page actions instead of asking for an upgrade; everything else keeps Playwright.
|
|
100
|
+
*/
|
|
101
|
+
export declare function decideBrowserDriver(input: BrowserDriverInput): BrowserDriver;
|