turno-cli 0.4.0 → 0.5.1

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.
@@ -1,459 +1,32 @@
1
- import { writeFileSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join, resolve } from "node:path";
4
1
  import { readProcTable } from "turno-core/process";
5
2
  import { gatewayUrl } from "../../agents/adapter.js";
6
3
  import { loadManifest, servesProfile } from "../../core/manifest.js";
4
+ import { tildify } from "../../core/paths.js";
7
5
  import { packageInfo } from "../../core/version.js";
8
- import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
6
+ import { str } from "../args.js";
9
7
  import { Exit } from "../exit.js";
10
- import { CliError, columns, examplesBlock, fail } from "../io.js";
11
- import { emit, jsonArg, jsonOutput } from "../output.js";
12
- import { tildify } from "../../core/paths.js";
8
+ import { CliError } from "../io.js";
13
9
  import { dropSaved, identityServer, ownerName, readSaved, sessionFile, sessionName, sessionOwner, sweepSaved, withLock, writeSaved, } from "./browser-do-session.js";
14
- import { callArguments, callerProfile, gatewayMessage } from "./mcp-call.js";
15
- /**
16
- * `turno browser do <id> <action>`: one browser action on an identity's browser from the shell,
17
- * for coding agents that prefer commands over MCP tools. Each action is one stock (or turno)
18
- * tool call through mcpd to the identity's turno-browser-mcp, the server agents use, so every
19
- * rule of the identity applies as it does to an agent: the tab locks or the one-session lease,
20
- * attach mode, read mode's refusals, humanize, recordings, the vault. The session that keeps the
21
- * commands of one agent or shell on one tab is in `browser-do-session.ts`.
22
- *
23
- * The output is short and stable: `url:` and `title:` lines, then what the action returned. The
24
- * code upstream ran and the snapshot file an action saves on the server are left out; a snapshot
25
- * comes from `snapshot` (or `--snapshot` after an action).
26
- */
27
- /** `turno browser do --json`: one object per command. */
28
- export const DO_JSON = jsonOutput([
29
- "identity",
30
- "server",
31
- "profile",
32
- "session",
33
- "action",
34
- "tool",
35
- "ok",
36
- "page",
37
- "result",
38
- "snapshot",
39
- "file",
40
- "notes",
41
- "error",
42
- ]);
43
- async function readStdin() {
44
- const chunks = [];
45
- for await (const c of process.stdin)
46
- chunks.push(c);
47
- return Buffer.concat(chunks).toString("utf8");
48
- }
10
+ import { callerProfile, gatewayMessage } from "./mcp-call.js";
49
11
  export const defaultDoDeps = {
50
12
  owner: (env) => sessionOwner(readProcTable(), process.ppid, Number(env.TURNO_SESSION_PID) || undefined),
51
- stdin: readStdin,
52
- };
53
- /** `read`: the visible text of the page, or of one element. Works in read mode too (no layout: textContent). */
54
- const READ_FUNCTION = "(element) => { const node = element || document.body || document.documentElement; if (!node) return ''; const text = typeof node.innerText === 'string' ? node.innerText : node.textContent; return String(text || '').replace(/[ \\t]+\\n/g, '\\n').replace(/\\n{3,}/g, '\\n\\n').trim(); }";
55
- const DEFAULT_MAX_CHARS = 20_000;
56
- function int(p, name) {
57
- const v = str(p, name);
58
- if (v === undefined)
59
- return undefined;
60
- const n = Number(v);
61
- if (!Number.isInteger(n) || n < 0)
62
- fail(`--${name} must be a whole number, not "${v}"`);
63
- return n;
64
- }
65
- const ACTIONS = {
66
- open: {
67
- synopsis: "<url>",
68
- summary: "go to a URL in the session's tab",
69
- min: 1,
70
- max: 1,
71
- shape: "page",
72
- build: ([url]) => ({ tool: "browser_navigate", args: { url } }),
73
- },
74
- back: {
75
- synopsis: "",
76
- summary: "go back in the tab's history",
77
- min: 0,
78
- max: 0,
79
- shape: "page",
80
- build: () => ({ tool: "browser_navigate_back", args: {} }),
81
- },
82
- snapshot: {
83
- synopsis: "[<ref>] [--depth <n>]",
84
- summary: "the page's accessibility tree with refs (e12) to act on; <ref> limits it to one element",
85
- flags: { depth: { type: "string" } },
86
- min: 0,
87
- max: 1,
88
- shape: "snapshot",
89
- build: ([ref], p) => {
90
- const depth = int(p, "depth");
91
- return {
92
- tool: "browser_snapshot",
93
- args: { ...(ref ? { target: ref } : {}), ...(depth !== undefined ? { depth } : {}) },
94
- };
95
- },
96
- },
97
- read: {
98
- synopsis: "[<ref>] [--max-chars <n>]",
99
- summary: `the visible text of the page or one element (first ${DEFAULT_MAX_CHARS} characters; --max-chars 0 for all)`,
100
- flags: { "max-chars": { type: "string" } },
101
- min: 0,
102
- max: 1,
103
- shape: "read",
104
- build: ([ref]) => ({
105
- tool: "browser_evaluate",
106
- args: { function: READ_FUNCTION, ...(ref ? { target: ref } : {}) },
107
- }),
108
- },
109
- find: {
110
- synopsis: "<text>",
111
- summary: "elements whose text matches, with their refs",
112
- min: 1,
113
- max: 1,
114
- shape: "result",
115
- build: ([text]) => ({ tool: "browser_find", args: { text } }),
116
- },
117
- click: {
118
- synopsis: "<ref> [--double] [--right]",
119
- summary: "click an element",
120
- flags: { double: { type: "boolean" }, right: { type: "boolean" } },
121
- min: 1,
122
- max: 1,
123
- shape: "page",
124
- build: ([target], p) => ({
125
- tool: "browser_click",
126
- args: {
127
- target,
128
- ...(bool(p, "double") ? { doubleClick: true } : {}),
129
- ...(bool(p, "right") ? { button: "right" } : {}),
130
- },
131
- }),
132
- },
133
- type: {
134
- synopsis: "<ref> <text|-> [--submit] [--slowly]",
135
- summary: "fill a field (- reads the text from stdin); --submit presses Enter after",
136
- flags: { submit: { type: "boolean" }, slowly: { type: "boolean" } },
137
- min: 2,
138
- max: 2,
139
- shape: "page",
140
- build: async ([target, text], p, deps) => ({
141
- tool: "browser_type",
142
- args: {
143
- target,
144
- text: text === "-" ? (await deps.stdin()).replace(/\r?\n$/, "") : text,
145
- ...(bool(p, "submit") ? { submit: true } : {}),
146
- ...(bool(p, "slowly") ? { slowly: true } : {}),
147
- },
148
- }),
149
- },
150
- press: {
151
- synopsis: "<key>",
152
- summary: "press a key (Enter, Escape, ArrowDown, Control+a)",
153
- min: 1,
154
- max: 1,
155
- shape: "page",
156
- build: ([key]) => ({ tool: "browser_press_key", args: { key } }),
157
- },
158
- select: {
159
- synopsis: "<ref> <value>...",
160
- summary: "choose options of a select element",
161
- min: 2,
162
- max: 50,
163
- shape: "page",
164
- build: ([target, ...values]) => ({ tool: "browser_select_option", args: { target, values } }),
165
- },
166
- hover: {
167
- synopsis: "<ref>",
168
- summary: "move the pointer over an element",
169
- min: 1,
170
- max: 1,
171
- shape: "page",
172
- build: ([target]) => ({ tool: "browser_hover", args: { target } }),
173
- },
174
- wait: {
175
- synopsis: "[--text <t>] [--gone <t>] [--seconds <n>]",
176
- summary: "wait for text to appear or go, or for some seconds",
177
- flags: { text: { type: "string" }, gone: { type: "string" }, seconds: { type: "string" } },
178
- min: 0,
179
- max: 0,
180
- shape: "page",
181
- build: (_pos, p) => {
182
- const text = str(p, "text");
183
- const gone = str(p, "gone");
184
- const seconds = str(p, "seconds");
185
- if (text === undefined && gone === undefined && seconds === undefined)
186
- fail("wait needs --text, --gone or --seconds");
187
- const time = seconds === undefined ? undefined : Number(seconds);
188
- if (time !== undefined && !(time >= 0))
189
- fail(`--seconds must be a number, not "${seconds}"`);
190
- return {
191
- tool: "browser_wait_for",
192
- args: {
193
- ...(text !== undefined ? { text } : {}),
194
- ...(gone !== undefined ? { textGone: gone } : {}),
195
- ...(time !== undefined ? { time } : {}),
196
- },
197
- };
198
- },
199
- },
200
- screenshot: {
201
- synopsis: "[--out <file.png>] [--full]",
202
- summary: "save a PNG of the tab (default: a file in the temporary folder) and print its path",
203
- flags: { out: { type: "string" }, full: { type: "boolean" } },
204
- min: 0,
205
- max: 0,
206
- shape: "screenshot",
207
- build: (_pos, p) => ({
208
- tool: "browser_take_screenshot",
209
- args: { type: "png", scale: "css", ...(bool(p, "full") ? { fullPage: true } : {}) },
210
- }),
211
- },
212
- tabs: {
213
- synopsis: "[new [<url>] | select <n> | close <n>]",
214
- summary: "the browser's tabs (others' marked in use), or open, pick or close one",
215
- min: 0,
216
- max: 2,
217
- shape: "result",
218
- build: ([what, value]) => {
219
- if (what === undefined || what === "list")
220
- return { tool: "browser_tabs", args: { action: "list" } };
221
- if (what === "new")
222
- return { tool: "browser_tabs", args: { action: "new", ...(value ? { url: value } : {}) } };
223
- if (what === "select" || what === "close") {
224
- const index = Number(value);
225
- if (value === undefined || !Number.isInteger(index) || index < 0)
226
- fail(`tabs ${what} needs a tab number from 'tabs', for example: tabs ${what} 1`);
227
- return { tool: "browser_tabs", args: { action: what, index } };
228
- }
229
- return fail(`tabs takes new, select <n> or close <n>, not "${what}"`);
230
- },
231
- },
232
- login: {
233
- synopsis: "<site>",
234
- summary: "sign in with a vault credential (turno browser vault); the value never reaches the shell",
235
- min: 1,
236
- max: 1,
237
- shape: "result",
238
- build: ([site]) => ({ tool: "browser_login", args: { site } }),
239
- },
240
- call: {
241
- synopsis: "<tool> [--args <json>] [--arg key=value]...",
242
- summary: "any tool of the identity's server, in this session (browser_batch, browser_fill_form...)",
243
- flags: { args: { type: "string" }, arg: { type: "string", multiple: true } },
244
- min: 1,
245
- max: 1,
246
- shape: "raw",
247
- build: ([tool], p) => ({
248
- tool: tool,
249
- args: callArguments(str(p, "args"), p.values.arg ?? []),
250
- }),
251
- },
252
- close: {
253
- synopsis: "",
254
- summary: "close the session's tabs (the whole browser when it serves one session) and end the session",
255
- min: 0,
256
- max: 0,
257
- shape: "result",
258
- build: () => ({ tool: "browser_close", args: {} }),
259
- },
260
13
  };
