@deepraxis/sdk 0.1.1 → 0.2.0-dev.05b5159

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.
Files changed (47) hide show
  1. package/METHODS.md +1994 -208
  2. package/README.md +10 -9
  3. package/dist/automation.d.ts +61 -0
  4. package/dist/core/binary-operations.d.ts +3 -0
  5. package/dist/core/binary-operations.js +14 -0
  6. package/dist/core/client.d.ts +11 -1
  7. package/dist/core/client.js +13 -0
  8. package/dist/core/credentials.d.ts +22 -3
  9. package/dist/core/credentials.js +44 -5
  10. package/dist/core/deprecation.d.ts +11 -0
  11. package/dist/core/deprecation.js +20 -0
  12. package/dist/core/errors.d.ts +6 -0
  13. package/dist/core/errors.js +8 -0
  14. package/dist/core/retry.js +2 -0
  15. package/dist/core/transport.d.ts +14 -1
  16. package/dist/core/transport.js +39 -9
  17. package/dist/generated/binary-operations.gen.d.ts +3 -0
  18. package/dist/generated/binary-operations.gen.js +14 -0
  19. package/dist/generated/index.d.ts +2 -2
  20. package/dist/generated/index.js +1 -1
  21. package/dist/generated/sdk.gen.d.ts +4473 -852
  22. package/dist/generated/sdk.gen.js +12608 -2319
  23. package/dist/generated/types.gen.d.ts +109137 -46892
  24. package/dist/helpers/application-build.d.ts +10 -0
  25. package/dist/helpers/application-build.js +98 -0
  26. package/dist/helpers/application-publish.d.ts +8 -0
  27. package/dist/helpers/application-publish.js +42 -11
  28. package/dist/helpers/browser-actions.d.ts +104 -0
  29. package/dist/helpers/browser-actions.js +150 -0
  30. package/dist/helpers/browser-connect-error.d.ts +34 -0
  31. package/dist/helpers/browser-connect-error.js +85 -0
  32. package/dist/helpers/browser-connect.d.ts +111 -0
  33. package/dist/helpers/browser-connect.js +407 -0
  34. package/dist/helpers/browser-decisions.d.ts +104 -0
  35. package/dist/helpers/browser-decisions.js +153 -0
  36. package/dist/helpers/browser-documentation.d.ts +2 -0
  37. package/dist/helpers/browser-documentation.js +69 -0
  38. package/dist/helpers/file-upload.d.ts +2 -2
  39. package/dist/helpers/sandbox-templates.d.ts +121 -0
  40. package/dist/helpers/sandbox-templates.js +60 -0
  41. package/dist/index.d.ts +9 -0
  42. package/dist/index.js +5 -0
  43. package/dist/operations.generated.d.ts +37 -13482
  44. package/dist/operations.generated.js +27895 -7213
  45. package/dist/resources.generated.d.ts +4064 -295
  46. package/dist/resources.generated.js +1289 -60
  47. package/package.json +2 -2
@@ -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,
@@ -121,16 +140,28 @@ export async function publish(client, input) {
121
140
  // The service contract accepts jwt instead of manifest. Its generated OpenAPI
122
141
  // type currently omits jwt; keep this explicit shape until that schema catches up.
123
142
  const versionAssets = { jwt, ...(input.assets_config ? { config: input.assets_config } : {}) };
124
- const result = await workers.versions.create({ path, body: {
143
+ // #3232: a large build takes minutes (one serial object write per module, ~1 s each), so the caller may be cut
144
+ // off by a codemode runtime limit or a gateway before the answer arrives while the service keeps writing. The key
145
+ // is chosen here, before the request: the same publish that is retried answers the version it already created
146
+ // instead of writing a second one, and a create still in progress answers 409 IDEMPOTENCY_IN_FLIGHT.
147
+ // A fresh key per publish() call is deliberate — publishing the same build twice on purpose is two versions.
148
+ // It is reused by the transport's own retries, which replay the same request (headers included).
149
+ const idempotencyKey = `publish-${crypto.randomUUID()}`;
150
+ const result = await workers.versions.create({
151
+ path,
152
+ headers: { 'Idempotency-Key': idempotencyKey },
153
+ // deploy stays true: the create and its pending deployment are one write to one Durable Object, and a replay
154
+ // returns that same deployment. Splitting it into two calls would add a second, unkeyed write whose timeout
155
+ // leaves the version created but not deployed.
156
+ body: {
125
157
  deploy: true,
126
158
  compatibility_date: input.compatibility_date ?? new Date().toISOString().slice(0, 10),
127
159
  assets: versionAssets,
128
160
  ...(input.compatibility_flags ? { compatibility_flags: input.compatibility_flags } : {}),
129
161
  ...(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)) }] } : {}),
133
- } });
162
+ ...(entryModules ? { main_module: mainModule, modules: entryModules } : {}),
163
+ },
164
+ });
134
165
  let deployment = result.deployment;
