@deepraxis/sdk 0.1.1-dev.349f88a → 0.1.1-dev.3987a02

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.
@@ -47,6 +47,7 @@ interface ContextsApi {
47
47
  query?: {
48
48
  limit?: number;
49
49
  cursor?: string;
50
+ name?: string;
50
51
  };
51
52
  }): Promise<{
52
53
  data: (ContextLike & {
@@ -61,6 +62,15 @@ interface ContextsApi {
61
62
  };
62
63
  }): Promise<ContextLike>;
63
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
+ }
64
74
  /** What connect() needs from the platform client and the process. All of it is injectable for tests. */
65
75
  export interface BrowserConnectDeps {
66
76
  contexts: ContextsApi;
@@ -68,6 +78,8 @@ export interface BrowserConnectDeps {
68
78
  /** process.getBuiltinModule; undefined on runtimes without it. */
69
79
  builtin: ((name: string) => unknown) | undefined;
70
80
  now?: () => number;
81
+ /** An already-loaded playwright-core; the real loader finds or installs one and imports it. */
82
+ playwright?: PlaywrightModule;
71
83
  }
72
84
  export declare const unavailable: (message: string) => PraxisError;
73
85
  /** Same signal the plugin installer and child_process use: the light machine asks to be upgraded and the program runs again. */
@@ -8,7 +8,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
8
8
  };
9
9
  import { PraxisError } from "../core/errors.js";
10
10
  import { BROWSER_DOCUMENTATION } from "./browser-documentation.js";
11
- import { agentContextName, buildConnectUrl, decideTabReuse, pickAgentContext } from "./browser-decisions.js";
11
+ import { agentContextName, buildConnectUrl, decideTabReuse, isDuplicateNameError, matchTargetsToPages, pickAgentContext, pickContextByName } from "./browser-decisions.js";
12
12
  /** Version of the Playwright client library: preinstalled in the base image, installed on demand elsewhere. */
13
13
  export const PLAYWRIGHT_CORE_VERSION = '1.63.0';
14
14
  const GLOBAL_PLAYWRIGHT = '/usr/local/lib/node_modules/playwright-core';
@@ -33,6 +33,8 @@ function node(deps, name) {
33
33
  throw needsFullMachine();
34
34
  }
35
35
  async function loadPlaywright(deps, home) {
36
+ if (deps.playwright)
37
+ return deps.playwright;
36
38
  node(deps, 'node:child_process'); // fails fast on a light machine, before any network work
37
39
  const fs = node(deps, 'node:fs');
38
40
  const entry = (root) => `${root}/index.mjs`;
@@ -49,20 +51,49 @@ async function loadPlaywright(deps, home) {
49
51
  }
50
52
  return await import(__rewriteRelativeImportExtension(/* @vite-ignore */ `file://${entry(root)}`));
51
53
  }
54
+ /** The agent's own context, in one name-filtered request; the paged scan is only the pre-`name` server fallback. */
52
55
  async function ensureContext(deps, agentId) {
53
- const seen = [];
54
- let cursor;
55
- for (let page = 0; page < 20; page++) {
56
- const result = await deps.contexts.list({ query: { limit: 100, ...(cursor ? { cursor } : {}) } });
57
- seen.push(...result.data);
58
- const own = pickAgentContext(seen, agentId);
59
- if (own)
60
- return own.id;
61
- if (!result.nextCursor)
62
- break;
63
- cursor = result.nextCursor;
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;
64
96
  }
65
- return (await deps.contexts.create({ body: { name: agentContextName(agentId), labels: { agent: agentId } } })).id;
66
97
  }
67
98
  const bounded = (work, ms) => Promise.race([work, new Promise((_, reject) => setTimeout(() => reject(new Error('timed out')), ms))]);