261
- /** Actions that make no tool call. */
262
- const LOCAL = {
263
- session: { synopsis: "", summary: "which session these commands use, who owns it and how it ends" },
264
- end: { synopsis: "", summary: "end the session now: its tabs stay open and free, the browser keeps running" },
265
- };
266
- const COMMON = {
267
- session: { type: "string" },
268
- profile: { type: "string" },
269
- timeout: { type: "string" },
270
- snapshot: { type: "boolean" },
271
- ...JSON_FLAG,
272
- };
273
- /** Every action name with its synopsis and summary, for the help and for completion. */
274
- export const ACTION_NAMES = [...Object.keys(ACTIONS), ...Object.keys(LOCAL)];
275
- export const DO_FLAG_NAMES = [
276
- "--session",
277
- "--profile",
278
- "--timeout",
279
- "--snapshot",
280
- "--json",
281
- ...new Set(Object.values(ACTIONS)
282
- .flatMap((a) => Object.keys(a.flags ?? {}))
283
- .map((f) => `--${f}`)),
284
- ];
285
- export const DO_SYNOPSIS = "<id> <action> [args] [--session <name>] [--json]";
286
- export const DO_DETAILS = `Runs one action on the identity's browser through mcpd and turno-browser-mcp, the server
14
+ const HELP = {
15
+ intro: `Runs one action on the identity's browser through mcpd and turno-browser-mcp, the server
287
16
  agents use, so the identity's rules apply as they do to an agent's tool call. The identity must