135
166
  if (!deployment)
136
167
  throw new PraxisError({ code: 'INVALID_RESPONSE', message: 'Version creation did not return a deployment' });
@@ -0,0 +1,104 @@
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
+ /** ADR-205: a paired user's own browser (byb_…); the session create carries `source: { byob }`. */
33
+ byob?: string;
34
+ home: string;
35
+ fetch: typeof globalThis.fetch;
36
+ fs: FsPromisesLike;
37
+ now: () => number;
38
+ }
39
+ /** An existing tab as `tabs.list` reports it. */
40
+ export interface ActionTabInfo {
41
+ id: string;
42
+ url: string;
43
+ title: string;
44
+ active: boolean;
45
+ }
46
+ /**
47
+ * One option to select on a `<select>`, Playwright's own vocabulary: a string matches the option's value or its
48
+ * visible text, and an object matches by any of `value`, visible `label`, or 0-based `index` (every property it
49
+ * names must match).
50
+ */
51
+ export type SelectOptionTarget = string | {
52
+ value?: string;
53
+ label?: string;
54
+ index?: number;
55
+ };
56
+ /** A page action's answer, structurally: every result kind carries at least `type`. */
57
+ type ActionAnswer = Record<string, unknown> & {
58
+ type?: unknown;
59
+ };
60
+ /** `~/.praxis/screenshots/<timestamp>-<tab>.png`, the Playwright driver's own naming. */
61
+ export declare const screenshotPath: (home: string, tab: string, now: number) => string;
62
+ /**
63
+ * base64 → bytes, without Buffer or atob: the light machine's isolate is promised neither, and the screenshot is
64
+ * the one binary this file writes. Characters outside the alphabet are ignored, as base64 decoders do.
65
+ */
66
+ export declare function decodeBase64(text: string): Uint8Array;
67
+ /** One tab handle: every method is one page action on the resolved session. */
68
+ export interface ActionsTab {
69
+ readonly id: string;
70
+ snapshot(): Promise<string>;
71
+ click(ref: string): Promise<void>;
72
+ fill(ref: string, text: string): Promise<void>;
73
+ /**
74
+ * A native `<select>`: choose the options named here — Playwright's `locator.selectOption` vocabulary. A string
75
+ * matches the option's value or its visible text; `{ value }`, `{ label }` and `{ index }` match that property
76
+ * alone, and an object naming several properties must match all of them. Pass one item or a list of them; the answer
77
+ * is the values of the options selected (a single `<select>` keeps only the first match, a `multiple` keeps every
78
+ * one).
79
+ */
80
+ selectOption(ref: string, values: SelectOptionTarget | readonly SelectOptionTarget[]): Promise<string[]>;
81
+ press(key: string): Promise<void>;
82
+ scroll(direction: 'up' | 'down', pixels?: number): Promise<void>;
83
+ evaluate(expression: string): Promise<unknown>;
84
+ screenshot(options?: {
85
+ fullPage?: boolean;
86
+ }): Promise<{
87
+ path: string;
88
+ hint: string;
89
+ }>;
90
+ }
91
+ /** The page-action client: session resolution, one request per action, one tab handle per tab id. */
92
+ export interface BrowserActions {
93
+ sessionId(): Promise<string>;
94
+ list(): Promise<ActionTabInfo[]>;
95
+ tab(id: string): ActionsTab;
96
+ /** One already-built action, for the shapes no tab method covers. */
97
+ action(body: Record<string, unknown>): Promise<ActionAnswer>;
98
+ }
99
+ /**
100
+ * Builds the actions client. It never opens a connection, imports Playwright, or reads a Node builtin: a session
101
+ * id is resolved once per call from the name, and every action is a request that returns its own answer.
102
+ */
103
+ export declare function createBrowserActions(deps: BrowserActionsDeps): BrowserActions;
104
+ export {};
@@ -0,0 +1,150 @@
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
+ import { byobRefusalBody, isByobRefusalCode } from "./browser-connect-error.js";
16
+ /** The public own-face path prefix — the same one this SDK's connect URL is built on. */
17
+ const BROWSER_V1 = '/browser/v1';
18
+ /** Where screenshots land, matching the Playwright driver's directory. */
19
+ export const SCREENSHOT_DIR = '.praxis/screenshots';
20
+ /**
21
+ * A refusal becomes an error here and nowhere else: the server's own code, status and message travel unchanged,
22
+ * so ACTION_REF_STALE stays distinguishable from an outage (ticket-834's rule, for the actions door).
23
+ */
24
+ function failure(status, body) {
25
+ const record = body;
26
+ const named = typeof record?.code === 'string' ? record.code : undefined;
27
+ const raw = isByobRefusalCode(named) ? byobRefusalBody(named, record) : body;
28
+ const code = typeof record?.code === 'string' ? record.code : undefined;
29
+ const message = typeof record?.message === 'string' ? record.message
30
+ : typeof record?.error === 'string' ? record.error
31
+ : `The browser action failed with HTTP ${status}.`;
32
+ return new PraxisError({ status, ...(code === undefined ? {} : { code }), message, raw });
33
+ }
34
+ /** `~/.praxis/screenshots/<timestamp>-<tab>.png`, the Playwright driver's own naming. */
35
+ export const screenshotPath = (home, tab, now) => `${home}/${SCREENSHOT_DIR}/${now}-${tab.slice(0, 8)}.png`;
36
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
37
+ /**
38
+ * base64 → bytes, without Buffer or atob: the light machine's isolate is promised neither, and the screenshot is
39
+ * the one binary this file writes. Characters outside the alphabet are ignored, as base64 decoders do.
40
+ */
41
+ export function decodeBase64(text) {
42
+ const clean = text.replace(/[^A-Za-z0-9+/]/g, '');
43
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
44
+ let byte = 0;
45
+ let bits = 0;
46
+ let written = 0;
47
+ for (const character of clean) {
48
+ const value = ALPHABET.indexOf(character);
49
+ if (value < 0)
50
+ continue;
51
+ byte = (byte << 6) | value;
52
+ bits += 6;
53
+ if (bits >= 8) {
54
+ bits -= 8;
55
+ out[written++] = (byte >> bits) & 0xff;
56
+ }
57
+ }
58
+ return out.subarray(0, written);
59
+ }
60
+ /**
61
+ * Builds the actions client. It never opens a connection, imports Playwright, or reads a Node builtin: a session
62
+ * id is resolved once per call from the name, and every action is a request that returns its own answer.
63
+ */
64
+ export function createBrowserActions(deps) {
65
+ const request = async (path, init = {}) => {
66
+ const headers = {
67
+ Authorization: `Bearer ${deps.token}`,
68
+ ...(init.body === undefined ? {} : { 'content-type': 'application/json' }),
69
+ ...(init.headers ?? {}),
70
+ };
71
+ let response;
72
+ try {
73
+ response = await deps.fetch(`${deps.api}${BROWSER_V1}${path}`, { ...init, headers });
74
+ }
75
+ catch (cause) {
76
+ throw new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message: `Reaching the cloud browser failed: ${cause.message.split('\n')[0]}` });
77
+ }
78
+ const text = await response.text();
79
+ let body;
80
+ try {
81
+ body = text ? JSON.parse(text) : undefined;
82
+ }
83
+ catch {
84
+ body = text;
85
+ }
86
+ if (!response.ok)
87
+ throw failure(response.status, body);
88
+ return body;
89
+ };
90
+ /** Resolved once per client: one connect() is one program, and the session it named does not change inside it. */
91
+ let resolved;
92
+ /** The live session named for this agent session, else a new one under that name. */
93
+ const sessionId = async () => {
94
+ resolved ??= (async () => {
95
+ const found = (await request(`/sessions?name=${encodeURIComponent(deps.name)}&status=RUNNING`));
96
+ // A page holds only this account's sessions, but a name is what identifies ours: anything else is not it.
97
+ const live = (found?.data ?? []).find(row => typeof row.id === 'string' && row.name === deps.name);
98
+ if (live?.id)
99
+ return live.id;
100
+ const created = (await request('/sessions', {
101
+ method: 'POST',
102
+ body: JSON.stringify({
103
+ name: deps.name,
104
+ labels: deps.labels,
105
+ ...(deps.byob === undefined ? {} : { source: { byob: deps.byob } }),
106
+ ...(deps.context === undefined ? {} : { browserSettings: { context: { id: deps.context, persist: true } } }),
107
+ }),
108
+ }));
109
+ if (typeof created?.id !== 'string')
110
+ throw new PraxisError({ status: 503, code: 'BROWSER_UNAVAILABLE', message: 'The cloud browser session could not be opened.' });
111
+ return created.id;
112
+ })();
113
+ // A failed resolution is not cached: the next action may find the service again.
114
+ return await resolved.catch(cause => { resolved = undefined; throw cause; });
115
+ };
116
+ const action = async (body) => {
117
+ const id = await sessionId();
118
+ return (await request(`/sessions/${encodeURIComponent(id)}/actions`, { method: 'POST', body: JSON.stringify(body) }));
119
+ };
120
+ const list = async () => {
121
+ const answer = await action({ type: 'tabs.list' });
122
+ return (answer.tabs ?? []).map(tab => ({ id: tab.id, url: tab.url, title: tab.title, active: tab.active }));
123
+ };
124
+ const tab = (id) => {
125
+ const on = (type, extra = {}) => action({ type, tab: id, ...extra });
126
+ return {
127
+ id,
128
+ // The server's own rendering; same reading model as the Playwright driver's ariaSnapshot({ mode: "ai" }).
129
+ snapshot: async () => String((await on('snapshot')).snapshot ?? ''),
130
+ click: async (ref) => { await on('click', { ref }); },
131
+ fill: async (ref, text) => { await on('fill', { ref, text }); },
132
+ selectOption: async (ref, values) => {
133
+ // Playwright takes one item or a list; the wire always carries the list.
134
+ const answer = await on('select', { ref, values: Array.isArray(values) ? values : [values] });
135
+ return (answer.values ?? []).filter((value) => typeof value === 'string');
136
+ },
137
+ press: async (key) => { await on('press', { key }); },
138
+ scroll: async (direction, pixels) => { await on('scroll', { direction, ...(pixels === undefined ? {} : { pixels }) }); },
139
+ evaluate: async (expression) => (await on('evaluate', { expression })).value,
140
+ screenshot: async (options) => {
141
+ const answer = await on('screenshot', options?.fullPage === true ? { fullPage: true } : {});
142
+ const path = screenshotPath(deps.home, id, deps.now());
143
+ await deps.fs.mkdir(`${deps.home}/${SCREENSHOT_DIR}`, { recursive: true });
144
+ await deps.fs.writeFile(path, decodeBase64(String(answer.data ?? '')));
145
+ return { path, hint: 'View this PNG with the Read tool.' };
146
+ },
147
+ };
148
+ };
149
+ return { sessionId, list, tab, action };
150
+ }
@@ -0,0 +1,34 @@
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. For a BYOB refusal it also carries `retryable` and `last_seen_at`. */
21
+ readonly raw?: unknown;
22
+ }
23
+ /** ADR-205: the refusals of a user's own browser (BYOB). Their codes travel as themselves; only these say whether a retry can help. */
24
+ export declare const BYOB_REFUSAL_CODES: readonly ["BROWSER_OFFLINE", "BROWSER_REVOKED", "BROWSER_NOT_FOUND"];
25
+ export type ByobRefusalCode = (typeof BYOB_REFUSAL_CODES)[number];
26
+ export declare const isByobRefusalCode: (code: unknown) => code is ByobRefusalCode;
27
+ /** The body of a BYOB refusal with `retryable` (only BROWSER_OFFLINE: the link may come back) and `last_seen_at` made explicit. */
28
+ export declare function byobRefusalBody(code: ByobRefusalCode, body: Record<string, unknown>): Record<string, unknown>;
29
+ /**
30
+ * The refusal a Playwright connect failure stands for. Total and pure: the same message always yields the same
31
+ * classification. The body's own code wins (the domain code crosses the boundary unchanged); with no readable
32
+ * body the status line names it, so a 409 arrives as CONTEXT_LOCKED rather than a 503.
33
+ */
34
+ export declare function classifyConnectRefusal(message: string): ConnectRefusal;
@@ -0,0 +1,85 @@
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
+ /** ADR-205: the refusals of a user's own browser (BYOB). Their codes travel as themselves; only these say whether a retry can help. */
16
+ export const BYOB_REFUSAL_CODES = ['BROWSER_OFFLINE', 'BROWSER_REVOKED', 'BROWSER_NOT_FOUND'];
17
+ export const isByobRefusalCode = (code) => BYOB_REFUSAL_CODES.includes(code);
18
+ /** The body of a BYOB refusal with `retryable` (only BROWSER_OFFLINE: the link may come back) and `last_seen_at` made explicit. */
19
+ export function byobRefusalBody(code, body) {
20
+ const seen = body.last_seen_at ?? body.lastSeenAt;
21
+ const fromMessage = typeof body.message === 'string' ? /since (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/.exec(body.message)?.[1] : undefined;
22
+ const lastSeenAt = typeof seen === 'string' ? seen : seen === null ? null : fromMessage ?? null;
23
+ return { ...body, retryable: code === 'BROWSER_OFFLINE', ...(code === 'BROWSER_OFFLINE' ? { last_seen_at: lastSeenAt } : {}) };
24
+ }
25
+ /**
26
+ * What a status line alone names, when the refusal body carried no code. Only statuses that the connect path
27
+ * answers with one unambiguous domain code belong here; anything else stays the outage.
28
+ */
29
+ const CODE_BY_STATUS = {
30
+ 400: 'INVALID_PARAMS',
31
+ 401: 'UNAUTHENTICATED',
32
+ 402: 'QUOTA_EXHAUSTED',
33
+ 403: 'FORBIDDEN',
34
+ 404: 'NOT_FOUND',
35
+ 409: 'CONTEXT_LOCKED',
36
+ 429: 'RATE_LIMITED',
37
+ };
38
+ /** The only useful thing to say about a locked sign-in context: wait for the lease, or leave it alone. */
39
+ 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).";
40
+ /** 503 is the outage: the service answered 503, or the SDK holds nothing that names the failure. */
41
+ const outage = (message) => ({ status: 503, code: 'BROWSER_UNAVAILABLE', message });
42
+ /** The object a body text parses to, or undefined when it is not a JSON object. */
43
+ function jsonObject(text) {
44
+ try {
45
+ const value = JSON.parse(text);
46
+ return value !== null && typeof value === 'object' ? value : undefined;
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ /** 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). */
53
+ function refusalFromMessage(message) {
54
+ const line = /WebSocket error: \S+ (\d{3})(?:[^\n]*)/.exec(message);
55
+ if (!line)
56
+ return null;
57
+ const status = Number(line[1]);
58
+ if (!Number.isInteger(status))
59
+ return null;
60
+ const at = message.indexOf('\n');
61
+ return { status, body: at < 0 ? undefined : jsonObject(message.slice(at + 1)) };
62
+ }
63
+ /**
64
+ * The refusal a Playwright connect failure stands for. Total and pure: the same message always yields the same
65
+ * classification. The body's own code wins (the domain code crosses the boundary unchanged); with no readable
66
+ * body the status line names it, so a 409 arrives as CONTEXT_LOCKED rather than a 503.
67
+ */
68
+ export function classifyConnectRefusal(message) {
69
+ const firstLine = message.split('\n')[0] ?? message;
70
+ const refusal = refusalFromMessage(message);
71
+ if (!refusal)
72
+ return outage(`Connecting to the cloud browser failed: ${firstLine}`);
73
+ const body = refusal.body;
74
+ const code = typeof body?.code === 'string' ? body.code : undefined;
75
+ if (code !== undefined && body) {
76
+ const retryAfter = typeof body.retryAfter === 'number' && Number.isFinite(body.retryAfter) ? body.retryAfter : null;
77
+ const text = typeof body.message === 'string' ? body.message : undefined;
78
+ const raw = isByobRefusalCode(code) ? byobRefusalBody(code, body) : body;
79
+ return { status: refusal.status, code, message: `${text ?? code}${retryAfter === null ? '' : ` Retry after ${retryAfter} s.`}`, raw };
80
+ }
81
+ const byStatus = CODE_BY_STATUS[refusal.status];
82
+ if (byStatus === undefined)
83
+ return outage(`Connecting to the cloud browser failed: ${firstLine}`);
84
+ return { status: refusal.status, code: byStatus, message: refusal.status === 409 ? CONTEXT_LOCKED_MESSAGE : firstLine };
85
+ }