@picassohq/cli 1.0.8 → 1.0.9

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,915 @@
1
+ // @picasso/browser — the agent's browser tools, executed by the Mac app on the thread's own Preview pane.
2
+ //
3
+ // dsh runs the model; the Picasso Mac app owns the only browser. A `browser_*` tool call queues an action on this
4
+ // plugin's Host Remote service (`picassoBrowser/*`), which the helper relay long-polls:
5
+ // take(timeoutMs[, signal]) -> {actions:[{actionId, sessionId, callId, tool, args, issuedAt}], cancelled:[id…]}
6
+ // returns as soon as work is queued, else after timeoutMs with empty arrays.
7
+ // Each action is handed out once; `cancelled` lists ids aborted before completion
8
+ // (tool-call abort or per-action timeout) so the Mac can drop them.
9
+ // complete(actionId, ok, value, error, sessionId) -> {}; unknown or already-settled ids fail
10
+ // `picassoBrowser/unknown-action`; a missing sessionId fails
11
+ // `picassoBrowser/session-required` and one that is not the
12
+ // issuing session's fails `picassoBrowser/session-mismatch` — stale,
13
+ // duplicate, cancelled and expired completions all land on
14
+ // unknown-action (the action is already settled). `value` is
15
+ // `{text, image?:{data: base64, mimeType}}`; `ok:false` carries `error`.
16
+ //
17
+ // Failure rules (see README): a tool call with no take() seen in the last 30 s fails fast ("Browser tools need the
18
+ // Picasso Mac app open."); an unanswered action fails after 60 s ("The Picasso preview didn't respond."); an aborted
19
+ // tool call drops its action and reports it cancelled.
20
+ //
21
+ // Mutating tools are gated by `tools/pre-execute` -> {kind:'ask'}, which dsh routes to the deployment's approval
22
+ // answerers (the Picasso relay forwards them to the Mac's approval card). Read-only tools delegate with next().
23
+ // Public http(s) sites pass through: the host (the Mac's Preview) is authoritative for the person's allowed sites.
24
+ // A remote-site ask reason ends `(site <key>)` (SITE_REASON) so the relay keys "Allow for this thread" per site and
25
+ // the Mac card offers Allow once / Always allow this site / Deny. Private-network and non-http(s) URLs never queue.
26
+ //
27
+ // Image projection goes through `@deepseek-ai/dsh-mcp-client`'s createMcpToolDefinition (the same adapter dsh's
28
+ // native Cua driver uses): a `{type:'image', data, mimeType}` block is admitted, stored as a durable attachment and
29
+ // referenced — never inlined — when the current model declares image input. The adapter is loaded with createRequire
30
+ // anchored at `config.dshBin` (the realpath of the launched dsh bin, passed by the relay's generated patch). When it
31
+ // cannot resolve, the same tools register text-only and browser_screenshot returns a text error.
32
+ //
33
+ // CLI host (`config.host: 'cli'`, the CLI's own engine sessions on every OS): the picasso-sdk-server hands each queued
34
+ // action to the CLI process (`browser/action`), which runs it on a headless Chromium (packages/core browser-host.ts).
35
+ // There the plugin keeps the person's site rules itself, as the Mac app does: localhost and files in the thread's
36
+ // folder open directly (no tool ask); a public site not yet allowed asks once through the engine's user-questions
37
+ // service (Allow once / Always allow <site> / Deny), so the TUI shows it in every permission mode; "Always allow"
38
+ // lands in `config.sitesFile` (`<picassoHome>/settings/browser-sites.json`, the list Picasso for Mac shares). Each
39
+ // action carries the thread's folder and allowed sites (`cwd`, `sites`) so the executor can refuse every other load.
40
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
41
+ import { createRequire } from 'node:module';
42
+ import { homedir } from 'node:os';
43
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
44
+ import { fileURLToPath, pathToFileURL } from 'node:url';
45
+
46
+ export const name = 'picasso-browser';
47
+ export const dshTarget = '0.2.2-rc.3';
48
+ // `inject` orders us after the tools service and unlocks `ctx.tools` property access.
49
+ export const inject = ['tools'];
50
+
51
+ export const SERVICE_KEY = 'picassoBrowser';
52
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
53
+
54
+ /** No `take()` seen within this window means the Mac app is not running its poller. */
55
+ export const NO_POLLER_MS = 30_000;
56
+ /** One queued action's answer budget before its tool call fails. */
57
+ export const ACTION_TIMEOUT_MS = 60_000;
58
+ export const TAKE_DEFAULT_MS = 25_000;
59
+
60
+ export const APP_CLOSED = 'Browser tools need the Picasso Mac app open.';
61
+ export const ACTION_TIMEOUT = "The Picasso preview didn't respond.";
62
+ /** CLI host: the terminal that runs this session's browser stopped polling (it quit or never started one). */
63
+ export const CLI_HOST_GONE = "This session's browser isn't running (the terminal that started the session is gone). Start the session again in Picasso.";
64
+ export const CLI_ACTION_TIMEOUT = "The browser didn't respond.";
65
+ export const FILE_OUTSIDE_REFUSAL = "Only files inside this thread's folder open in the Picasso browser.";
66
+ export const PRIVATE_REFUSAL =
67
+ 'Private-network addresses never open in the Picasso browser. Only localhost dev servers and public sites the person allows open there.';
68
+ export const UNSUPPORTED_REFUSAL =
69
+ 'Only http(s) addresses, localhost dev servers and files in the thread’s folder open in the Picasso browser.';
70
+
71
+ /** The tools that always change the page: each prompts via the approval card. `browser_tabs` asks only to open a URL. */
72
+ export const ASK_TOOLS = new Set(['browser_navigate', 'browser_click', 'browser_type', 'browser_press_key']);
73
+ export const ALLOW_TOOLS = new Set([
74
+ 'browser_back', 'browser_console', 'browser_forward', 'browser_reload', 'browser_screenshot',
75
+ 'browser_scroll', 'browser_snapshot', 'browser_tabs', 'browser_wait_for',
76
+ ]);
77
+ export const TOOL_NAMES = [...ASK_TOOLS, ...ALLOW_TOOLS].sort();
78
+ const ALLOWED_KEYS = new Set(['Enter', 'Tab', 'Escape', 'Backspace', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);
79
+ export const TAB_ACTIONS = ['list', 'new', 'select', 'close'];
80
+ export const WAIT_MAX_SECONDS = 30;
81
+ export const WAIT_MIN_SECONDS = 0.1;
82
+ const WAIT_TEXT_MAX = 500;
83
+
84
+ export class BrowserError extends Error {
85
+ constructor(code, message, details = {}) {
86
+ super(message);
87
+ this.name = 'RemoteError';
88
+ this.code = `${SERVICE_KEY}/${code}`;
89
+ this.details = details;
90
+ this.isDSHRemoteError = true;
91
+ }
92
+ }
93
+
94
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
95
+
96
+ // ── URL classification (mirrors the Mac's PreviewURLPolicy; the host stays authoritative) ─────────────────────
97
+
98
+ const PRIVATE_SUFFIXES = ['.local', '.lan', '.internal', '.intranet', '.home', '.home.arpa', '.localdomain', '.corp'];
99
+
100
+ function ipv4Parts(host) {
101
+ const parts = host.split('.');
102
+ if (parts.length !== 4 || !parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)) return undefined;
103
+ return parts.map(Number);
104
+ }
105
+
106
+ /** 'loopback' | 'private' | 'public' for an IPv4 address given as four octets. */
107
+ function ipv4Class([a, b]) {
108
+ if (a === 127) return 'loopback';
109
+ if (a === 10 || a === 0) return 'private';
110
+ if (a === 172 && b >= 16 && b <= 31) return 'private';
111
+ if (a === 192 && b === 168) return 'private';
112
+ if (a === 169 && b === 254) return 'private';
113
+ if (a === 100 && b >= 64 && b <= 127) return 'private';
114
+ if (a >= 224) return 'private'; // multicast, reserved, broadcast
115
+ return 'public';
116
+ }
117
+
118
+ /** Expand a WHATWG-serialized IPv6 literal (no brackets; IPv4 tails are already hex) to eight groups, or undefined. */
119
+ function ipv6Groups(host) {
120
+ const halves = host.split('::');
121
+ if (halves.length > 2) return undefined;
122
+ const parse = (part) => (part === '' ? [] : part.split(':').map((g) => (/^[0-9a-f]{1,4}$/i.test(g) ? parseInt(g, 16) : NaN)));
123
+ const head = parse(halves[0]);
124
+ const rest = halves.length === 2 ? parse(halves[1]) : [];
125
+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;
126
+ if (fill < 0) return undefined;
127
+ const groups = [...head, ...new Array(fill).fill(0), ...rest];
128
+ if (groups.length !== 8 || groups.some((g) => Number.isNaN(g))) return undefined;
129
+ return groups;
130
+ }
131
+
132
+ /** 'loopback' | 'private' | 'public' for a hostname as WHATWG URL normalizes it (IPv6 keeps its brackets). */
133
+ export function hostClass(rawHost) {
134
+ const host = String(rawHost ?? '').toLowerCase().replace(/\.$/, '');
135
+ if (host === '') return 'private';
136
+ if (host === 'localhost' || host.endsWith('.localhost')) return 'loopback';
137
+ if (host.startsWith('[')) {
138
+ const groups = ipv6Groups(host.slice(1, -1));
139
+ if (!groups) return 'private';
140
+ if (groups.every((g, i) => (i < 7 ? g === 0 : g === 1))) return 'loopback'; // ::1
141
+ if (groups.every((g) => g === 0)) return 'private'; // ::
142
+ if ((groups[0] & 0xfe00) === 0xfc00) return 'private'; // fc00::/7
143
+ if ((groups[0] & 0xffc0) === 0xfe80) return 'private'; // fe80::/10
144
+ if ((groups[0] & 0xff00) === 0xff00) return 'private'; // multicast
145
+ if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff) {
146
+ const mapped = [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff];
147
+ return ipv4Class(mapped) === 'public' ? 'public' : 'private'; // a mapped loopback is never treated as this Mac
148
+ }
149
+ return 'public';
150
+ }
151
+ const octets = ipv4Parts(host);
152
+ if (octets) return host === '0.0.0.0' ? 'loopback' : ipv4Class(octets);
153
+ if (/^[0-9.]+$/.test(host) || /^0x/.test(host)) return 'private'; // numeric shorthands WHATWG did not canonicalize
154
+ if (!host.includes('.')) return 'private'; // single-label intranet names
155
+ if (PRIVATE_SUFFIXES.some((suffix) => host.endsWith(suffix))) return 'private';
156
+ return 'public';
157
+ }
158
+
159
+ /** The person-facing site key: host without one leading "www.", plus a non-default port. */
160
+ export function siteOf(url) {
161
+ const parsed = url instanceof URL ? url : new URL(String(url));
162
+ const host = parsed.hostname.toLowerCase().replace(/^www\./, '');
163
+ return parsed.port ? `${host}:${parsed.port}` : host; // WHATWG URL drops the scheme's default port
164
+ }
165
+
166
+ /**
167
+ * What a `browser_navigate` / `browser_tabs` url names, normalized the way the Mac's address field reads input:
168
+ * `{kind, url?, site?}` with kind loopback | remote | private | file | blank | unsupported | invalid.
169
+ */
170
+ export function classifyUrl(input) {
171
+ if (typeof input !== 'string') return { kind: 'invalid' };
172
+ const text = input.trim();
173
+ if (!text) return { kind: 'invalid' };
174
+ if (text.startsWith('/') || text.startsWith('~')) return { kind: 'file' };
175
+ const port = /^:?(\d{1,5})$/.exec(text);
176
+ if (port) {
177
+ const n = Number(port[1]);
178
+ if (n < 1 || n > 65535) return { kind: 'invalid' };
179
+ return { kind: 'loopback', url: new URL(`http://localhost:${n}`) };
180
+ }
181
+ let url;
182
+ try {
183
+ url = new URL(/^[a-z][a-z0-9+.-]*:/i.test(text) && (text.includes('://') || !/^[^:/]+:\d/.test(text)) ? text : `http://${text}`);
184
+ } catch {
185
+ return { kind: 'invalid' };
186
+ }
187
+ const scheme = url.protocol;
188
+ if (scheme === 'about:') return url.href === 'about:blank' ? { kind: 'blank', url } : { kind: 'unsupported', url };
189
+ if (scheme === 'file:') return { kind: 'file', url };
190
+ if (scheme !== 'http:' && scheme !== 'https:') return { kind: 'unsupported', url };
191
+ if (url.username || url.password) return { kind: 'unsupported', url };
192
+ const cls = hostClass(url.hostname);
193
+ if (cls === 'loopback') return { kind: 'loopback', url };
194
+ if (cls === 'private') return { kind: 'private', url };
195
+ return { kind: 'remote', url, site: siteOf(url) };
196
+ }
197
+
198
+ /** The refusal for a url the plugin never queues, else undefined (the host decides everything else). */
199
+ export function urlProblem(input) {
200
+ const { kind } = classifyUrl(input);
201
+ if (kind === 'invalid') return 'url must be a non-empty address.';
202
+ if (kind === 'private') return PRIVATE_REFUSAL;
203
+ if (kind === 'unsupported') return UNSUPPORTED_REFUSAL;
204
+ return undefined;
205
+ }
206
+
207
+ /** The trailing `(site X)` an ask reason carries for a remote site; the relay and the Mac card parse it. */
208
+ export const SITE_REASON = /\(site ([^()\s]+)\)$/;
209
+
210
+ export function siteFromReason(reason) {
211
+ if (typeof reason !== 'string') return undefined;
212
+ return SITE_REASON.exec(reason.trim())?.[1];
213
+ }
214
+
215
+ /** Shared model-facing preamble: what this browser is and how refs work. Surface-neutral (Mac Preview, CLI host). */
216
+ const GUIDE =
217
+ ' This drives the Picasso browser for this thread (the Preview pane in the Picasso app). Pages on this machine' +
218
+ ' (localhost) and files in the thread’s folder open directly; other http(s) sites open after the person allows' +
219
+ ' the site; private-network addresses never open. Call browser_snapshot first and act on the refs it prints; refs' +
220
+ ' go stale after navigation — take a new snapshot.';
221
+
222
+ const NO_PARAMS = () => ({ type: 'object', properties: {}, additionalProperties: false });
223
+
224
+ export const TOOL_SPECS = [
225
+ {
226
+ name: 'browser_back',
227
+ description: `Go back one page in the current tab's history.${GUIDE}`,
228
+ parameters: NO_PARAMS(),
229
+ },
230
+ {
231
+ name: 'browser_click',
232
+ description: `Click an element in the Preview, by snapshot ref.${GUIDE}`,
233
+ parameters: {
234
+ type: 'object',
235
+ properties: { ref: { type: 'string', description: 'Element ref from the latest browser_snapshot (e.g. "e12").' } },
236
+ required: ['ref'],
237
+ additionalProperties: false,
238
+ },
239
+ },
240
+ {
241
+ name: 'browser_console',
242
+ description: `Read console messages, page errors and failed network requests captured from the current tab.${GUIDE}`,
243
+ parameters: {
244
+ type: 'object',
245
+ properties: {
246
+ sinceId: { type: 'integer', description: 'Only entries after this id (see the last line of a previous result).' },
247
+ errorsOnly: { type: 'boolean', description: 'Keep only error-level messages and failed requests.' },
248
+ },
249
+ additionalProperties: false,
250
+ },
251
+ },
252
+ {
253
+ name: 'browser_forward',
254
+ description: `Go forward one page in the current tab's history.${GUIDE}`,
255
+ parameters: NO_PARAMS(),
256
+ },
257
+ {
258
+ name: 'browser_navigate',
259
+ description: `Open a page in the current Preview tab.${GUIDE}`,
260
+ parameters: {
261
+ type: 'object',
262
+ properties: { url: { type: 'string', description: 'Address to open: a public http(s) URL (https://example.com), a localhost URL (http://localhost:3000) or a file inside the thread folder.' } },
263
+ required: ['url'],
264
+ additionalProperties: false,
265
+ },
266
+ },
267
+ {
268
+ name: 'browser_press_key',
269
+ description: `Press one key in the Preview: Enter, Tab, Escape, Backspace or an arrow key.${GUIDE}`,
270
+ parameters: {
271
+ type: 'object',
272
+ properties: { key: { type: 'string', enum: [...ALLOWED_KEYS], description: 'One of Enter, Tab, Escape, Backspace, ArrowUp, ArrowDown, ArrowLeft, ArrowRight.' } },
273
+ required: ['key'],
274
+ additionalProperties: false,
275
+ },
276
+ },
277
+ {
278
+ name: 'browser_reload',
279
+ description: `Reload the current tab's page.${GUIDE}`,
280
+ parameters: NO_PARAMS(),
281
+ },
282
+ {
283
+ name: 'browser_screenshot',
284
+ description: `Capture the current tab's visible viewport as a PNG, returned as an image when the model accepts images and described in text otherwise.${GUIDE}`,
285
+ parameters: NO_PARAMS(),
286
+ },
287
+ {
288
+ name: 'browser_scroll',
289
+ description: `Scroll the page (or one element) up or down about a viewport.${GUIDE}`,
290
+ parameters: {
291
+ type: 'object',
292
+ properties: {
293
+ direction: { type: 'string', enum: ['up', 'down'], description: 'Scroll direction.' },
294
+ ref: { type: 'string', description: 'Optional element ref to scroll inside.' },
295
+ },
296
+ required: ['direction'],
297
+ additionalProperties: false,
298
+ },
299
+ },
300
+ {
301
+ name: 'browser_snapshot',
302
+ description: `Read the current tab as an accessibility-tree style outline: one indented line per landmark, heading, text block and control with its role, name and states, and [ref=eN] on every element you can act on (e.g. "- button \"Save\" [ref=e12]").${GUIDE}`,
303
+ parameters: NO_PARAMS(),
304
+ },
305
+ {
306
+ name: 'browser_tabs',
307
+ description: `List, open, select or close Preview tabs for this thread. The other browser tools act on the selected tab; tab 0 is the thread's main tab and cannot be closed.${GUIDE}`,
308
+ parameters: {
309
+ type: 'object',
310
+ properties: {
311
+ action: { type: 'string', enum: [...TAB_ACTIONS], description: 'list the tabs, open a new one, select one, or close one.' },
312
+ index: { type: 'integer', description: 'Tab index (0-based) for select and close.' },
313
+ url: { type: 'string', description: 'Address to open in the new tab (action "new" only).' },
314
+ },
315
+ required: ['action'],
316
+ additionalProperties: false,
317
+ },
318
+ },
319
+ {
320
+ name: 'browser_type',
321
+ description: `Type text into an input, textarea or editable element in the Preview.${GUIDE}`,
322
+ parameters: {
323
+ type: 'object',
324
+ properties: {
325
+ ref: { type: 'string', description: 'Element ref from the latest browser_snapshot.' },
326
+ text: { type: 'string', description: 'Text to enter (replaces the current value).' },
327
+ submit: { type: 'boolean', description: 'Submit the enclosing form (or press Enter) after typing.' },
328
+ },
329
+ required: ['ref', 'text'],
330
+ additionalProperties: false,
331
+ },
332
+ },
333
+ {
334
+ name: 'browser_wait_for',
335
+ description: `Wait until text appears or disappears on the current tab's page, or for a number of seconds (at most 30). Give at least one of text, textGone or time.${GUIDE}`,
336
+ parameters: {
337
+ type: 'object',
338
+ properties: {
339
+ text: { type: 'string', description: 'Wait until this text appears on the page.' },
340
+ textGone: { type: 'string', description: 'Wait until this text is no longer on the page.' },
341
+ time: { type: 'number', description: 'Seconds to wait (0.1 to 30); with text or textGone, the longest to wait.' },
342
+ },
343
+ additionalProperties: false,
344
+ },
345
+ },
346
+ ];
347
+
348
+ /** Reason the approval card shows for one gated call. A remote site ends `(site X)` (SITE_REASON). */
349
+ export function askReason(exec) {
350
+ const args = isRecord(exec.arguments) ? exec.arguments : {};
351
+ const open = (raw, where) => {
352
+ const target = classifyUrl(raw);
353
+ if (target.kind === 'remote') return `Open ${target.url.href} ${where} (site ${target.site})`;
354
+ return `Open ${typeof raw === 'string' ? raw : 'a page'} ${where}`;
355
+ };
356
+ switch (exec.name) {
357
+ case 'browser_navigate': return open(args.url, 'in the Preview');
358
+ case 'browser_tabs': return open(args.url, 'in a new Preview tab');
359
+ case 'browser_click': return `Click ${typeof args.ref === 'string' ? args.ref : 'an element'} in the Preview`;
360
+ case 'browser_type': return `Type into ${typeof args.ref === 'string' ? args.ref : 'a field'} in the Preview`;
361
+ case 'browser_press_key': return `Press ${typeof args.key === 'string' ? args.key : 'a key'} in the Preview`;
362
+ default: return `Run ${exec.name} in the Preview`;
363
+ }
364
+ }
365
+
366
+ /** Whether one call needs the person: the four mutating tools, and browser_tabs opening a URL. */
367
+ export function needsAsk(exec) {
368
+ if (ASK_TOOLS.has(exec.name)) return true;
369
+ if (exec.name !== 'browser_tabs') return false;
370
+ const args = isRecord(exec.arguments) ? exec.arguments : {};
371
+ return args.action === 'new' && typeof args.url === 'string' && args.url.trim() !== '';
372
+ }
373
+
374
+ /**
375
+ * The `tools/pre-execute` listener: ask for page-changing calls, delegate everything else. On the CLI host an address
376
+ * never asks as a tool: localhost and thread files open directly and a public site asks its own question (CliSites).
377
+ */
378
+ export function preExecute(exec, next, host) {
379
+ if (!needsAsk(exec)) return next();
380
+ if (host === 'cli' && (exec.name === 'browser_navigate' || exec.name === 'browser_tabs')) return next();
381
+ const reason = askReason(exec);
382
+ return Promise.resolve({ kind: 'ask', reason, displayReason: { en: reason } });
383
+ }
384
+
385
+ /**
386
+ * The action queue the Mac drains through `picassoBrowser/*`. `now` is injectable for tests. Tool calls arrive via
387
+ * `issue()`; the poller drains via `take()`; results land via `complete()`. Wire params are simple identifiers only —
388
+ * the Typert gateway reads SRC method signatures off the function source, and a trailing `signal` is the transport
389
+ * cancellation slot, never a wire field.
390
+ */
391
+ export class BrowserActions {
392
+ constructor(options = {}) {
393
+ this.now = options.now ?? Date.now;
394
+ this.noPollerMs = options.noPollerMs ?? NO_POLLER_MS;
395
+ this.actionTimeoutMs = options.actionTimeoutMs ?? ACTION_TIMEOUT_MS;
396
+ this.closedMessage = options.closedMessage ?? APP_CLOSED;
397
+ this.timeoutMessage = options.timeoutMessage ?? ACTION_TIMEOUT;
398
+ this.queue = [];
399
+ this.inflight = new Map();
400
+ this.cancelledIds = [];
401
+ this.waiters = new Set();
402
+ this.lastPollAt = 0;
403
+ this.seq = 0;
404
+ }
405
+
406
+ // ── Remote surface ──────────────────────────────────────────────────────────────────────────────────────────
407
+
408
+ /** Long-poll for queued work; resolves early with whatever arrived, else empty after timeoutMs. */
409
+ async take(timeoutMs, signal) {
410
+ this.lastPollAt = this.now();
411
+ const ms = typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : TAKE_DEFAULT_MS;
412
+ const deadline = this.now() + ms;
413
+ const flush = () => {
414
+ const actions = this.queue.splice(0);
415
+ const cancelled = this.cancelledIds.splice(0);
416
+ for (const action of actions) this.inflight.set(action.actionId, action);
417
+ return { actions: actions.map(({ resolve: _r, reject: _j, timer: _t, onAbort: _a, signal: _s, result: _p, ...wire }) => wire), cancelled };
418
+ };
419
+ let out = flush();
420
+ if (out.actions.length > 0 || out.cancelled.length > 0) return out;
421
+ return await new Promise((resolve) => {
422
+ const settle = () => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); this.waiters.delete(entry); resolve(flush()); };
423
+ const timer = setTimeout(settle, Math.max(0, deadline - this.now()));
424
+ const onAbort = () => settle();
425
+ signal?.addEventListener('abort', onAbort, { once: true });
426
+ const entry = { settle };
427
+ this.waiters.add(entry);
428
+ });
429
+ }
430
+
431
+ /**
432
+ * Deliver one action's outcome back to its tool call. AO-006.07: the completion is bound to the
433
+ * issuing session — `sessionId` (which the relay fills from ITS pending record, not from the
434
+ * caller's claim) must equal the session the action was issued for, else `session-mismatch`.
435
+ */
436
+ complete(actionId, ok, value, error, sessionId) {
437
+ const action = this.inflight.get(actionId);
438
+ if (action === undefined) throw new BrowserError('unknown-action', `No pending browser action "${String(actionId)}".`, { actionId });
439
+ if (typeof sessionId !== 'string' || sessionId === '') {
440
+ throw new BrowserError('session-required', `Completing browser action "${String(actionId)}" requires the issuing sessionId.`, { actionId });
441
+ }
442
+ if (sessionId !== action.sessionId) {
443
+ throw new BrowserError('session-mismatch', `Browser action "${String(actionId)}" belongs to a different session.`, { actionId });
444
+ }
445
+ clearTimeout(action.timer);
446
+ action.onAbort && action.signal?.removeEventListener('abort', action.onAbort);
447
+ this.inflight.delete(actionId);
448
+ if (ok === true) action.resolve(normalizeValue(value));
449
+ else action.reject(new Error(typeof error === 'string' && error ? error : 'The browser action failed.'));
450
+ return {};
451
+ }
452
+
453
+ // ── Tool side ───────────────────────────────────────────────────────────────────────────────────────────────
454
+
455
+ /**
456
+ * Queue one action for `sessionId` and wait for its outcome. Rejects fast when no poller is live, after the
457
+ * per-action timeout, or when the tool call's signal aborts (the action is then listed in the next `cancelled`).
458
+ */
459
+ issue(sessionId, callId, tool, args, signal, extra) {
460
+ if (this.now() - this.lastPollAt > this.noPollerMs) return Promise.reject(new Error(this.closedMessage));
461
+ const actionId = `ba-${++this.seq}`;
462
+ const action = { actionId, sessionId, callId, tool, args: isRecord(args) ? args : {}, issuedAt: this.now(), ...(isRecord(extra) ? extra : {}) };
463
+ const promise = new Promise((resolve, reject) => {
464
+ action.resolve = resolve;
465
+ action.reject = reject;
466
+ action.timer = setTimeout(() => this.expire(actionId, new Error(this.timeoutMessage)), this.actionTimeoutMs);
467
+ action.timer.unref?.();
468
+ if (signal) {
469
+ action.signal = signal;
470
+ action.onAbort = () => this.expire(actionId, aborted(signal));
471
+ signal.addEventListener('abort', action.onAbort, { once: true });
472
+ }
473
+ });
474
+ action.result = promise;
475
+ this.queue.push(action);
476
+ for (const waiter of [...this.waiters]) waiter.settle();
477
+ return { actionId, promise };
478
+ }
479
+
480
+ /** Settle a queued or in-flight action as failed and report it cancelled to the next poller. */
481
+ expire(actionId, error) {
482
+ let action = this.inflight.get(actionId);
483
+ if (action !== undefined) this.inflight.delete(actionId);
484
+ else {
485
+ const index = this.queue.findIndex((entry) => entry.actionId === actionId);
486
+ if (index < 0) return;
487
+ action = this.queue.splice(index, 1)[0];
488
+ }
489
+ clearTimeout(action.timer);
490
+ action.onAbort && action.signal?.removeEventListener('abort', action.onAbort);
491
+ this.cancelledIds.push(actionId);
492
+ action.reject(error);
493
+ for (const waiter of [...this.waiters]) waiter.settle();
494
+ }
495
+ }
496
+
497
+ function aborted(signal) {
498
+ const reason = signal?.reason;
499
+ return reason instanceof Error ? reason : new Error('The tool call was cancelled.');
500
+ }
501
+
502
+ /** `{text, image?}` from the Mac, normalized to the canonical value a tool result carries. */
503
+ export function normalizeValue(value) {
504
+ if (!isRecord(value) || typeof value.text !== 'string') return { text: '' };
505
+ const image = isRecord(value.image) && typeof value.image.data === 'string' && typeof value.image.mimeType === 'string'
506
+ ? { data: value.image.data, mimeType: value.image.mimeType }
507
+ : undefined;
508
+ return { text: value.text, ...(image ? { image } : {}) };
509
+ }
510
+
511
+ /** Snapshot refs look like e1–e99999; anything else never reaches the page (and never a JS string). */
512
+ const REF_SHAPE = /^e[1-9][0-9]{0,4}$/;
513
+ export const REF_PROBLEM = 'ref must be a snapshot ref like "e12".';
514
+
515
+ function refProblem(ref, required) {
516
+ if (typeof ref !== 'string' || !REF_SHAPE.test(ref)) return required ? REF_PROBLEM : ref === undefined ? undefined : REF_PROBLEM;
517
+ return undefined;
518
+ }
519
+
520
+ /** Validate args the plugin itself owns before an action is queued; returns the failure message or undefined. */
521
+ export function argProblem(tool, args) {
522
+ if (tool === 'browser_navigate') return urlProblem(args.url);
523
+ if (tool === 'browser_press_key' && !ALLOWED_KEYS.has(args.key)) {
524
+ return `key must be one of ${[...ALLOWED_KEYS].join(', ')}.`;
525
+ }
526
+ if (tool === 'browser_click' || tool === 'browser_type') return refProblem(args.ref, true);
527
+ if (tool === 'browser_scroll') {
528
+ if (args.direction !== 'up' && args.direction !== 'down') return 'direction must be "up" or "down".';
529
+ return refProblem(args.ref, false);
530
+ }
531
+ if (tool === 'browser_tabs') {
532
+ if (!TAB_ACTIONS.includes(args.action)) return `action must be one of ${TAB_ACTIONS.join(', ')}.`;
533
+ if (args.url !== undefined && args.action !== 'new') return 'url is only for action "new".';
534
+ if (args.action === 'new' && args.url !== undefined) return urlProblem(args.url);
535
+ if (args.action === 'select' || args.action === 'close') {
536
+ if (!Number.isInteger(args.index) || args.index < 0) return 'index must be a tab index (0 or more).';
537
+ if (args.action === 'close' && args.index === 0) return 'Tab 0 is the thread’s main tab and cannot be closed.';
538
+ }
539
+ return undefined;
540
+ }
541
+ if (tool === 'browser_wait_for') {
542
+ const { text, textGone, time } = args;
543
+ if (text === undefined && textGone === undefined && time === undefined) return 'Give at least one of text, textGone or time.';
544
+ for (const [key, value] of [['text', text], ['textGone', textGone]]) {
545
+ if (value === undefined) continue;
546
+ if (typeof value !== 'string' || value.trim() === '') return `${key} must be non-empty text.`;
547
+ if (value.length > WAIT_TEXT_MAX) return `${key} must be at most ${WAIT_TEXT_MAX} characters.`;
548
+ }
549
+ if (time !== undefined && (typeof time !== 'number' || !Number.isFinite(time) || time < WAIT_MIN_SECONDS || time > WAIT_MAX_SECONDS)) {
550
+ return `time must be a number of seconds from ${WAIT_MIN_SECONDS} to ${WAIT_MAX_SECONDS}.`;
551
+ }
552
+ }
553
+ return undefined;
554
+ }
555
+
556
+ /**
557
+ * Run one tool call: validate, queue, await the Mac's outcome. Returns `{text, image?}` (normalized Mac value).
558
+ * `exec.agent.id` is the session id (dsh's Agent id is the SessionId) — the action's routing key to the Mac.
559
+ */
560
+ export async function runAction(actions, exec, cliHost) {
561
+ const args = isRecord(exec.arguments) ? exec.arguments : {};
562
+ const problem = argProblem(exec.name, args);
563
+ if (problem) throw new Error(problem);
564
+ const sessionId = exec.agent?.id;
565
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('browser actions need an agent session');
566
+ const extra = cliHost === undefined ? undefined : await cliHost.admit(exec, args, sessionId);
567
+ const issued = actions.issue(sessionId, String(exec.callId ?? ''), exec.name, args, exec.signal, extra);
568
+ // No poller: `issue` answers with the rejected promise itself (its message is the model's reason).
569
+ if (typeof issued?.then === 'function') return await issued;
570
+ return await issued.promise;
571
+ }
572
+
573
+ // ── CLI host: the person's sites, kept by the plugin (the Mac app keeps them itself) ─────────────────────────
574
+
575
+ export const SITES_FILE_VERSION = 1;
576
+
577
+ /** The always-allowed sites in `<picassoHome>/settings/browser-sites.json` (`{version: 1, sites: [{site, addedAt}]}`). */
578
+ export function readAllowedSites(file) {
579
+ if (typeof file !== 'string' || file === '') return [];
580
+ try {
581
+ const stored = JSON.parse(readFileSync(file, 'utf8'));
582
+ const sites = Array.isArray(stored?.sites) ? stored.sites : [];
583
+ return [...new Set(sites.map((entry) => String(entry?.site ?? '').toLowerCase()).filter((site) => site !== ''))].sort();
584
+ } catch {
585
+ return [];
586
+ }
587
+ }
588
+
589
+ /** Add one site to the shared list (atomic write, sorted, earlier `addedAt` kept), as the Mac's Settings does. */
590
+ export function addAllowedSite(file, site, now = () => new Date()) {
591
+ const key = String(site ?? '').toLowerCase();
592
+ if (typeof file !== 'string' || file === '' || key === '') return false;
593
+ let previous = [];
594
+ try {
595
+ const stored = JSON.parse(readFileSync(file, 'utf8'));
596
+ previous = Array.isArray(stored?.sites) ? stored.sites.filter((entry) => typeof entry?.site === 'string' && entry.site !== '') : [];
597
+ } catch {
598
+ previous = [];
599
+ }
600
+ if (previous.some((entry) => entry.site.toLowerCase() === key)) return true;
601
+ // ISO 8601 without fractions, as the Mac's ISO8601DateFormatter writes it.
602
+ const stamp = now().toISOString().replace(/\.\d{3}Z$/, 'Z');
603
+ const sites = [...previous.map((entry) => ({ addedAt: typeof entry.addedAt === 'string' ? entry.addedAt : stamp, site: entry.site.toLowerCase() })), { addedAt: stamp, site: key }]
604
+ .sort((a, b) => a.site.localeCompare(b.site));
605
+ mkdirSync(dirname(file), { recursive: true });
606
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
607
+ writeFileSync(temp, `${JSON.stringify({ sites, version: SITES_FILE_VERSION }, null, 2)}\n`, { mode: 0o600 });
608
+ renameSync(temp, file);
609
+ return true;
610
+ }
611
+
612
+ /** Remove one site from the shared list (the Mac's Settings › Browser remove). True when it was listed. */
613
+ export function removeAllowedSite(file, site) {
614
+ const key = String(site ?? '').toLowerCase();
615
+ if (typeof file !== 'string' || file === '' || key === '') return false;
616
+ let stored;
617
+ try {
618
+ stored = JSON.parse(readFileSync(file, 'utf8'));
619
+ } catch {
620
+ return false;
621
+ }
622
+ const sites = Array.isArray(stored?.sites) ? stored.sites.filter((entry) => typeof entry?.site === 'string' && entry.site !== '') : [];
623
+ const kept = sites.filter((entry) => entry.site.toLowerCase() !== key);
624
+ if (kept.length === sites.length) return false;
625
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
626
+ writeFileSync(temp, `${JSON.stringify({ sites: kept, version: SITES_FILE_VERSION }, null, 2)}\n`, { mode: 0o600 });
627
+ renameSync(temp, file);
628
+ return true;
629
+ }
630
+
631
+ /** The site-question options, in the Mac card's order. */
632
+ export const SITE_ALLOW_ONCE = 'Allow once';
633
+ export const SITE_DENY = 'Deny';
634
+ export function siteAlwaysLabel(site) {
635
+ return `Always allow ${site}`;
636
+ }
637
+
638
+ /** The engine user-questions request that asks about one site (the TUI shows it as a question card). */
639
+ export function siteQuestion(site, url, exec) {
640
+ return {
641
+ questions: [
642
+ {
643
+ id: 'site',
644
+ header: 'Browser',
645
+ question: `Open ${site}?`,
646
+ detail: `The agent wants to open ${url} in its browser. Picasso hasn't opened ${site} before. Allow it in this thread only, or on every thread from now on.`,
647
+ options: [
648
+ { label: SITE_ALLOW_ONCE, description: 'This thread only, until Picasso quits.' },
649
+ { label: siteAlwaysLabel(site), description: 'Every thread from now on (Settings › Browser in Picasso for Mac lists it too).' },
650
+ { label: SITE_DENY, description: 'The agent is told you said no.' },
651
+ ],
652
+ },
653
+ ],
654
+ ...(exec?.agent !== undefined ? { agent: exec.agent } : {}),
655
+ ...(exec?.signal !== undefined ? { signal: exec.signal } : {}),
656
+ };
657
+ }
658
+
659
+ /** `once` | `always` | `deny` from the engine's answer batch; anything but a pick (a skip, own words) is a deny. */
660
+ export function siteAnswer(answer, site) {
661
+ const answers = Array.isArray(answer?.answers) ? answer.answers : Array.isArray(answer) ? answer : [];
662
+ const pick = answers.find((item) => item?.id === 'site') ?? answers[0];
663
+ const label = Array.isArray(pick?.selected) ? pick.selected.find((value) => typeof value === 'string') : undefined;
664
+ if (label === SITE_ALLOW_ONCE) return 'once';
665
+ if (label === siteAlwaysLabel(site)) return 'always';
666
+ return 'deny';
667
+ }
668
+
669
+ export function deniedSiteMessage(site) {
670
+ return `The person didn't allow ${site}. Don't retry it unless they ask; they can allow it with \`picasso browser sites add ${site}\` (or in Picasso for Mac, Settings › Browser).`;
671
+ }
672
+
673
+ export function unaskedSiteMessage(site) {
674
+ return `${site} isn't an allowed site yet, and no one could be asked in this session. Allow it with \`picasso browser sites add ${site}\` (or in Picasso for Mac, Settings › Browser), then try again.`;
675
+ }
676
+
677
+ /** The path a file address names (`/…`, `~/…`, `file:` URLs, or a relative path that exists in the thread folder). */
678
+ export function fileTarget(input, cwd) {
679
+ if (typeof input !== 'string') return undefined;
680
+ const text = input.trim();
681
+ if (text.startsWith('~')) return join(homedir(), text.slice(1).replace(/^[\\/]/, ''));
682
+ if (text.startsWith('/')) return text;
683
+ if (/^file:/i.test(text)) {
684
+ try {
685
+ return fileURLToPath(new URL(text));
686
+ } catch {
687
+ return undefined;
688
+ }
689
+ }
690
+ if (typeof cwd === 'string' && cwd !== '' && !/^[a-z][a-z0-9+.-]*:/i.test(text) && !/^:?\d{1,5}$/.test(text) && /[\\/]|\.[a-z0-9]+$/i.test(text)) {
691
+ const candidate = resolve(cwd, text.split(/[?#]/)[0]);
692
+ if (existsSync(candidate)) return candidate;
693
+ }
694
+ return undefined;
695
+ }
696
+
697
+ /** Whether `path` (resolved through symlinks where it exists) is inside the folder `cwd`. */
698
+ export function insideFolder(path, cwd) {
699
+ if (typeof path !== 'string' || typeof cwd !== 'string' || cwd === '' || !isAbsolute(path)) return false;
700
+ const real = (value) => {
701
+ try {
702
+ return realpathSync(value);
703
+ } catch {
704
+ return resolve(value);
705
+ }
706
+ };
707
+ const rel = relative(real(cwd), real(path));
708
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel) && !rel.startsWith(`..${sep}`));
709
+ }
710
+
711
+ /**
712
+ * The CLI host's site rules. `admit(exec, args, sessionId)` runs before an action is queued: files outside the thread
713
+ * folder are refused, a public site not yet allowed asks the person once (deduplicated per thread and site), and the
714
+ * returned `{cwd, sites}` rides the action so the executor can refuse every other load.
715
+ */
716
+ export class CliSites {
717
+ constructor(options = {}) {
718
+ this.sitesFile = options.sitesFile;
719
+ this.questions = options.questions ?? (() => undefined);
720
+ this.cwdOf = options.cwdOf ?? (() => undefined);
721
+ this.once = new Map();
722
+ this.asking = new Map();
723
+ }
724
+
725
+ allowed(sessionId) {
726
+ return [...new Set([...readAllowedSites(this.sitesFile), ...(this.once.get(sessionId) ?? [])])].sort();
727
+ }
728
+
729
+ isAllowed(site, sessionId) {
730
+ const key = String(site).toLowerCase();
731
+ return this.once.get(sessionId)?.has(key) === true || readAllowedSites(this.sitesFile).includes(key);
732
+ }
733
+
734
+ grantOnce(sessionId, site) {
735
+ let sites = this.once.get(sessionId);
736
+ if (sites === undefined) this.once.set(sessionId, (sites = new Set()));
737
+ sites.add(String(site).toLowerCase());
738
+ }
739
+
740
+ /** The URL a navigate-like call opens, else undefined (snapshot, click, …). */
741
+ static target(exec, args) {
742
+ if (exec.name === 'browser_navigate') return args.url;
743
+ if (exec.name === 'browser_tabs' && args.action === 'new' && typeof args.url === 'string' && args.url.trim() !== '') return args.url;
744
+ return undefined;
745
+ }
746
+
747
+ async admit(exec, args, sessionId) {
748
+ const cwd = this.cwdOf(exec);
749
+ const input = CliSites.target(exec, args);
750
+ if (input !== undefined) {
751
+ const file = fileTarget(input, cwd);
752
+ if (file !== undefined) {
753
+ if (!insideFolder(file, cwd)) throw new Error(FILE_OUTSIDE_REFUSAL);
754
+ } else {
755
+ const target = classifyUrl(input);
756
+ if (target.kind === 'remote' && !this.isAllowed(target.site, sessionId)) await this.ask(exec, sessionId, target.site, target.url.href);
757
+ }
758
+ }
759
+ return { ...(typeof cwd === 'string' && cwd !== '' ? { cwd } : {}), sites: this.allowed(sessionId) };
760
+ }
761
+
762
+ async ask(exec, sessionId, site, href) {
763
+ const key = `${sessionId}\u0000${site}`;
764
+ let pending = this.asking.get(key);
765
+ if (pending === undefined) {
766
+ pending = this.askOnce(exec, sessionId, site, href).finally(() => this.asking.delete(key));
767
+ this.asking.set(key, pending);
768
+ }
769
+ await pending;
770
+ }
771
+
772
+ async askOnce(exec, sessionId, site, href) {
773
+ const questions = this.questions();
774
+ if (questions === undefined || typeof questions.ask !== 'function') throw new Error(unaskedSiteMessage(site));
775
+ let answer;
776
+ try {
777
+ answer = await questions.ask(siteQuestion(site, href, exec));
778
+ } catch (error) {
779
+ if (exec.signal?.aborted) throw error;
780
+ throw new Error(unaskedSiteMessage(site));
781
+ }
782
+ const choice = siteAnswer(answer, site);
783
+ if (choice === 'deny') throw new Error(deniedSiteMessage(site));
784
+ if (choice === 'always') {
785
+ try {
786
+ addAllowedSite(this.sitesFile, site);
787
+ } catch {
788
+ // The list could not be written: the site is still allowed in this thread.
789
+ }
790
+ }
791
+ this.grantOnce(sessionId, site);
792
+ }
793
+ }
794
+
795
+ /** The tool definitions registered on ctx.tools. `adapter` is createMcpToolDefinition, or undefined for text-only. */
796
+ export function buildTools(ctx, adapter, actions, cliHost) {
797
+ return TOOL_SPECS.map((spec) => {
798
+ if (adapter !== undefined) {
799
+ return adapter(ctx, {
800
+ name: spec.name,
801
+ rawName: spec.name,
802
+ description: spec.description,
803
+ inputSchema: spec.parameters,
804
+ async call(_args, exec) {
805
+ const result = await runAction(actions, exec, cliHost);
806
+ return {
807
+ content: [
808
+ { type: 'text', text: result.text },
809
+ ...(result.image ? [{ type: 'image', data: result.image.data, mimeType: result.image.mimeType }] : []),
810
+ ],
811
+ };
812
+ },
813
+ });
814
+ }
815
+ return {
816
+ name: spec.name,
817
+ description: spec.description,
818
+ parameters: spec.parameters,
819
+ output: {
820
+ schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
821
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : '' }],
822
+ },
823
+ async execute(_args, exec) {
824
+ if (spec.name === 'browser_screenshot') throw new Error('Screenshots need this dsh build\u2019s image support; other browser tools still work.');
825
+ const result = await runAction(actions, exec, cliHost);
826
+ return { text: result.image ? `${result.text}\n(image omitted: no image projection available)` : result.text };
827
+ },
828
+ };
829
+ });
830
+ }
831
+
832
+ /** Import one of dsh's bundled packages from a path-loaded plugin: anchor createRequire at the dsh bin's realpath. */
833
+ export async function dshModule(dshBin, specifier) {
834
+ const require = createRequire(dshBin);
835
+ return import(pathToFileURL(require.resolve(specifier)).href);
836
+ }
837
+
838
+ /**
839
+ * Where to resolve dsh's bundled packages from: the configured bin (the relay passes its realpath), else the running
840
+ * engine's own entry (the CLI launches dsh, so `process.argv[1]` is its bin) and install dir, else the Homebrew bin.
841
+ */
842
+ export function dshBinCandidates(config, argv = process.argv, env = process.env) {
843
+ const out = [];
844
+ if (typeof config?.dshBin === 'string' && config.dshBin) out.push(config.dshBin);
845
+ if (typeof argv?.[1] === 'string' && argv[1]) {
846
+ try {
847
+ out.push(realpathSync(argv[1]));
848
+ } catch {
849
+ out.push(argv[1]);
850
+ }
851
+ }
852
+ if (typeof env?.PICASSO_DSH_INSTALL_DIR === 'string' && env.PICASSO_DSH_INSTALL_DIR) out.push(join(env.PICASSO_DSH_INSTALL_DIR, 'package.json'));
853
+ out.push('/opt/homebrew/bin/dsh');
854
+ return [...new Set(out)];
855
+ }
856
+
857
+ /** The working directory of the calling agent's session, best effort. */
858
+ function cwdFor(ctx, exec) {
859
+ const session = exec?.agent?.session;
860
+ try {
861
+ const service = ctx.get?.('workingDirectory') ?? ctx.workingDirectory;
862
+ const cwd = service?.get?.(session);
863
+ if (typeof cwd === 'string' && cwd) return cwd;
864
+ } catch {
865
+ // fall through to the session's own cwd
866
+ }
867
+ return typeof session?.cwd === 'string' && session.cwd ? session.cwd : undefined;
868
+ }
869
+
870
+ export async function apply(ctx, config) {
871
+ const host = config?.host === 'cli' ? 'cli' : 'mac';
872
+ const actions = new BrowserActions(host === 'cli' ? { closedMessage: CLI_HOST_GONE, timeoutMessage: CLI_ACTION_TIMEOUT } : {});
873
+ const service = actions;
874
+ service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
875
+ ctx.provide(SERVICE_KEY, service);
876
+ let adapter;
877
+ const failures = [];
878
+ for (const bin of host === 'cli' ? dshBinCandidates(config) : [config?.dshBin ?? '/opt/homebrew/bin/dsh']) {
879
+ try {
880
+ const module = await dshModule(bin, '@deepseek-ai/dsh-mcp-client');
881
+ if (typeof module.createMcpToolDefinition !== 'function') throw new Error('no export');
882
+ adapter = module.createMcpToolDefinition;
883
+ break;
884
+ } catch (error) {
885
+ failures.push(error instanceof Error ? error.message : String(error));
886
+ }
887
+ }
888
+ if (adapter === undefined) console.warn(`${name}: image projection unavailable (${failures.join('; ')}); registering text-only browser tools`);
889
+ const cliHost = host === 'cli'
890
+ ? new CliSites({
891
+ sitesFile: typeof config?.sitesFile === 'string' ? config.sitesFile : undefined,
892
+ questions: () => {
893
+ try {
894
+ return ctx.get?.('userQuestions') ?? ctx.userQuestions;
895
+ } catch {
896
+ return undefined;
897
+ }
898
+ },
899
+ cwdOf: (exec) => cwdFor(ctx, exec),
900
+ })
901
+ : undefined;
902
+ for (const tool of buildTools(ctx, adapter, actions, cliHost)) ctx.tools.register(tool);
903
+ ctx.on('tools/pre-execute', (exec, next) => preExecute(exec, next, host));
904
+ }
905
+
906
+ Object.defineProperty(BrowserActions.prototype, REMOTE_METHOD_DESCRIPTOR, {
907
+ configurable: true,
908
+ value: Object.freeze({
909
+ version: 1,
910
+ methods: Object.freeze([
911
+ Object.freeze({ method: 'take', invocation: Object.freeze({ kind: 'direct' }) }),
912
+ Object.freeze({ method: 'complete', invocation: Object.freeze({ kind: 'direct' }) }),
913
+ ]),
914
+ }),
915
+ });