288
- be served by mcpd (its [server.browser-<id>] block in mcp.toml, which turno browser add prints).
289
-
290
- Actions:
291
- ${columns([
292
- ...Object.entries(ACTIONS).map(([n, a]) => [`${n}${a.synopsis ? ` ${a.synopsis}` : ""}`, a.summary]),
293
- ...Object.entries(LOCAL).map(([n, a]) => [`${n}${a.synopsis ? ` ${a.synopsis}` : ""}`, a.summary]),
294
- ], 2, 40)}
295
-
296
- Refs (e12) come from the last snapshot; take a new one after the page changes.
297
-
298
- Session: the commands one agent or one terminal shell runs are one session, so they keep their
17
+ be served by mcpd (its [server.browser-<id>] block in mcp.toml, which turno browser add prints).`,
18
+ session: `Session: the commands one agent or one terminal shell runs are one session, so they keep their
299
19
  tab and their place in the tab locks ("sharing": "tabs") or hold the identity's one-session lease
300
20
  ("sharing": "session"). The session belongs to the process that runs the commands: the coding
301
21
  agent (each of its shell commands passes through a short-lived shell) or your terminal's shell.
302
22
  It ends when that process exits, with 'end' or 'close', or when mcpd restarts. --session <name>
303
23
  (or TURNO_BROWSER_SESSION) keeps several sessions apart under one owner, for example two
