turno-cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +266 -0
  2. package/README.md +134 -42
  3. package/dist/accounts/audit.js +27 -15
  4. package/dist/accounts/builtin.js +35 -7
  5. package/dist/accounts/delegate.js +30 -7
  6. package/dist/accounts/policy.js +4 -2
  7. package/dist/accounts/registry.js +3 -1
  8. package/dist/agents/adapter.js +22 -0
  9. package/dist/agents/claude.js +54 -3
  10. package/dist/agents/codex.js +94 -6
  11. package/dist/agents/copilot.js +19 -2
  12. package/dist/agents/cursor.js +19 -2
  13. package/dist/agents/index.js +1 -1
  14. package/dist/agents/snippets.js +37 -10
  15. package/dist/cli/args.js +32 -15
  16. package/dist/cli/commands/accounts.js +29 -7
  17. package/dist/cli/commands/auto.js +50 -12
  18. package/dist/cli/commands/browser-do-session.js +170 -0
  19. package/dist/cli/commands/browser-do.js +740 -0
  20. package/dist/cli/commands/browser-flows.js +300 -0
  21. package/dist/cli/commands/browser-identity.js +952 -0
  22. package/dist/cli/commands/browser-live.js +118 -0
  23. package/dist/cli/commands/browser-session.js +102 -0
  24. package/dist/cli/commands/browser-vault.js +193 -0
  25. package/dist/cli/commands/browser.js +303 -62
  26. package/dist/cli/commands/complete.js +13 -3
  27. package/dist/cli/commands/completion.js +4 -0
  28. package/dist/cli/commands/config.js +90 -13
  29. package/dist/cli/commands/demo.js +36 -7
  30. package/dist/cli/commands/doctor.js +170 -36
  31. package/dist/cli/commands/identity.js +101 -12
  32. package/dist/cli/commands/init.js +42 -10
  33. package/dist/cli/commands/limit.js +65 -9
  34. package/dist/cli/commands/mcp-call.js +240 -0
  35. package/dist/cli/commands/mcp-oauth.js +33 -6
  36. package/dist/cli/commands/mcp-observe.js +128 -23
  37. package/dist/cli/commands/mcp-share.js +201 -0
  38. package/dist/cli/commands/mcp.js +203 -42
  39. package/dist/cli/commands/mcpd.js +76 -12
  40. package/dist/cli/commands/open.js +26 -3
  41. package/dist/cli/commands/profile.js +212 -30
  42. package/dist/cli/commands/resolve.js +8 -1
  43. package/dist/cli/commands/run.js +24 -4
  44. package/dist/cli/commands/secret.js +23 -38
  45. package/dist/cli/commands/session.js +16 -5
  46. package/dist/cli/commands/sessions.js +7 -1
  47. package/dist/cli/commands/setup.js +83 -11
  48. package/dist/cli/commands/status.js +67 -15
  49. package/dist/cli/commands/statusline.js +7 -2
  50. package/dist/cli/commands/ui.js +17 -5
  51. package/dist/cli/commands/undo.js +39 -7
  52. package/dist/cli/commands/uninstall.js +24 -5
  53. package/dist/cli/commands/upgrade.js +113 -76
  54. package/dist/cli/commands/usage.js +11 -10
  55. package/dist/cli/commands/version.js +20 -8
  56. package/dist/cli/commands/which.js +5 -3
  57. package/dist/cli/diagnostics.js +184 -0
  58. package/dist/cli/exit.js +65 -0
  59. package/dist/cli/group.js +20 -8
  60. package/dist/cli/help.js +6 -1
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +24 -8
  63. package/dist/cli/launch.js +31 -2
  64. package/dist/cli/launchers.js +25 -10
  65. package/dist/cli/main.js +52 -18
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +17 -5
  69. package/dist/cli/registry.js +20 -2
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +31 -9
  73. package/dist/cli/style.js +35 -5
  74. package/dist/cli/topics.js +155 -0
  75. package/dist/core/config.js +39 -3
  76. package/dist/core/fsutil.js +2 -10
  77. package/dist/core/journal.js +19 -11
  78. package/dist/core/manifest.js +28 -1
  79. package/dist/core/paths.js +6 -112
  80. package/dist/core/profiles.js +28 -8
  81. package/dist/core/resolve.js +13 -3
  82. package/dist/core/secrets.js +4 -154
  83. package/dist/core/state-file.js +107 -0
  84. package/dist/core/update.js +14 -11
  85. package/dist/core/version.js +57 -10
  86. package/dist/demo/server.js +10 -2
  87. package/dist/mcpd/cache.js +6 -7
  88. package/dist/mcpd/calllog.js +10 -9
  89. package/dist/mcpd/client-names.js +8 -13
  90. package/dist/mcpd/connectors.js +42 -3
  91. package/dist/mcpd/daemon.js +29 -8
  92. package/dist/mcpd/folder-sets.js +5 -2
  93. package/dist/mcpd/gateway.js +57 -29
  94. package/dist/mcpd/health.js +70 -26
  95. package/dist/mcpd/importer.js +106 -9
  96. package/dist/mcpd/instances.js +70 -32
  97. package/dist/mcpd/jsonrpc.js +3 -1
  98. package/dist/mcpd/middleware.js +156 -0
  99. package/dist/mcpd/modern.js +57 -19
  100. package/dist/mcpd/oauth.js +71 -17
  101. package/dist/mcpd/peerpid.js +63 -17
  102. package/dist/mcpd/pressure.js +4 -1
  103. package/dist/mcpd/rss.js +34 -19
  104. package/dist/mcpd/service.js +28 -4
  105. package/dist/mcpd/share.js +217 -0
  106. package/dist/mcpd/state.js +16 -16
  107. package/dist/mcpd/sync.js +22 -12
  108. package/dist/mcpd/systemd.js +4 -1
  109. package/dist/mcpd/tokens.js +4 -8
  110. package/dist/mcpd/upstream.js +12 -5
  111. package/dist/statusline/cost.js +17 -4
  112. package/dist/statusline/input.js +15 -3
  113. package/dist/ui/fonts.js +1 -1
  114. package/dist/ui/settings.js +6 -1
  115. package/npm-shrinkwrap.json +12 -3
  116. package/package.json +7 -6