68
99
  export async function connectBrowser(deps, options = {}) {
@@ -86,6 +117,33 @@ export async function connectBrowser(deps, options = {}) {
86
117
  const now = deps.now ?? Date.now;
87
118
  const pages = () => browser.contexts().flatMap((c) => c.pages());
88
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
+ };
89
147
  const idOf = async (page) => {
90
148
  const known = ids.get(page);
91
149
  if (known)
@@ -100,6 +158,25 @@ export async function connectBrowser(deps, options = {}) {
100
158
  await session.detach().catch(() => { });
101
159
  }
102
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(() => '');
103
180
  const wrap = async (page) => {
104
181
  const id = await idOf(page);
105
182
  return {
@@ -121,17 +198,20 @@ export async function connectBrowser(deps, options = {}) {
121
198
  },
122
199
  };
123
200
  };
124
- const list = async () => Promise.all(pages().map(async (page) => ({
125
- id: await idOf(page), url: page.url(),
126
- title: await bounded(page.title(), 2000).catch(() => ''),
127
- active: await bounded(page.evaluate(() => document.visibilityState === 'visible'), 2000).catch(() => false),
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),
128
206
  })));
129
207
  const get = async (id) => {
130
- for (const page of pages())
131
- if (await idOf(page) === id) {
132
- await page.bringToFront().catch(() => { });
133
- return wrap(page);
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);
134
213
  }
214
+ }
135
215
  throw new PraxisError({ status: 404, code: 'TAB_NOT_FOUND', message: `No tab with id ${id}; call browser.tabs.list() for the current tabs.` });
136
216
  };
137
217
  const create = async () => {
@@ -156,6 +236,11 @@ export async function connectBrowser(deps, options = {}) {
156
236
  return tab;
157
237
  },
158
238
  documentation: () => BROWSER_DOCUMENTATION,
159
- disconnect: async () => { await browser.close(); },
239
+ /** Drops this connection only; the cloud session and its tabs stay until it idles out. */
240
+ disconnect: async () => {
241
+ await cdp?.detach().catch(() => { });
242
+ cdp = undefined;
243
+ await browser.close();
244
+ },
160
245
  };
161
246
  }
@@ -42,3 +42,32 @@ export declare function pickAgentContext<T extends ContextLike>(contexts: readon
42
42
  export declare const agentContextName: (agentId: string) => string;
43
43
  /** Start pages are expendable only on Console hosts, never arbitrary sites' /start pages. */
44
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;
@@ -82,3 +82,42 @@ export function isBlankTab(value) {
82
82
  return false;
83
83
  }
84
84
  }
