@deepraxis/sdk 0.1.1-dev.78b913a → 0.1.1-dev.7b4567f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ import type { PublishInput } from './application-publish.js';
2
+ /** A vite/vinext build read into memory: paths are relative to dist/server and dist/client. */
3
+ export interface BuildOutput {
4
+ serverFiles: Record<string, Uint8Array>;
5
+ clientFiles: Record<string, Uint8Array>;
6
+ /** Parsed dist/server/wrangler.json. */
7
+ wranglerJson: unknown;
8
+ }
9
+ /** Pure mapping from a vite/vinext build (dist/server + dist/client + wrangler.json) to `praxis.application.publish` input. No fs, no network. */
10
+ export declare function publishInputFromBuild(build: BuildOutput, name: string): PublishInput;
@@ -0,0 +1,98 @@
1
+ import { PraxisError } from "../core/errors.js";
2
+ // wrangler.json keys that declare a binding the platform does not accept (it answers UNSUPPORTED).
3
+ const UNSUPPORTED_BINDING_KEYS = ['services', 'queues', 'durable_objects', 'ai', 'analytics_engine_datasets', 'vectorize', 'hyperdrive',
4
+ 'browser', 'send_email', 'mtls_certificates', 'dispatch_namespaces', 'unsafe', 'version_metadata', 'images', 'workflows', 'pipelines',
5
+ 'secrets_store_secrets', 'ratelimits', 'vpc_services', 'media', 'tail_consumers', 'worker_loaders'];
6
+ // A key declares something only if it holds a value somewhere inside: vite's generated wrangler.json writes
7
+ // empty containers such as `queues: { producers: [], consumers: [] }` and `durable_objects: { bindings: [] }`.
8
+ const isPresent = (value) => {
9
+ if (value === undefined || value === null)
10
+ return false;
11
+ if (Array.isArray(value))
12
+ return value.some(isPresent);
13
+ if (typeof value === 'object')
14
+ return Object.values(value).some(isPresent);
15
+ return true;
16
+ };
17
+ /** Compile one .assetsignore line (gitignore subset: names, `*`, `**`, leading /, trailing /) to a matcher over a relative path. */
18
+ function ignoreMatcher(line) {
19
+ let pattern = line.trim();
20
+ if (!pattern || pattern.startsWith('#') || pattern.startsWith('!'))
21
+ return null;
22
+ const anchored = pattern.startsWith('/') || pattern.slice(0, -1).includes('/');
23
+ pattern = pattern.replace(/^\//, '').replace(/\/$/, '');
24
+ const source = pattern.split('**').map(part => part.split('*').map(piece => piece.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')).join('.*');
25
+ const regex = new RegExp(`^${source}$`);
26
+ return path => {
27
+ const segments = path.split('/');
28
+ // The path or any of its parent directories matches, as in gitignore.
29
+ for (let end = 1; end <= segments.length; end++) {
30
+ if (anchored ? regex.test(segments.slice(0, end).join('/')) : regex.test(segments[end - 1]))
31
+ return true;
32
+ }
33
+ return false;
34
+ };
35
+ }
36
+ function bindingsFrom(wrangler) {
37
+ const bindings = [];
38
+ const fromList = (key, type) => {
39
+ const list = wrangler[key];
40
+ if (!isPresent(list))
41
+ return;
42
+ if (!Array.isArray(list))
43
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `wrangler.json ${key} must be an array` });
44
+ for (const entry of list) {
45
+ if (typeof entry?.binding !== 'string')
46
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `wrangler.json ${key} entry has no binding name` });
47
+ bindings.push({ type, name: entry.binding });
48
+ }
49
+ };
50
+ fromList('d1_databases', 'd1');
51
+ fromList('kv_namespaces', 'kv_namespace');
52
+ fromList('r2_buckets', 'r2_bucket');
53
+ for (const [name, value] of Object.entries((wrangler.vars ?? {}))) {
54
+ bindings.push((typeof value === 'string' ? { type: 'plain_text', name, text: value } : { type: 'json', name, json: value }));
55
+ }
56
+ if (typeof wrangler.assets?.binding === 'string')
57
+ bindings.push({ type: 'assets', name: wrangler.assets.binding });
58
+ return bindings;
59
+ }
60
+ /** Pure mapping from a vite/vinext build (dist/server + dist/client + wrangler.json) to `praxis.application.publish` input. No fs, no network. */
61
+ export function publishInputFromBuild(build, name) {
62
+ const wrangler = build.wranglerJson;
63
+ if (!wrangler || typeof wrangler !== 'object' || Array.isArray(wrangler)) {
64
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: 'wranglerJson must be the parsed dist/server/wrangler.json object' });
65
+ }
66
+ const offending = UNSUPPORTED_BINDING_KEYS.filter(key => isPresent(wrangler[key]));
67
+ if (offending.length) {
68
+ throw new PraxisError({ code: 'UNSUPPORTED', message: `wrangler.json declares bindings the platform does not support: ${offending.join(', ')}` });
69
+ }
70
+ const modules = Object.entries(build.serverFiles)
71
+ .filter(([path]) => path.endsWith('.js'))
72
+ .map(([path, content]) => ({ name: path, content, content_type: 'application/javascript+module' }));
73
+ if (typeof wrangler.main !== 'string')
74
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: 'wrangler.json has no main entry' });
75
+ if (!modules.some(module => module.name === wrangler.main)) {
76
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `wrangler.json main ${wrangler.main} is not a .js file under dist/server` });
77
+ }
78
+ const ignored = new TextDecoder().decode(build.clientFiles['.assetsignore'] ?? new Uint8Array()).split(/\r?\n/)
79
+ .map(ignoreMatcher).filter((matcher) => matcher !== null);
80
+ const files = {};
81
+ for (const [path, content] of Object.entries(build.clientFiles)) {
82
+ if (path === '.assetsignore' || ignored.some(matches => matches(path)))
83
+ continue;
84
+ files[`/${path}`] = content;
85
+ }
86
+ const { binding: _binding, directory: _directory, ...assetsConfig } = (wrangler.assets ?? {});
87
+ const bindings = bindingsFrom(wrangler);
88
+ return {
89
+ name,
90
+ files,
91
+ modules,
92
+ main_module: wrangler.main,
93
+ ...(typeof wrangler.compatibility_date === 'string' ? { compatibility_date: wrangler.compatibility_date } : {}),
94
+ ...(Array.isArray(wrangler.compatibility_flags) ? { compatibility_flags: wrangler.compatibility_flags } : {}),
95
+ ...(bindings.length ? { bindings } : {}),
96
+ ...(Object.keys(assetsConfig).length ? { assets_config: assetsConfig } : {}),
97
+ };
98
+ }
@@ -12,6 +12,14 @@ export interface PublishInput {
12
12
  content: string;
13
13
  content_type?: string;
14
14
  };