@@ -0,0 +1,740 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { readProcTable } from "turno-core/process";
5
+ import { gatewayUrl } from "../../agents/adapter.js";
6
+ import { loadManifest, servesProfile } from "../../core/manifest.js";
7
+ import { packageInfo } from "../../core/version.js";
8
+ import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
9
+ 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";
13
+ 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
+ }
49
+ export const defaultDoDeps = {
50
+ 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
+ };
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
287
+ 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
299
+ tab and their place in the tab locks ("sharing": "tabs") or hold the identity's one-session lease
300
+ ("sharing": "session"). The session belongs to the process that runs the commands: the coding
301
+ agent (each of its shell commands passes through a short-lived shell) or your terminal's shell.
302
+ It ends when that process exits, with 'end' or 'close', or when mcpd restarts. --session <name>
303
+ (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.
307
+ --snapshot after an action prints the snapshot too; --json prints one object.
308
+ --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
+ }
457
+ const down = () => new CliError("mcpd is not running (turno mcp daemon start)", Exit.gatewayDown);
458
+ async function open(t, saved) {
459
+ const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
460
+ const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
461
+ const transport = new StreamableHTTPClientTransport(new URL(gatewayUrl(t.server, t.port)), {
462
+ ...(saved ? { sessionId: saved.sessionId } : {}),
463
+ requestInit: {
464
+ headers: {
465
+ Authorization: `Bearer ${t.token}`,
466
+ "X-Turno-Profile": t.profile,
467
+ // The session's owner, not this short-lived process: mcpd keeps the session while it lives.
468
+ "X-Turno-Pid": String(t.owner.pid),
469
+ "X-Turno-Cwd-B64": Buffer.from(process.cwd(), "utf8").toString("base64url"),
470
+ },
471
+ },
472
+ });
473
+ if (saved?.protocolVersion)
474
+ transport.setProtocolVersion(saved.protocolVersion);
475
+ const client = new Client({ name: "turno-browser-do", version: packageInfo().version }, { capabilities: {} });
476
+ try {
477
+ await client.connect(transport);
478
+ }
479
+ catch (err) {
480
+ const g = gatewayMessage(err);
481
+ if (g.status === undefined && /ECONNREFUSED|fetch failed|connect/i.test(g.message))
482
+ throw down();
483
+ throw new CliError(`mcpd refused the session for ${t.server} as profile ${t.profile}: ${g.message}`);
484
+ }
485
+ if (!saved && client.getServerVersion()?.version === "hidden")
486
+ throw new CliError(client.getInstructions() ?? `${t.server} is hidden in this folder`);
487
+ return { client, transport };
488
+ }
489
+ function freshSaved(t, transport, previous) {
490
+ const now = new Date().toISOString();
491
+ return {
492
+ v: 1,
493
+ identity: t.identity,
494
+ server: t.server,
495
+ profile: t.profile,
496
+ port: t.port,
497
+ sessionId: transport.sessionId,
498
+ ...(transport.protocolVersion ? { protocolVersion: transport.protocolVersion } : {}),
499
+ owner: t.owner,
500
+ name: t.name,
501
+ createdAt: previous?.createdAt ?? now,
502
+ usedAt: now,
503
+ };
504
+ }
505
+ /** A saved session this command can continue: same mcpd, server, profile and owner. */
506
+ function usable(saved, t) {
507
+ return (saved !== undefined &&
508
+ saved.port === t.port &&
509
+ saved.server === t.server &&
510
+ saved.profile === t.profile &&
511
+ saved.owner.pid === t.owner.pid);
512
+ }
513
+ /** mcpd no longer knows the session (it answers 404): the command opens a new one. */
514
+ function sessionGone(err) {
515
+ const g = gatewayMessage(err);
516
+ return g.status === 404 || /session not found|unknown session/i.test(g.message);
517
+ }
518
+ async function terminate(t, saved) {
519
+ const { transport, client } = await open(t, saved).catch(() => ({ transport: undefined, client: undefined }));
520
+ await transport?.terminateSession().catch(() => { });
521
+ await client?.close().catch(() => { });
522
+ }
523
+ /**
524
+ * Ends a saved session when the mcpd that holds it still runs (it may hold the identity's
525
+ * lease), with the token of the profile that opened it. Another mcpd forgot it already.
526
+ */
527
+ async function endSaved(t, saved) {
528
+ if (saved.port !== t.port || saved.owner.pid !== t.owner.pid)
529
+ return;
530
+ await terminate({ ...t, server: saved.server, profile: saved.profile, token: t.tokenFor(saved.profile) }, saved);
531
+ }
532
+ // ---- the command -----------------------------------------------------------------------
533
+ async function resolveTarget(id, p, io, deps) {
534
+ const manifest = loadManifest(io.env);
535
+ const def = identityServer(manifest, id);
536
+ if (!def)
537
+ throw new CliError(`browser identity "${id}" is not served by mcpd: add its block to mcp.toml (turno browser add ${id} prints it, or use [server.browser-${id}] with args = ["--identity", "${id}"]) and run turno mcp sync`);
538
+ const profile = callerProfile(str(p, "profile"), io.env, process.cwd());
539
+ if (!servesProfile(def, profile))
540
+ throw new CliError(`${def.name} is not served to profile ${profile} (profiles = ${JSON.stringify(def.profiles)} in mcp.toml); pick another with --profile`);
541
+ const { mcpdPort, readToken } = await import("../../mcpd/state.js");
542
+ const { profileToken } = await import("../../mcpd/tokens.js");
543
+ const master = readToken(io.env);
544
+ if (!master)
545
+ throw down();
546
+ const owner = deps.owner(io.env);
547
+ const name = sessionName(str(p, "session"), io.env);
548
+ return {
549
+ identity: id,
550
+ server: def.name,
551
+ profile,
552
+ port: mcpdPort(io.env),
553
+ token: profileToken(master, profile),
554
+ owner,
555
+ name,
556
+ file: sessionFile(io.env, id, owner.pid, name),
557
+ tokenFor: (other) => profileToken(master, other),
558
+ };
559
+ }
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;
657
+ return await withLock(t.file, io.env, async () => {
658
+ let saved = readSaved(t.file);
659
+ if (saved && !usable(saved, t)) {
660
+ // Another mcpd, server, profile or owner: that session is not this one's to continue.
661
+ await endSaved(t, saved);
662
+ dropSaved(t.file);
663
+ saved = undefined;
664
+ }
665
+ let resumed = saved !== undefined;
666
+ 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);
689
+ try {
690
+ result = await callTool(c.tool, c.args);
691
+ }
692
+ catch (again) {
693
+ return await giveUp(again);
694
+ }
695
+ }
696
+ const closing = action === "close" && result.isError !== true;
697
+ if (closing) {
698
+ await conn.transport.terminateSession().catch(() => { });
699
+ 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;
733
+ }
734
+ finally {
735
+ // Never terminateSession here: the next command of this session reconnects to it.
736
+ await conn.client.close().catch(() => { });
737
+ }
738
+ });
739
+ }
740
+ //# sourceMappingURL=browser-do.js.map