304
- subagents each in its own tab.
305
-
306
- Output: url: and title: lines, then what the action returned; errors go to stderr with exit 1.
24
+ subagents each in its own tab.`,
25
+ output: `Output: url: and title: lines, then what the action returned; errors go to stderr with exit 1.
307
26
  --snapshot after an action prints the snapshot too; --json prints one object.
308
27
  --timeout <seconds> (default 120) bounds one action; attach mode can wait for Chrome's consent
309
- dialog. --profile picks the profile whose token and tool filter apply (default: this folder's).`;
310
- const DO_EXAMPLES = [
311
- "turno browser do school open https://example.com",
312
- "turno browser do school snapshot",
313
- "turno browser do school click e12",
314
- "turno browser do school type e5 'alice@example.com' --submit",
315
- "turno browser do school read",
316
- "turno browser do school screenshot --out page.png",
317
- "turno browser do school end",
318
- ];
319
- function doUsage() {
320
- return `Usage:\n turno browser do ${DO_SYNOPSIS}\n\n${DO_DETAILS}\n\n${examplesBlock(DO_EXAMPLES)}`;
321
- }
322
- function actionUsage(name) {
323
- const a = ACTIONS[name] ?? LOCAL[name];
324
- const mine = DO_EXAMPLES.filter((e) => e.split(" ")[4] === name);
325
- return `Usage:\n turno browser do <id> ${name}${a.synopsis ? ` ${a.synopsis}` : ""} [--session <name>] [--json]\n\n${a.summary}\n\n${examplesBlock(mine.length ? mine : [`turno browser do school ${name}`])}`;
326
- }
327
- // ---- results ---------------------------------------------------------------------------
328
- const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
329
- /** The sections of an upstream result text (`### Title`, then the body). */
330
- function sections(text) {
331
- const out = new Map();
332
- const parts = text.split(/^### /m);
333
- const head = parts[0].trim();
334
- if (head)
335
- out.set("", head);
336
- for (const part of parts.slice(1)) {
337
- const nl = part.indexOf("\n");
338
- const title = nl < 0 ? part.trim() : part.slice(0, nl).trim();
339
- out.set(title, nl < 0 ? "" : part.slice(nl + 1).trim());
340
- }
341
- return out;
342
- }
343
- function unfence(body) {
344
- return body.replace(/^```[a-z]*\n/, "").replace(/\n?```$/, "");
345
- }
346
- function pageOf(parts) {
347
- const body = parts.get("Page");
348
- if (!body)
349
- return null;
350
- const url = /^- Page URL: (.*)$/m.exec(body)?.[1]?.trim() ?? "";
351
- const title = /^- Page Title: (.*)$/m.exec(body)?.[1]?.trim() ?? "";
352
- return url || title ? { url, title } : null;
353
- }
354
- /** Upstream's error without the wrapper names and terminal colors. */
355
- function errorText(parts, whole) {
356
- const raw = parts.get("Error") ?? whole;
357
- return raw
358
- .replace(ANSI, "")
359
- .replace(/^(Error: )?browserBackend\.callTool: (Error: )?/, "")
360
- .trim();
361
- }
362
- /**
363
- * Notes worth a line: a pause by the user (the live view: how long, what changed while the
364
- * command waited), a dialog, new tabs and downloads, what the tab governor did.
365
- */
366
- function notesOf(parts) {
367
- const out = [];
368
- for (const title of ["Paused by the user", "Modal state", "Events", "Tab governor", "Downloads"]) {
369
- const body = parts.get(title);
370
- if (body)
371
- out.push(...body
372
- .split("\n")
373
- .map((l) => l.replace(/^- /, "").trim())
374
- .filter(Boolean));
375
- }
376
- return out;
377
- }
378
- function textOf(content) {
379
- return content
380
- .filter((c) => c.type === "text")
381
- .map((c) => c.text ?? "")
382
- .join("\n");
383
- }
384
- function render(shape, content, isError, opts) {
385
- const whole = textOf(content);
386
- const parts = sections(whole);
387
- const base = {
388
- ok: !isError,
389
- page: pageOf(parts),
390
- result: null,
391
- snapshot: null,
392
- file: null,
393
- notes: notesOf(parts),
394
- error: null,
395
- warnings: [],
396
- };
397
- if (isError)
398
- return { ...base, error: errorText(parts, whole) };
399
- const result = parts.get("Result");
400
- switch (shape) {
401
- case "snapshot": {
402
- const snap = parts.get("Snapshot");
403
- return { ...base, snapshot: snap === undefined ? null : unfence(snap) };
404
- }
405
- case "read": {
406
- let text = result ?? "";
407
- try {
408
- const v = JSON.parse(text);
409
- text = typeof v === "string" ? v : JSON.stringify(v);
410
- }
411
- catch {
412
- /* not JSON: as it came */
413
- }
414
- if (opts.maxChars > 0 && text.length > opts.maxChars) {
415
- const full = text.length;
416
- text = text.slice(0, opts.maxChars);
417
- base.warnings.push(`text cut at ${opts.maxChars} of ${full} characters (--max-chars 0 for all)`);
418
- }
419
- return { ...base, result: text };
420
- }
421
- case "screenshot": {
422
- const image = content.find((c) => c.type === "image" && c.data);
423
- if (!image)
424
- return { ...base, ok: false, error: "the server returned no image" };
425
- const ext = image.mimeType === "image/jpeg" ? "jpg" : "png";
426
- const file = resolve(opts.out ?? join(tmpdir(), `turno-${opts.identity}-${Date.now()}.${ext}`));
427
- writeFileSync(file, Buffer.from(image.data, "base64"));
428
- return { ...base, file };
429
- }
430
- case "raw":
431
- return { ...base, result: whole.replace(ANSI, "") || null };
432
- default:
433
- return { ...base, result: result ?? null };
434
- }
435
- }
436
- function printText(io, r, json) {
437
- if (json)
438
- return;
439
- if (r.page) {
440
- io.out(`url: ${r.page.url}`);
441
- if (r.page.title)
442
- io.out(`title: ${r.page.title}`);
443
- }
444
- if (r.result !== null && r.result !== "")
445
- io.out(r.result);
446
- if (r.file)
447
- io.out(`file: ${r.file}`);
448
- for (const n of r.notes)
449
- io.out(`note: ${n}`);
450
- if (r.snapshot !== null)
451
- io.out(r.snapshot);
452
- for (const w of r.warnings)
453
- io.err(`turno: ${w}`);
454
- if (r.error)
455
- io.err(`error: ${r.error}`);
456
- }
28
+ dialog. --profile picks the profile whose token and tool filter apply (default: this folder's).`,
29
+ };
457
30
  const down = () => new CliError("mcpd is not running (turno mcp daemon start)", Exit.gatewayDown);
458
31
  async function open(t, saved) {
459
32
  const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
@@ -529,7 +102,6 @@ async function endSaved(t, saved) {
529
102
  return;
530
103
  await terminate({ ...t, server: saved.server, profile: saved.profile, token: t.tokenFor(saved.profile) }, saved);
531
104
  }
532
- // ---- the command -----------------------------------------------------------------------
533
105
  async function resolveTarget(id, p, io, deps) {
534
106
  const manifest = loadManifest(io.env);
535
107
  const def = identityServer(manifest, id);
@@ -557,103 +129,8 @@ async function resolveTarget(id, p, io, deps) {
557
129
  tokenFor: (other) => profileToken(master, other),
558
130
  };
559
131
  }
560
- function sessionInfo(t, resumed) {
561
- return { name: t.name, ownerPid: t.owner.pid, owner: ownerName(t.owner), resumed };
562
- }
563
- const IDENTITY_ID = /^[a-z0-9][a-z0-9_-]*$/;
564
- /** `turno browser do <id> <action> [args]`. */
565
- export async function browserDo(args, io, deps = defaultDoDeps) {
566
- const [id, action, ...rest] = args;
567
- if (id === undefined || id === "--help" || id === "-h" || id === "help") {
568
- io.out(doUsage());
569
- return Exit.ok;
570
- }
571
- if (!IDENTITY_ID.test(id) || id.length > 64)
572
- return fail(`invalid identity "${id}": use lowercase letters, digits, "-" and "_" (turno browser identities lists them)`);
573
- if (action === undefined || action.startsWith("-")) {
574
- if (action === "--help" || action === "-h") {
575
- io.out(doUsage());
576
- return Exit.ok;
577
- }
578
- return fail(`browser do needs an action: turno browser do ${id} <action> (${ACTION_NAMES.join(", ")})`);
579
- }
580
- const act = ACTIONS[action];
581
- if (!act && !LOCAL[action]) {
582
- return fail(`unknown action "${action}" (actions: ${ACTION_NAMES.join(", ")}; turno browser do --help)`);
583
- }
584
- if (rest.includes("--help") || rest.includes("-h")) {
585
- io.out(actionUsage(action));
586
- return Exit.ok;
587
- }
588
- const p = parseFlags(rest, { ...COMMON, ...(act?.flags ?? {}) }, act ? act.max : 0);
589
- if (act && p.positionals.length < act.min)
590
- return fail(`usage: turno browser do ${id} ${action} ${act.synopsis}`.trimEnd());
591
- const json = jsonArg(rest) !== undefined;
592
- const timeoutFlag = str(p, "timeout");
593
- const timeoutS = timeoutFlag === undefined ? 120 : Number(timeoutFlag);
594
- if (!(timeoutS > 0))
595
- return fail(`--timeout takes seconds, not "${timeoutFlag}"`);
596
- const maxChars = int(p, "max-chars") ?? DEFAULT_MAX_CHARS;
597
- // Build the call before anything connects: a bad argument opens no session.
598
- const call = act ? await act.build(p.positionals, p, deps) : undefined;
599
- const t = await resolveTarget(id, p, io, deps);
600
- sweepSaved(io.env);
601
- const identity = `browser:${id}`;
602
- const head = { identity, server: t.server, profile: t.profile };
603
- if (action === "session") {
604
- const found = readSaved(t.file);
605
- const saved = usable(found, t) ? found : undefined;
606
- const live = saved !== undefined;
607
- if (json) {
608
- emit(io, p, DO_JSON, {
609
- ...head,
610
- session: sessionInfo(t, live),
611
- action,
612
- tool: null,
613
- ok: true,
614
- page: null,
615
- result: live ? "open" : "none",
616
- snapshot: null,
617
- file: null,
618
- notes: [],
619
- error: null,
620
- });
621
- return Exit.ok;
622
- }
623
- io.out(`identity: ${identity} (server ${t.server}, profile ${t.profile})`);
624
- io.out(`session: ${t.name}, owned by ${ownerName(t.owner)} (pid ${t.owner.pid})`);
625
- io.out(saved
626
- ? `state: open since ${saved.createdAt}, last used ${saved.usedAt}`
627
- : "state: none yet; the next action opens it");
628
- io.out(`ends: when pid ${t.owner.pid} exits, with 'end' or 'close', or when mcpd restarts`);
629
- io.out(`file: ${tildify(t.file, io.env)}`);
630
- return Exit.ok;
631
- }
632
- if (action === "end") {
633
- const saved = readSaved(t.file);
634
- if (saved)
635
- await endSaved(t, saved);
636
- dropSaved(t.file);
637
- if (json) {
638
- emit(io, p, DO_JSON, {
639
- ...head,
640
- session: sessionInfo(t, null),
641
- action,
642
- tool: null,
643
- ok: true,
644
- page: null,
645
- result: saved ? "ended" : "none",
646
- snapshot: null,
647
- file: null,
648
- notes: [],
649
- error: null,
650
- });
651
- }
652
- else
653
- io.out(saved ? `ended session ${t.name} of ${identity}` : `no session ${t.name} of ${identity} to end`);
654
- return Exit.ok;
655
- }
656
- const c = call;
132
+ /** Run `fn` in the saved session of `t`, or a new one, under the session file's lock. */
133
+ async function inSession(t, io, fn) {
657
134
  return await withLock(t.file, io.env, async () => {
658
135
  let saved = readSaved(t.file);
659
136
  if (saved && !usable(saved, t)) {
@@ -663,73 +140,57 @@ export async function browserDo(args, io, deps = defaultDoDeps) {
663
140
  saved = undefined;
664
141
  }
665
142
  let resumed = saved !== undefined;
143
+ let used = false;
144
+ let ended = false;
666
145
  let conn = await open(t, saved);
667
- const timeout = timeoutS * 1000;
668
- const callTool = (name, a) => conn.client.callTool({ name, arguments: a }, undefined, { timeout, resetTimeoutOnProgress: true });
669
- try {
670
- let result;
671
- // A session this command opened and could not use (a lease another session holds, a
672
- // refused call) goes at once instead of waiting for its owner to exit.
673
- const giveUp = async (err) => {
674
- if (!resumed)
675
- await conn.transport.terminateSession().catch(() => { });
676
- throw new CliError(`${c.tool}: ${gatewayMessage(err).message}`);
677
- };
678
- try {
679
- result = await callTool(c.tool, c.args);
680
- }
681
- catch (err) {
682
- if (!resumed || !sessionGone(err))
683
- return await giveUp(err);
684
- // mcpd forgot the session (it restarted and could not rebuild it): start a new one.
685
- await conn.client.close().catch(() => { });
686
- dropSaved(t.file);
687
- resumed = false;
688
- conn = await open(t);
146
+ const raw = async (name, a, timeout) => (await conn.client.callTool({ name, arguments: a }, undefined, {
147
+ timeout,
148
+ resetTimeoutOnProgress: true,
149
+ }));
150
+ // A session this command opened and could not use (a lease another session holds, a
151
+ // refused call) goes at once instead of waiting for its owner to exit.
152
+ const giveUp = async (tool, err) => {
153
+ if (!resumed && !used)
154
+ await conn.transport.terminateSession().catch(() => { });
155
+ throw new CliError(`${tool}: ${gatewayMessage(err).message}`);
156
+ };
157
+ const session = {
158
+ get resumed() {
159
+ return resumed;
160
+ },
161
+ async call(tool, args, timeout) {
162
+ let result;
689
163
  try {
690
- result = await callTool(c.tool, c.args);
164
+ result = await raw(tool, args, timeout);
691
165
  }
692
- catch (again) {
693
- return await giveUp(again);
166
+ catch (err) {
167
+ if (!resumed || used || !sessionGone(err))
168
+ return await giveUp(tool, err);
169
+ // mcpd forgot the session (it restarted and could not rebuild it): start a new one.
170
+ await conn.client.close().catch(() => { });
171
+ dropSaved(t.file);
172
+ resumed = false;
173
+ conn = await open(t);
174
+ try {
175
+ result = await raw(tool, args, timeout);
176
+ }
177
+ catch (again) {
178
+ return await giveUp(tool, again);
179
+ }
694
180
  }
695
- }
696
- const closing = action === "close" && result.isError !== true;
697
- if (closing) {
181
+ if (!used && !ended)
182
+ writeSaved(t.file, freshSaved(t, conn.transport, saved), io.env);
183
+ used = true;
184
+ return result;
185
+ },
186
+ async end() {
187
+ ended = true;
698
188
  await conn.transport.terminateSession().catch(() => { });
699
189
  dropSaved(t.file);
700
- }
701
- else
702
- writeSaved(t.file, freshSaved(t, conn.transport, saved), io.env);
703
- const content = (Array.isArray(result.content) ? result.content : []);
704
- const r = render(act.shape, content, result.isError === true, {
705
- maxChars,
706
- out: str(p, "out"),
707
- identity: id,
708
- });
709
- if (r.ok && bool(p, "snapshot") && act.shape === "page" && !closing) {
710
- const snap = await callTool("browser_snapshot", {}).catch(() => undefined);
711
- const sc = (Array.isArray(snap?.content) ? snap.content : []);
712
- const s = render("snapshot", sc, snap?.isError === true, { maxChars, identity: id });
713
- r.snapshot = s.snapshot;
714
- if (s.page)
715
- r.page = s.page;
716
- }
717
- if (json)
718
- emit(io, p, DO_JSON, {
719
- ...head,
720
- session: sessionInfo(t, resumed),
721
- action,
722
- tool: c.tool,
723
- ok: r.ok,
724
- page: r.page,
725
- result: r.result,
726
- snapshot: r.snapshot,
727
- file: r.file,
728
- notes: r.notes,
729
- error: r.error,
730
- });
731
- printText(io, r, json);
732
- return r.ok ? Exit.ok : Exit.failure;
190
+ },
191
+ };
192
+ try {
193
+ return await fn(session);
733
194
  }
734
195
  finally {
735
196
  // Never terminateSession here: the next command of this session reconnects to it.
@@ -737,4 +198,44 @@ export async function browserDo(args, io, deps = defaultDoDeps) {
737
198
  }
738
199
  });
739
200
  }
201
+ /** The mcpd transport of `turno browser do`. */
202
+ export function mcpdTransport(deps = defaultDoDeps) {
203
+ return {
204
+ help: HELP,
205
+ flags: { profile: { type: "string" } },
206
+ async target(id, p, io) {
207
+ const t = await resolveTarget(id, p, io, deps);
208
+ sweepSaved(io.env);
209
+ const identity = `browser:${id}`;
210
+ return {
211
+ head: { identity, server: t.server, profile: t.profile },
212
+ info: (resumed) => ({ name: t.name, ownerPid: t.owner.pid, owner: ownerName(t.owner), resumed }),
213
+ describe() {
214
+ const found = readSaved(t.file);
215
+ const saved = usable(found, t) ? found : undefined;
216
+ return {
217
+ open: saved !== undefined,
218
+ lines: [
219
+ `identity: ${identity} (server ${t.server}, profile ${t.profile})`,
220
+ `session: ${t.name}, owned by ${ownerName(t.owner)} (pid ${t.owner.pid})`,
221
+ saved
222
+ ? `state: open since ${saved.createdAt}, last used ${saved.usedAt}`
223
+ : "state: none yet; the next action opens it",
224
+ `ends: when pid ${t.owner.pid} exits, with 'end' or 'close', or when mcpd restarts`,
225
+ `file: ${tildify(t.file, io.env)}`,
226
+ ],
227
+ };
228
+ },
229
+ async end() {
230
+ const saved = readSaved(t.file);
231
+ if (saved)
232
+ await endSaved(t, saved);
233
+ dropSaved(t.file);
234
+ return saved !== undefined;
235
+ },
236
+ session: (fn) => inSession(t, io, fn),
237
+ };
238
+ },
239
+ };
240
+ }
740
241
  //# sourceMappingURL=browser-do.js.map