15
+ /** Multi-module Worker (e.g. a vite/vinext build). Names pass through unchanged; relative paths with / are legal. Mutually exclusive with main. */
16
+ modules?: {
17
+ name: string;
18
+ content: string | Uint8Array;
19
+ content_type?: string;
20
+ }[];
21
+ /** Entry module name; defaults to the first module and must name one of modules. */
22
+ main_module?: string;
15
23
  /** 运行时兼容日期,默认当天 UTC(YYYY-MM-DD)。 */
16
24
  compatibility_date?: string;
17
25
  /** 运行时兼容标志,原样传递;平台固定附加 global_fetch_strictly_public。 */
@@ -21,11 +21,30 @@ export async function publish(client, input) {
21
21
  const timeout = input.timeout_ms ?? 120_000;
22
22
  if (!Number.isFinite(timeout) || timeout < 0)
23
23
  throw new RangeError('timeout_ms must be non-negative and finite');
24
- const contentType = ['application/javascript+module', 'text/javascript', 'application/javascript', 'application/json',
25
- 'text/plain', 'application/wasm', 'application/octet-stream', 'application/x-python']
26
- .find(type => type === (input.main?.content_type ?? 'application/javascript+module'));
27
- if (!contentType)
28
- throw new PraxisError({ code: 'INVALID_PARAMS', message: `Unsupported module content_type: ${input.main?.content_type}` });
24
+ const moduleTypes = ['application/javascript+module', 'text/javascript', 'application/javascript', 'application/json',
25
+ 'text/plain', 'application/wasm', 'application/octet-stream', 'application/x-python'];
26
+ const moduleType = (type) => {
27
+ const found = moduleTypes.find(candidate => candidate === (type ?? 'application/javascript+module'));
28
+ if (!found)
29
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `Unsupported module content_type: ${type}` });
30
+ return found;
31
+ };
32
+ if (input.main && input.modules)
33
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: 'Pass either main or modules, not both' });
34
+ if (input.main_module !== undefined && !input.modules)
35
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: 'main_module requires modules; with main the entry is main.name' });
36
+ if (input.modules && input.modules.length === 0)
37
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: 'modules must not be empty' });
38
+ const entryModules = input.main
39
+ ? [{ name: input.main.name, content_type: moduleType(input.main.content_type), content_base64: base64(new TextEncoder().encode(input.main.content)) }]
40
+ : input.modules?.map(module => ({ name: module.name, content_type: moduleType(module.content_type),
41
+ content_base64: base64(typeof module.content === 'string' ? new TextEncoder().encode(module.content) : module.content) }));
42
+ if (new Set(entryModules?.map(module => module.name)).size !== (entryModules?.length ?? 0))
43
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: 'Duplicate module name' });
44
+ const mainModule = input.main ? input.main.name : input.modules ? (input.main_module ?? input.modules[0].name) : undefined;
45
+ if (input.modules && !input.modules.some(module => module.name === mainModule)) {
46
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `main_module ${mainModule} is not among modules` });
47
+ }
29
48
  const files = Object.entries(input.files);