85
+ /**
86
+ * Matches the browser's page targets (a raw `Target.getTargets` answer) to the pages Playwright holds, by url.
87
+ * Non-page targets name no tab. A url naming more than one target, or more than one page, identifies nothing:
88
+ * both sides fall back to the per-page lookup, because a wrong tab id is worse than one extra round trip.
89
+ */
90
+ export function matchTargetsToPages(targets, pageUrls) {
91
+ const byUrl = new Map();
92
+ for (const target of targets)
93
+ if (target.type === 'page')
94
+ byUrl.set(target.url, [...(byUrl.get(target.url) ?? []), target]);
95
+ const pagesPerUrl = new Map();
96
+ for (const url of pageUrls)
97
+ pagesPerUrl.set(url, (pagesPerUrl.get(url) ?? 0) + 1);
98
+ const matched = new Map();
99
+ const unmatched = [];
100
+ pageUrls.forEach((url, index) => {
101
+ const candidates = byUrl.get(url);
102
+ const target = candidates?.length === 1 && pagesPerUrl.get(url) === 1 ? candidates[0] : undefined;
103
+ if (target)
104
+ matched.set(index, target);
105
+ else
106
+ unmatched.push(index);
107
+ });
108
+ return { matched, unmatched };
109
+ }
110
+ /**
111
+ * The context a name-filtered lookup returned for this agent, or nothing when the entry is not it.
112
+ * An old server ignores `name` and answers with unrelated rows; adopting one of those would hand this run
113
+ * another agent's stored sign-ins.
114
+ */
115
+ export function pickContextByName(contexts, agentId) {
116
+ const wanted = agentContextName(agentId);
117
+ return contexts.find(context => context.name === wanted && context.labels?.agent === agentId);
118
+ }
119
+ /** A context name is unique per account, so a create that loses a race answers INVALID_PARAMS with this phrase. */
120
+ export function isDuplicateNameError(error) {
121
+ const problem = error;
122
+ return problem?.code === 'INVALID_PARAMS' && typeof problem.message === 'string' && problem.message.includes('already exists');
123
+ }
@@ -0,0 +1,121 @@
1
+ export interface TemplateBuildLog {
2
+ timestamp: string;
3
+ level: 'debug' | 'info' | 'warn' | 'error';
4
+ message: string;
5
+ step?: string;
6
+ }
7
+ export interface TemplateBuildReason {
8
+ message: string;
9
+ step?: string;
10
+ logEntries?: TemplateBuildLog[];
11
+ }
12
+ export interface TemplateBuildStatus {
13
+ templateID: string;
14
+ buildID: string;
15
+ status: 'waiting' | 'building' | 'ready' | 'error';
16
+ logEntries: TemplateBuildLog[];
17
+ logs: string[];
18
+ reason?: TemplateBuildReason;
19
+ }
20
+ export type SandboxTemplateBuildInput = {
21
+ /** Organization-local name. Reusing it reserves another build of the same template. */
22
+ name: string;
23
+ /** Optional resource counts; defaults to 2 vCPUs and 1024 MiB. */
24
+ cpuCount?: number;
25
+ memoryMB?: number;
26
+ /** Disk size in GiB, a positive integer; default 10. */
27
+ diskGb?: number;
28
+ /** Labels assigned only after a successful build. */
29
+ tags?: string[];
30
+ /** Structured build steps; COPY is rejected. Mutually exclusive with dockerfile. */
31
+ steps?: {
32
+ type: 'RUN' | 'ENV' | 'WORKDIR' | 'USER';
33
+ args: string[];
34
+ }[];
35
+ /** Called sequentially for newly read log entries. */
36
+ onLog?: (entry: TemplateBuildLog) => void | Promise<void>;
37
+ /** Stops requests and polling; the remote build continues. */
38
+ signal?: AbortSignal;
39
+ /** Nonnegative polling delay in milliseconds; default 1000. */
40
+ pollIntervalMs?: number;
41
+ } & ({
42
+ dockerfile: string;
43
+ fromTemplate?: never;
44
+ fromImage?: never;
45
+ steps?: never;
46
+ } | {
47
+ dockerfile?: never;
48
+ fromTemplate: string;
49
+ fromImage?: never;
50
+ } | {
51
+ dockerfile?: never;
52
+ fromTemplate?: never;
53
+ fromImage: string;
54
+ });
55
+ export interface SandboxTemplateBuildResult extends TemplateBuildStatus {
56
+ status: 'ready';
57
+ }
58
+ export declare class SandboxTemplateBuildError extends Error {
59
+ readonly templateID: string;
60
+ readonly buildID: string;
61
+ readonly reason: TemplateBuildReason | undefined;
62
+ readonly logEntries: readonly TemplateBuildLog[];
63
+ readonly name = "SandboxTemplateBuildError";
64
+ constructor(templateID: string, buildID: string, reason: TemplateBuildReason | undefined, logEntries: readonly TemplateBuildLog[]);
65
+ }
66
+ /** Structural port keeps the helper independent of the client that attaches it. */
67
+ export interface SandboxTemplateBuildClient {
68
+ sandbox: {
69
+ templates: {
70
+ create(input: {
71
+ body: {
72
+ name: string;
73
+ cpuCount?: number;
74
+ memoryMB?: number;
75
+ diskGb?: number;
76
+ tags?: string[];
77
+ };
78
+ signal: AbortSignal;
79
+ }): Promise<{
80
+ templateID: string;
81
+ buildID: string;
82
+ }>;
83
+ builds: {
84
+ update(input: {
85
+ path: {
86
+ templateID: string;
87
+ buildID: string;
88
+ };
89
+ body: {
90
+ dockerfile?: string;
91
+ fromTemplate?: string;
92
+ fromImage?: string;
93
+ steps?: {
94
+ type: string;
95
+ args: string[];
96
+ }[];
97
+ };
98
+ signal: AbortSignal;
99
+ }): Promise<unknown>;
100
+ status: {
101
+ list(input: {
102
+ path: {
103
+ templateID: string;
104
+ buildID: string;
105
+ };
106
+ query: {
107
+ logsOffset: number;
108
+ };
109
+ signal: AbortSignal;
110
+ }): Promise<TemplateBuildStatus>;
111
+ };
112
+ };
113
+ };
114
+ };
115
+ }
116
+ /** Build an organization-local template and wait until it is ready, streaming logs in order.
117
+ * Uses create, source submission and status polling. COPY is unavailable; use RUN curl or git clone.
118
+ * fromTemplate accepts official catalog names only. Abort stops the client; it does not cancel the build.
119
+ * Terminal errors include the provider reason and the final twenty bounded log entries.
120
+ */
121
+ export declare function buildSandboxTemplate(client: SandboxTemplateBuildClient, input: SandboxTemplateBuildInput): Promise<SandboxTemplateBuildResult>;
@@ -0,0 +1,60 @@
1
+ import { sleep } from "../core/retry.js";
2
+ export class SandboxTemplateBuildError extends Error {
3
+ templateID;
4
+ buildID;
5
+ reason;
6
+ logEntries;
7
+ name = 'SandboxTemplateBuildError';
8
+ constructor(templateID, buildID, reason, logEntries) {
9
+ super(`Template build failed: ${reason?.message ?? 'Unknown build error'}${logEntries.length ? `\n${logEntries.map(log => log.message).join('\n')}` : ''}`);
10
+ this.templateID = templateID;
11
+ this.buildID = buildID;
12
+ this.reason = reason;
13
+ this.logEntries = logEntries;
14
+ }
15
+ }
16
+ /** Build an organization-local template and wait until it is ready, streaming logs in order.
17
+ * Uses create, source submission and status polling. COPY is unavailable; use RUN curl or git clone.
18
+ * fromTemplate accepts official catalog names only. Abort stops the client; it does not cancel the build.
19
+ * Terminal errors include the provider reason and the final twenty bounded log entries.
20
+ */
21
+ export async function buildSandboxTemplate(client, input) {
22
+ const signal = input.signal ?? new AbortController().signal;
23
+ signal.throwIfAborted();
24
+ const interval = input.pollIntervalMs ?? 1000;
25
+ if (!Number.isSafeInteger(interval) || interval < 0)
26
+ throw new RangeError('pollIntervalMs must be a nonnegative integer');
27
+ if ([input.dockerfile, input.fromTemplate, input.fromImage].filter(value => value !== undefined).length !== 1
28
+ || (input.dockerfile !== undefined && input.steps !== undefined))
29
+ throw new TypeError('Supply dockerfile, fromTemplate or fromImage; dockerfile cannot include steps');
30
+ const created = await client.sandbox.templates.create({ body: {
31
+ name: input.name, cpuCount: input.cpuCount, memoryMB: input.memoryMB, diskGb: input.diskGb, tags: input.tags,
32
+ }, signal });
33
+ const path = { templateID: created.templateID, buildID: created.buildID };
34
+ await client.sandbox.templates.builds.update({ path, body: input.dockerfile !== undefined ? { dockerfile: input.dockerfile }
35
+ : { fromTemplate: input.fromTemplate, fromImage: input.fromImage, steps: input.steps }, signal });
36
+ let logsOffset = 0;
37
+ const tail = [];
38
+ let terminal;
39
+ while (true) {
40
+ signal.throwIfAborted();
41
+ const result = await client.sandbox.templates.builds.status.list({ path, query: { logsOffset }, signal });
42
+ for (const entry of result.logEntries) {
43
+ signal.throwIfAborted();
44
+ await input.onLog?.(entry);
45
+ // Bound retained diagnostics even when one provider log message is enormous.
46
+ tail.push({ ...entry, message: entry.message.slice(-4096) });
47
+ if (tail.length > 20)
48
+ tail.shift();
49
+ }
50
+ logsOffset += result.logEntries.length;
51
+ if (!terminal && (result.status === 'ready' || result.status === 'error'))
52
+ terminal = result;
53
+ if (terminal && result.logEntries.length === 0) {
54
+ if (terminal.status === 'error')
55
+ throw new SandboxTemplateBuildError(path.templateID, path.buildID, terminal.reason, tail);
56
+ return { ...terminal, status: 'ready', logEntries: [] };
57
+ }
58
+ await sleep(interval, signal);
59
+ }
60
+ }
package/dist/index.d.ts CHANGED
@@ -15,3 +15,5 @@ export { uploadFile } from './helpers/file-upload.js';
15
15
  export type { UploadFileOptions, UploadedFile } from './helpers/file-upload.js';
16
16
  export { connectBrowser } from './helpers/browser-connect.js';
17
17
  export type { PraxisBrowser, BrowserTab, BrowserConnectOptions } from './helpers/browser-connect.js';
18
+ export { buildSandboxTemplate, SandboxTemplateBuildError } from './helpers/sandbox-templates.js';
19
+ export type { SandboxTemplateBuildInput, SandboxTemplateBuildResult, TemplateBuildLog, TemplateBuildReason } from './helpers/sandbox-templates.js';
package/dist/index.js CHANGED
@@ -7,3 +7,4 @@ export { publishInputFromBuild } from "./helpers/application-build.js";
7
7
  export { count } from "./helpers/database-count.js";
8
8
  export { uploadFile } from "./helpers/file-upload.js";
9
9
  export { connectBrowser } from "./helpers/browser-connect.js";
10
+ export { buildSandboxTemplate, SandboxTemplateBuildError } from "./helpers/sandbox-templates.js";