30
49
  if (files.length > 100_000)
31
50
  throw new PraxisError({ code: 'LIMIT_EXCEEDED', message: 'At most 100000 asset paths can be published' });
@@ -80,7 +99,7 @@ export async function publish(client, input) {
80
99
  const removed = Object.keys(previous).filter(key => !Object.hasOwn(manifest, key));
81
100
  const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(manifest))));
82
101
  const manifestHash = Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');
83
- const staticOnly = !['main', 'bindings', 'compatibility_date', 'compatibility_flags', 'assets_config'].some(key => Object.hasOwn(input, key));
102
+ const staticOnly = !['main', 'modules', 'main_module', 'bindings', 'compatibility_date', 'compatibility_flags', 'assets_config'].some(key => Object.hasOwn(input, key));
84
103
  const unchanged = staticOnly && !!currentVersion && manifestHash === currentVersion.praxis.assets_manifest?.manifest_hash;
85
104
  const hashes = new Set(Object.values(manifest).map(entry => entry.hash));
86
105
  const currentResult = { url: worker.subdomain.url, worker_id: worker.id, version_id: currentVersion?.id ?? null,
@@ -127,9 +146,7 @@ export async function publish(client, input) {
127
146
  assets: versionAssets,
128
147
  ...(input.compatibility_flags ? { compatibility_flags: input.compatibility_flags } : {}),
129
148
  ...(input.bindings ? { bindings: input.bindings } : {}),
130
- ...(input.main ? { main_module: input.main.name, modules: [{ name: input.main.name,
131
- content_type: contentType,
132
- content_base64: base64(new TextEncoder().encode(input.main.content)) }] } : {}),
149
+ ...(entryModules ? { main_module: mainModule, modules: entryModules } : {}),
133
150
  } });
134
151
  let deployment = result.deployment;
135
152
  if (!deployment)
@@ -0,0 +1,90 @@
1
+ import { PraxisError } from '../core/errors.js';
2
+ import { type BrowserTabInfo, type ContextLike } from './browser-decisions.js';
3
+ /** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
4
+ export declare const PLAYWRIGHT_CORE_VERSION = "1.63.0";
5
+ /** Playwright's Page, kept structural: the SDK does not depend on playwright-core. */
6
+ export type PlaywrightPage = any;
7
+ export interface BrowserTab {
8
+ readonly id: string;
9
+ /** The Playwright Page for locators and waits. */
10
+ readonly playwright: PlaywrightPage;
11
+ goto(url: string): Promise<void>;
12
+ back(): Promise<void>;
13
+ forward(): Promise<void>;
14
+ reload(): Promise<void>;
15
+ close(): Promise<void>;
16
+ url(): Promise<string>;
17
+ title(): Promise<string>;
18
+ /** The page as a Playwright ARIA snapshot with [ref=eN] marks. */
19
+ snapshot(): Promise<string>;
20
+ /** Writes a PNG under ~/.praxis/screenshots and returns its path; view it with the Read tool. */
21
+ screenshot(options?: {
22
+ fullPage?: boolean;
23
+ }): Promise<{
24
+ path: string;
25
+ hint: string;
26
+ }>;
27
+ }
28
+ export interface PraxisBrowser {
29
+ readonly tabs: {
30
+ list(): Promise<BrowserTabInfo[]>;
31
+ get(id: string): Promise<BrowserTab>;
32
+ 'new'(): Promise<BrowserTab>;
33
+ };
34
+ open(url: string, options?: {
35
+ reuseTab?: boolean;
36
+ }): Promise<BrowserTab>;
37
+ documentation(): string;
38
+ /** Drops this connection only; the cloud session and its tabs stay until it idles out. */
39
+ disconnect(): Promise<void>;
40
+ }
41
+ export interface BrowserConnectOptions {
42
+ /** false skips the agent's saved sign-in context. */
43
+ context?: false;
44
+ }
45
+ interface ContextsApi {
46
+ list(args?: {
47
+ query?: {
48
+ limit?: number;
49
+ cursor?: string;
50
+ name?: string;
51
+ };
52
+ }): Promise<{
53
+ data: (ContextLike & {
54
+ name?: unknown;
55
+ })[];
56
+ nextCursor: string | null;
57
+ }>;
58
+ create(args: {
59
+ body: {
60
+ name: string;
61
+ labels: Record<string, string>;
62
+ };
63
+ }): Promise<ContextLike>;
64
+ }
65
+ /** The playwright-core module shape the helper uses. */
66
+ export interface PlaywrightModule {
67
+ chromium: {
68
+ connectOverCDP(url: string, options: {
69
+ headers: Record<string, string>;
70
+ timeout?: number;
71
+ }): Promise<unknown>;
72
+ };
73
+ }
74
+ /** What connect() needs from the platform client and the process. All of it is injectable for tests. */
75
+ export interface BrowserConnectDeps {
76
+ contexts: ContextsApi;
77
+ env: Readonly<Record<string, string | undefined>>;
78
+ /** process.getBuiltinModule; undefined on runtimes without it. */
79
+ builtin: ((name: string) => unknown) | undefined;
80
+ now?: () => number;
81
+ /** An already-loaded playwright-core; the real loader finds or installs one and imports it. */
82
+ playwright?: PlaywrightModule;
83
+ }
84
+ export declare const unavailable: (message: string) => PraxisError;
85
+ /** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
86
+ export declare const needsFullMachine: () => Error & {
87
+ code: string;
88
+ };
89
+ export declare function connectBrowser(deps: BrowserConnectDeps, options?: BrowserConnectOptions): Promise<PraxisBrowser>;
90
+ export {};
@@ -0,0 +1,247 @@
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 { BROWSER_DOCUMENTATION } from "./browser-documentation.js";
11
+ import { agentContextName, buildConnectUrl, decideTabReuse, isDuplicateNameError, matchTargetsToPages, pickAgentContext, pickContextByName } from "./browser-decisions.js";
12
+ /** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
13
+ export const PLAYWRIGHT_CORE_VERSION = '1.63.0';
14
+ const GLOBAL_PLAYWRIGHT = '/usr/local/lib/node_modules/playwright-core';
15
+ const IDLE_MS = 300_000;
16
+ export const unavailable = (message) => new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message });
17
+ /** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
18
+ export const needsFullMachine = () => Object.assign(new Error('The cloud browser needs a full sandbox — upgrade this instance'), { code: 'PROGRAM_NEEDS_FULL_MACHINE' });
19
+ /** Reads a Node builtin; a light machine's isolate refuses child_process, which is the signal to upgrade. */
20
+ function node(deps, name) {
21
+ if (!deps.builtin)
22
+ throw unavailable('praxis.browser.connect() needs Node.js 22.3 or newer on the session machine.');
23
+ try {
24
+ const module = deps.builtin(name);
25
+ if (module)
26
+ return module;
27
+ }
28
+ catch (cause) {
29
+ if (cause?.code === 'PROGRAM_NEEDS_FULL_MACHINE')
30
+ throw cause;
31
+ throw needsFullMachine();
32
+ }
33
+ throw needsFullMachine();
34
+ }
35
+ async function loadPlaywright(deps, home) {
36
+ if (deps.playwright)
37
+ return deps.playwright;
38
+ node(deps, 'node:child_process'); // fails fast on a light machine, before any network work
39
+ const fs = node(deps, 'node:fs');
40
+ const entry = (root) => `${root}/index.mjs`;
41
+ const cache = `${home}/.cache/praxis-browser`;
42
+ const cached = `${cache}/node_modules/playwright-core`;
43
+ let root = [GLOBAL_PLAYWRIGHT, cached].find(candidate => fs.existsSync(entry(candidate)));
44
+ if (!root) {
45
+ fs.mkdirSync(cache, { recursive: true });
46
+ if (!fs.existsSync(`${cache}/package.json`))
47
+ fs.writeFileSync(`${cache}/package.json`, '{"private":true}');
48
+ const cp = node(deps, 'node:child_process');
49
+ 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()));
50
+ root = cached;
51
+ }
52
+ return await import(__rewriteRelativeImportExtension(/* @vite-ignore */ `file://${entry(root)}`));
53
+ }
54
+ /** The agent's own context, in one name-filtered request; the paged scan is only the pre-`name` server fallback. */
55
+ async function ensureContext(deps, agentId) {
56
+ const name = agentContextName(agentId);
57
+ const byNameQuery = () => deps.contexts.list({ query: { name, limit: 1 } });
58
+ // A server that knows `name` answers with this agent's context or nothing; a non-empty answer of other rows means
59
+ // it ignored the filter, and only then is the paged scan worth its round trips.
60
+ const paged = async () => {
61
+ const seen = [];
62
+ let cursor;
63
+ for (let page = 0; page < 20; page++) {
64
+ const result = await deps.contexts.list({ query: { limit: 100, ...(cursor ? { cursor } : {}) } });
65
+ seen.push(...result.data);
66
+ const own = pickAgentContext(seen, agentId);
67
+ if (own)
68
+ return own.id;
69
+ if (!result.nextCursor)
70
+ break;
71
+ cursor = result.nextCursor;
72
+ }
73
+ return undefined;
74
+ };
75
+ const find = async () => {
76
+ const answer = (await byNameQuery()).data;
77
+ const byName = pickContextByName(answer, agentId);
78
+ if (byName)
79
+ return byName.id;
80
+ return answer.length > 0 ? paged() : undefined;
81
+ };
82
+ const existing = await find();
83
+ if (existing)
84
+ return existing;
85
+ try {
86
+ return (await deps.contexts.create({ body: { name, labels: { agent: agentId } } })).id;
87
+ }
88
+ catch (cause) {
89
+ // Names are unique per account, so this is a concurrent run winning the create: reuse what it made.
90
+ if (!isDuplicateNameError(cause))
91
+ throw cause;
92
+ const raced = await find();
93
+ if (raced)
94
+ return raced;
95
+ throw cause;
96
+ }
97
+ }
98
+ const bounded = (work, ms) => Promise.race([work, new Promise((_, reject) => setTimeout(() => reject(new Error('timed out')), ms))]);
99
+ export async function connectBrowser(deps, options = {}) {
100
+ const { PRAXIS_API: api, PRAXIS_RUN_TOKEN: token, PRAXIS_AGENT_ID: agentId, PRAXIS_SESSION_ID: sessionId } = deps.env;
101
+ const missing = ['PRAXIS_API', 'PRAXIS_RUN_TOKEN', 'PRAXIS_AGENT_ID', 'PRAXIS_SESSION_ID'].filter(name => !deps.env[name]);
102
+ if (missing.length || !api || !token || !agentId || !sessionId) {
103
+ 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
+ }
105
+ const home = deps.env.HOME ?? '/home/user';
106
+ const playwright = await loadPlaywright(deps, home);
107
+ const context = options.context === false ? undefined : await ensureContext(deps, agentId);
108
+ const url = buildConnectUrl({ api, name: sessionId, context, idleMs: IDLE_MS, labels: { agent_session: sessionId, agent: agentId } });
109
+ let browser;
110
+ try {
111
+ browser = await playwright.chromium.connectOverCDP(url, { headers: { Authorization: `Bearer ${token}` }, timeout: 60_000 });
112
+ }
113
+ catch (cause) {
114
+ throw unavailable(`Connecting to the cloud browser failed: ${cause.message.split('\n')[0]}`);
115
+ }
116
+ const fs = node(deps, 'node:fs');
117
+ const now = deps.now ?? Date.now;
118
+ const pages = () => browser.contexts().flatMap((c) => c.pages());
119
+ const ids = new WeakMap();
120
+ /** One browser-level CDP session for the connection: `Target.getTargets` answers for every tab in one round trip. */
121
+ let cdp;
122
+ const browserSession = async () => {
123
+ if (!browser.newBrowserCDPSession)
124
+ return undefined; // older playwright-core: every page keeps the per-page lookup
125
+ if (!cdp) {
126
+ try {
127
+ cdp = await browser.newBrowserCDPSession();
128
+ }
129
+ catch {
130
+ return undefined;
131
+ } // a browser that refuses the session lists tabs the old way, it does not fail
132
+ }
133
+ return cdp;
134
+ };
135
+ /** CDP's page targets, or nothing when the browser session is unavailable — never a thrown listing. */
136
+ const pageTargets = async () => {
137
+ const session = await browserSession();
138
+ if (!session)
139
+ return undefined;
140
+ try {
141
+ return ((await session.send('Target.getTargets'))?.targetInfos ?? []);
142
+ }
143
+ catch {
144
+ return undefined;
145
+ }
146
+ };
147
+ const idOf = async (page) => {
148
+ const known = ids.get(page);
149
+ if (known)
150
+ return known;
151
+ const session = await page.context().newCDPSession(page);
152
+ try {
153
+ const info = await session.send('Target.getTargetInfo');
154
+ ids.set(page, info.targetInfo.targetId);
155
+ return info.targetInfo.targetId;
156
+ }
157
+ finally {
158
+ await session.detach().catch(() => { });
159
+ }
160
+ };
161
+ /**
162
+ * Every page with its target id: the one `Target.getTargets` covers the pages it names unambiguously, and only
163
+ * the rest (another tab on the same url, a page it does not name) pay for their own `Target.getTargetInfo`.
164
+ * Matching itself makes no request, so `get` reads the map for free and only a miss asks the page again.
165
+ */
166
+ const observed = async () => {
167
+ const all = pages();
168
+ const urls = all.map(page => page.url());
169
+ const targets = await pageTargets();
170
+ const { matched } = matchTargetsToPages(targets ?? [], urls);
171
+ return all.map((page, index) => {
172
+ const target = matched.get(index);
173
+ if (target)
174
+ ids.set(page, target.targetId);
175
+ return { page, id: target?.targetId, url: target?.url ?? urls[index] ?? '', title: target?.title };
176
+ });
177
+ };
178
+ /** A page's target id, from the map when it named it or from its own CDP session otherwise. */
179
+ const idOfObserved = async (tab) => tab.id ?? await bounded(idOf(tab.page), 2000).catch(() => '');
180
+ const wrap = async (page) => {
181
+ const id = await idOf(page);
182
+ return {
183
+ id, playwright: page,
184
+ goto: async (target) => { await page.goto(target, { waitUntil: 'domcontentloaded' }); },
185
+ back: async () => { await page.goBack({ waitUntil: 'domcontentloaded' }); },
186
+ forward: async () => { await page.goForward({ waitUntil: 'domcontentloaded' }); },
187
+ reload: async () => { await page.reload({ waitUntil: 'domcontentloaded' }); },
188
+ close: async () => { await page.close(); },
189
+ url: async () => page.url(),
190
+ title: async () => page.title(),
191
+ snapshot: async () => page.ariaSnapshot({ mode: 'ai' }),
192
+ screenshot: async (shot) => {
193
+ const dir = `${home}/.praxis/screenshots`;
194
+ fs.mkdirSync(dir, { recursive: true });
195
+ const path = `${dir}/${now()}-${id.slice(0, 8)}.png`;
196
+ fs.writeFileSync(path, await page.screenshot({ type: 'png', fullPage: shot?.fullPage === true }));
197
+ return { path, hint: 'View this PNG with the Read tool.' };
198
+ },
199
+ };
200
+ };
201
+ const list = async () => Promise.all((await observed()).map(async (tab) => ({
202
+ id: await idOfObserved(tab), url: tab.url,
203
+ // A matched target already carries the title; an unmapped page keeps asking its own page, as before.
204
+ title: tab.title ?? await bounded(tab.page.title(), 2000).catch(() => ''),
205
+ active: await bounded(tab.page.evaluate(() => document.visibilityState === 'visible'), 2000).catch(() => false),
206
+ })));
207
+ const get = async (id) => {
208
+ for (const tab of await observed()) {
209
+ const known = await idOfObserved(tab);
210
+ if (known === id && known) {
211
+ await tab.page.bringToFront().catch(() => { });
212
+ return wrap(tab.page);
213
+ }
214
+ }
215
+ throw new PraxisError({ status: 404, code: 'TAB_NOT_FOUND', message: `No tab with id ${id}; call browser.tabs.list() for the current tabs.` });
216
+ };
217
+ const create = async () => {
218
+ const owner = browser.contexts()[0];
219
+ if (!owner)
220
+ throw unavailable('The cloud browser has no browser context to open a tab in.');
221
+ return wrap(await owner.newPage());
222
+ };
223
+ return {
224
+ tabs: { list, get, new: create },
225
+ open: async (target, openOptions) => {
226
+ if (openOptions?.reuseTab !== false) {
227
+ const reuse = decideTabReuse(target, await list());
228
+ if (reuse) {
229
+ const tab = await get(reuse.id);
230
+ await tab.goto(target);
231
+ return tab;
232
+ }
233
+ }
234
+ const tab = await create();
235
+ await tab.goto(target);
236
+ return tab;
237
+ },
238
+ documentation: () => BROWSER_DOCUMENTATION,
239
+ /** Drops this connection only; the cloud session and its tabs stay until it idles out. */
240
+ disconnect: async () => {
241
+ // browser.close() drops the whole CDP connection, the browser-level session with it; detaching
242
+ // it first only added one more cross-region round trip (+0.6–0.8 s on the #829 LAB).
243
+ cdp = undefined;
244
+ await browser.close();
245
+ },
246
+ };
247
+ }
@@ -0,0 +1,73 @@
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
+ /** Start pages are expendable only on Console hosts, never arbitrary sites' /start pages. */
44
+ export declare function isBlankTab(value: string): boolean;
45
+ /** One entry of a browser-level `Target.getTargets` answer, kept structural. */
46
+ export interface CdpPageTarget {
47
+ targetId: string;
48
+ type?: string;
49
+ url: string;
50
+ title?: string;
51
+ }
52
+ export interface TargetMatch<T extends CdpPageTarget> {
53
+ /** Page index → its CDP target, for every page a single target names unambiguously. */
54
+ matched: Map<number, T>;
55
+ /** Page indexes that still need their own `Target.getTargetInfo`: no target, or a url shared by several tabs. */
56
+ unmatched: number[];
57
+ }
58
+ /**
59
+ * Matches the browser's page targets (a raw `Target.getTargets` answer) to the pages Playwright holds, by url.
60
+ * Non-page targets name no tab. A url naming more than one target, or more than one page, identifies nothing:
61
+ * both sides fall back to the per-page lookup, because a wrong tab id is worse than one extra round trip.
62
+ */
63
+ export declare function matchTargetsToPages<T extends CdpPageTarget>(targets: readonly T[], pageUrls: readonly string[]): TargetMatch<T>;
64
+ /**
65
+ * The context a name-filtered lookup returned for this agent, or nothing when the entry is not it.
66
+ * An old server ignores `name` and answers with unrelated rows; adopting one of those would hand this run
67
+ * another agent's stored sign-ins.
68
+ */
69
+ export declare function pickContextByName<T extends ContextLike & {
70
+ name?: unknown;
71
+ }>(contexts: readonly T[], agentId: string): T | undefined;
72
+ /** A context name is unique per account, so a create that loses a race answers INVALID_PARAMS with this phrase. */
73
+ export declare function isDuplicateNameError(error: unknown): boolean;