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,952 +0,0 @@
1
- import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { basename, dirname, join } from "node:path";
4
- import { loadManifest } from "../../core/manifest.js";
5
- import { tildify } from "../../core/paths.js";
6
- import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
7
- import { Exit } from "../exit.js";
8
- import { fail } from "../io.js";
9
- import { emit, jsonOutput } from "../output.js";
10
- import { style } from "../style.js";
11
- /** `turno browser show --json` and `turno identity show browser:<id> --json`. */
12
- export const SHOW_JSON = jsonOutput(["id", "dir", "settingsFile", "settings", "problems", "inUse", "holder", "health"]);
13
- /** `turno browser set --json` and `turno identity set browser:<id> --json`: what changed, or would. */
14
- export const SET_JSON = jsonOutput(["id", "settingsFile", "dryRun", "changes", "settings"]);
15
- /** `turno browser doctor --json`: the shape of `turno doctor --json`. */
16
- export const DOCTOR_JSON = jsonOutput(["ok", "counts", "checks", "fixed"]);
17
- /** `turno browser reputation --json`: one element per identity. */
18
- export const REPUTATION_JSON = jsonOutput(["id", "file", "total", "sites"]);
19
- /** Flags that write identity.json, shared by `add` and `set`. An empty value removes the key. */
20
- export const SETTINGS_FLAGS = {
21
- timezone: { type: "string" },
22
- locale: { type: "string" },
23
- languages: { type: "string" },
24
- region: { type: "string" },
25
- "health-url": { type: "string" },
26
- "health-text": { type: "string" },
27
- "health-selector": { type: "string" },
28
- "no-health": { type: "boolean" },
29
- // How the host runs this identity's Chrome (format 2 of identity.json): the tab governor,
30
- // background throttling, settle, resource blocking and cache.
31
- "tabs-max": { type: "string" },
32
- "tabs-popups": { type: "string" },
33
- "tabs-park": { type: "string" },
34
- "tabs-close": { type: "string" },
35
- "no-tabs": { type: "boolean" },
36
- "background-throttling": { type: "string" },
37
- settle: { type: "string" },
38
- "block-trackers": { type: "string" },
39
- "block-types": { type: "string" },
40
- "block-patterns": { type: "string" },
41
- "no-block": { type: "boolean" },
42
- cache: { type: "boolean" },
43
- "cache-max-size": { type: "string" },
44
- "no-cache": { type: "boolean" },
45
- // Human-like input (format 4): off, light, full or adaptive.
46
- humanize: { type: "string" },
47
- // How many agent sessions use the identity's browser at once (format 5), and with tabs how
48
- // long a call waits for a held tab and when an idle session lets go (format 8).
49
- sharing: { type: "string" },
50
- "tab-lock-wait": { type: "string" },
51
- "tab-lock-release": { type: "string" },
52
- // Which engine runs the identity (format 6): read mode on Lightpanda, or attach mode.
53
- engine: { type: "string" },
54
- attach: { type: "string" },
55
- // What turno-browser records for this identity (format 7): flows, traces, screenshots.
56
- "record-flows": { type: "string" },
57
- "record-traces": { type: "string" },
58
- "record-screenshots": { type: "string" },
59
- "record-max-size": { type: "string" },
60
- "no-record": { type: "boolean" },
61
- // Natural language actions and captcha solving (format 8): off by default, opt-in only.
62
- act: { type: "boolean" },
63
- "act-sampling": { type: "string" },
64
- "act-provider": { type: "string" },
65
- "act-endpoint": { type: "string" },
66
- "act-model": { type: "string" },
67
- "act-key": { type: "string" },
68
- "act-max-steps": { type: "string" },
69
- "act-max-tokens": { type: "string" },
70
- "act-timeout": { type: "string" },
71
- "no-act": { type: "boolean" },
72
- "captcha-provider": { type: "string" },
73
- "captcha-endpoint": { type: "string" },
74
- "captcha-key": { type: "string" },
75
- "captcha-timeout": { type: "string" },
76
- "no-captcha": { type: "boolean" },
77
- // The live view and take-over (format 10).
78
- live: { type: "string" },
79
- "live-wait": { type: "string" },
80
- "no-live": { type: "boolean" },
81
- // Opt-in network and user agent settings (format 11), all off by default.
82
- "user-agent": { type: "string" },
83
- "proxy-server": { type: "string" },
84
- "proxy-username": { type: "string" },
85
- "proxy-password": { type: "string" },
86
- "no-proxy": { type: "boolean" },
87
- };
88
- /** The identity.json key behind each tuning flag, so the package's messages name the flag. */
89
- const KEY_FLAGS = [
90
- ["tabs.max", "--tabs-max"],
91
- ["tabs.popups", "--tabs-popups"],
92
- ["tabs.park", "--tabs-park"],
93
- ["tabs.close", "--tabs-close"],
94
- ["backgroundThrottling", "--background-throttling"],
95
- ["settle", "--settle"],
96
- ["block.trackers", "--block-trackers"],
97
- ["block.types", "--block-types"],
98
- ["block.patterns", "--block-patterns"],
99
- ["cache.maxSize", "--cache-max-size"],
100
- ["humanize.level", "--humanize"],
101
- ["sharing", "--sharing"],
102
- ["tabLocks.wait", "--tab-lock-wait"],
103
- ["tabLocks.release", "--tab-lock-release"],
104
- ["engine", "--engine"],
105
- ["attach", "--attach"],
106
- ["record.flows", "--record-flows"],
107
- ["record.traces", "--record-traces"],
108
- ["record.screenshots", "--record-screenshots"],
109
- ["record.maxSize", "--record-max-size"],
110
- ["act.sampling", "--act-sampling"],
111
- ["act.provider", "--act-provider"],
112
- ["act.endpoint", "--act-endpoint"],
113
- ["act.model", "--act-model"],
114
- ["act.key", "--act-key"],
115
- ["act.maxSteps", "--act-max-steps"],
116
- ["act.maxTokens", "--act-max-tokens"],
117
- ["act.timeout", "--act-timeout"],
118
- ["captcha.provider", "--captcha-provider"],
119
- ["captcha.endpoint", "--captcha-endpoint"],
120
- ["captcha.key", "--captcha-key"],
121
- ["captcha.timeout", "--captcha-timeout"],
122
- ["live.enabled", "--live"],
123
- ["live.wait", "--live-wait"],
124
- ["userAgent", "--user-agent"],
125
- ["proxy.server", "--proxy-server"],
126
- ["proxy.username", "--proxy-username"],
127
- ["proxy.password", "--proxy-password"],
128
- ];
129
- const TABS_MAX_PROBLEM = "--tabs-max must be a whole number from 0 (no cap) to 100";
130
- /**
131
- * A rejected identity.json with each problem of a tuning key told as its flag: the package
132
- * says `identity "school": settle must be ...`, the command line says `--settle must be ...`.
133
- * Other messages stay as the package wrote them.
134
- */
135
- function flagMessage(message) {
136
- const problems = message.replace(/^identity "[^"]*": /, "").split("; ");
137
- const told = problems.map((p) => {
138
- const hit = KEY_FLAGS.find(([key]) => p.startsWith(`${key} `));
139
- return hit ? `${hit[1]}${p.slice(hit[0].length)}` : undefined;
140
- });
141
- return told.every((t) => t !== undefined) ? told.join("; ") : message;
142
- }
143
- /** A true or false flag value; also on/off and yes/no. */
144
- function booleanValue(flag, v) {
145
- const word = v.toLowerCase();
146
- if (["true", "on", "yes"].includes(word))
147
- return true;
148
- if (["false", "off", "no"].includes(word))
149
- return false;
150
- return fail(`${flag} must be true or false (an empty value removes it)`);
151
- }
152
- const list = (v) => v
153
- .split(",")
154
- .map((x) => x.trim())
155
- .filter(Boolean);
156
- /**
157
- * A group of identity.json (tabs, block, cache) after the flags: `parts` set or (with null)
158
- * remove its keys, the rest of `base` stays. Null when nothing is left, so the key goes.
159
- */
160
- function mergeGroup(base, parts) {
161
- const next = { ...base };
162
- for (const [k, v] of Object.entries(parts)) {
163
- if (v === undefined)
164
- continue;
165
- if (v === null)
166
- delete next[k];
167
- else
168
- next[k] = v;
169
- }
170
- return Object.keys(next).length ? next : null;
171
- }
172
- export const SETTINGS_FLAG_NAMES = Object.keys(SETTINGS_FLAGS).map((f) => `--${f}`);
173
- /** The identity.json change the flags ask for; `current` fills the parts of health not given. */
174
- export function settingsPatch(p, current) {
175
- const patch = {};
176
- const value = (name) => {
177
- const v = str(p, name);
178
- return v === undefined ? undefined : v.trim() === "" ? null : v.trim();
179
- };
180
- for (const key of ["timezone", "locale", "region"]) {
181
- const v = value(key);
182
- if (v !== undefined)
183
- patch[key] = v;
184
- }
185
- const langs = value("languages");
186
- if (langs !== undefined)
187
- patch.languages =
188
- langs === null
189
- ? null
190
- : langs
191
- .split(",")
192
- .map((l) => l.trim())
193
- .filter(Boolean);
194
- const url = value("health-url");
195
- const text = value("health-text");
196
- const selector = value("health-selector");
197
- if (bool(p, "no-health")) {
198
- if (url !== undefined || text !== undefined || selector !== undefined)
199
- fail("--no-health does not go with the other --health flags");
200
- patch.health = null;
201
- }
202
- else if (url !== undefined || text !== undefined || selector !== undefined) {
203
- const base = current?.health;
204
- const health = { url: url ?? base?.url ?? "" };
205
- const t = text === undefined ? base?.text : (text ?? undefined);
206
- const s = selector === undefined ? base?.selector : (selector ?? undefined);
207
- if (t)
208
- health.text = t;
209
- if (s)
210
- health.selector = s;
211
- if (!health.url)
212
- fail("a health check needs --health-url (a page only a signed-in user sees)");
213
- if (!health.text && !health.selector)
214
- fail("a health check needs --health-text or --health-selector (what that page shows when signed in)");
215
- patch.health = health;
216
- }
217
- tuningPatch(p, value, patch, current);
218
- const engine = value("engine");
219
- if (engine !== undefined)
220
- patch.engine = engine;
221
- const attach = value("attach");
222
- if (attach !== undefined)
223
- patch.attach = attach;
224
- networkPatch(p, value, patch, current);
225
- return patch;
226
- }
227
- /** The format 11 keys: `userAgent` and `proxy`. The package checks the values. */
228
- function networkPatch(p, value, patch, current) {
229
- const userAgent = value("user-agent");
230
- if (userAgent !== undefined)
231
- patch.userAgent = userAgent;
232
- const parts = {
233
- server: value("proxy-server"),
234
- username: value("proxy-username"),
235
- password: value("proxy-password"),
236
- };
237
- const given = Object.values(parts).some((v) => v !== undefined);
238
- if (bool(p, "no-proxy")) {
239
- if (given)
240
- fail("--no-proxy does not go with the other --proxy flags");
241
- patch.proxy = null;
242
- }
243
- else if (given) {
244
- patch.proxy = mergeGroup(current?.proxy, parts);
245
- }
246
- }
247
- /** The format 2 keys of the patch: tabs, backgroundThrottling, settle, block and cache. */
248
- function tuningPatch(p, value, patch, current) {
249
- const tabs = {
250
- max: value("tabs-max"),
251
- popups: value("tabs-popups"),
252
- park: value("tabs-park"),
253
- close: value("tabs-close"),
254
- };
255
- if (bool(p, "no-tabs")) {
256
- if (Object.values(tabs).some((v) => v !== undefined))
257
- fail("--no-tabs does not go with the other --tabs flags");
258
- patch.tabs = null;
259
- }
260
- else if (Object.values(tabs).some((v) => v !== undefined)) {
261
- let max;
262
- if (typeof tabs.max === "string") {
263
- if (!/^\d+$/.test(tabs.max))
264
- fail(TABS_MAX_PROBLEM);
265
- max = Number(tabs.max);
266
- }
267
- else
268
- max = tabs.max;
269
- patch.tabs = mergeGroup(current?.tabs, { ...tabs, max });
270
- }
271
- const throttling = value("background-throttling");
272
- if (throttling !== undefined)
273
- patch.backgroundThrottling = throttling === null ? null : booleanValue("--background-throttling", throttling);
274
- const settle = value("settle");
275
- if (settle !== undefined)
276
- patch.settle = settle;
277
- const trackers = value("block-trackers");
278
- const types = value("block-types");
279
- const patterns = value("block-patterns");
280
- if (bool(p, "no-block")) {
281
- if (trackers !== undefined || types !== undefined || patterns !== undefined)
282
- fail("--no-block does not go with the other --block flags");
283
- patch.block = null;
284
- }
285
- else if (trackers !== undefined || types !== undefined || patterns !== undefined) {
286
- patch.block = mergeGroup(current?.block, {
287
- trackers: typeof trackers === "string" ? booleanValue("--block-trackers", trackers) : trackers,
288
- types: typeof types === "string" ? list(types) : types,
289
- patterns: typeof patterns === "string" ? list(patterns) : patterns,
290
- });
291
- }
292
- const maxSize = value("cache-max-size");
293
- if (bool(p, "no-cache")) {
294
- if (bool(p, "cache") || maxSize !== undefined)
295
- fail("--no-cache does not go with --cache or --cache-max-size");
296
- patch.cache = null;
297
- }
298
- else if (bool(p, "cache") || maxSize !== undefined) {
299
- // The cache stays on when its size is removed: {} is on with the default size.
300
- patch.cache = mergeGroup(current?.cache, { maxSize }) ?? {};
301
- }
302
- // An empty value removes the whole group (the seed with it); a level keeps a seed set by hand.
303
- const humanize = value("humanize");
304
- if (humanize !== undefined)
305
- patch.humanize = humanize === null ? null : { ...current?.humanize, level: humanize };
306
- // Checked by the package: an unknown value comes back as `--sharing must be ...`.
307
- const sharing = value("sharing");
308
- if (sharing !== undefined)
309
- patch.sharing = sharing;
310
- const locks = { wait: value("tab-lock-wait"), release: value("tab-lock-release") };
311
- if (locks.wait !== undefined || locks.release !== undefined)
312
- patch.tabLocks = mergeGroup(current?.tabLocks, locks);
313
- recordPatch(p, value, patch, current);
314
- actPatch(p, value, patch, current);
315
- captchaPatch(p, value, patch, current);
316
- livePatch(p, value, patch, current);
317
- }
318
- /** A whole number flag value as a number; anything else goes to the package, which says why. */
319
- const wholeNumber = (v) => (typeof v === "string" && /^\d+$/.test(v) ? Number(v) : v);
320
- /** The format 8 `act` key: natural language actions, with MCP sampling or a provider. */
321
- function actPatch(p, value, patch, current) {
322
- const sampling = value("act-sampling");
323
- const parts = {
324
- sampling: typeof sampling === "string" ? booleanValue("--act-sampling", sampling) : sampling,
325
- provider: value("act-provider"),
326
- endpoint: value("act-endpoint"),
327
- model: value("act-model"),
328
- key: value("act-key"),
329
- maxSteps: wholeNumber(value("act-max-steps")),
330
- maxTokens: wholeNumber(value("act-max-tokens")),
331
- timeout: value("act-timeout"),
332
- };
333
- const given = Object.values(parts).some((v) => v !== undefined);
334
- if (bool(p, "no-act")) {
335
- if (given || bool(p, "act"))
336
- fail("--no-act does not go with the other --act flags");
337
- patch.act = null;
338
- }
339
- else if (given || bool(p, "act")) {
340
- patch.act = mergeGroup(current?.act, parts) ?? {};
341
- }
342
- }
343
- /** The format 8 `captcha` key: a solver service and its key's secret store reference. */
344
- function captchaPatch(p, value, patch, current) {
345
- const parts = {
346
- provider: value("captcha-provider"),
347
- endpoint: value("captcha-endpoint"),
348
- key: value("captcha-key"),
349
- timeout: value("captcha-timeout"),
350
- };
351
- const given = Object.values(parts).some((v) => v !== undefined);
352
- if (bool(p, "no-captcha")) {
353
- if (given)
354
- fail("--no-captcha does not go with the other --captcha flags");
355
- patch.captcha = null;
356
- }
357
- else if (given) {
358
- patch.captcha = mergeGroup(current?.captcha, parts);
359
- }
360
- }
361
- /** How an identity's natural language actions get a model, in a few words. */
362
- function describeAct(a) {
363
- if (!a)
364
- return undefined;
365
- const provider = a.provider ? `${a.provider} ${a.model ?? ""} at ${a.endpoint ?? ""}`.replace(/\s+/g, " ") : "";
366
- const how = a.sampling === false
367
- ? provider
368
- : provider
369
- ? `MCP sampling, else ${provider}`
370
- : "MCP sampling (your client's model)";
371
- return `on: ${how}`;
372
- }
373
- /** The format 10 `live` key: the live view and take-over. */
374
- function livePatch(p, value, patch, current) {
375
- const enabled = value("live");
376
- const wait = value("live-wait");
377
- if (bool(p, "no-live")) {
378
- if (enabled !== undefined || wait !== undefined)
379
- fail("--no-live does not go with --live or --live-wait");
380
- patch.live = null;
381
- }
382
- else if (enabled !== undefined || wait !== undefined) {
383
- patch.live = mergeGroup(current?.live, {
384
- enabled: typeof enabled === "string" ? booleanValue("--live", enabled) : enabled,
385
- wait,
386
- });
387
- }
388
- }
389
- /** The format 7 `record` key: what turno-browser records for this identity. */
390
- function recordPatch(p, value, patch, current) {
391
- const parts = {
392
- flows: value("record-flows"),
393
- traces: value("record-traces"),
394
- screenshots: value("record-screenshots"),
395
- maxSize: value("record-max-size"),
396
- };
397
- const given = Object.values(parts).some((v) => v !== undefined);
398
- if (bool(p, "no-record")) {
399
- if (given)
400
- fail("--no-record does not go with the other --record flags");
401
- patch.record = null;
402
- }
403
- else if (given) {
404
- const flag = (name, v) => typeof v === "string" ? booleanValue(`--record-${name}`, v) : v;
405
- patch.record = mergeGroup(current?.record, {
406
- flows: flag("flows", parts.flows),
407
- traces: flag("traces", parts.traces),
408
- screenshots: flag("screenshots", parts.screenshots),
409
- maxSize: parts.maxSize,
410
- });
411
- }
412
- }
413
- /** What an identity records, in a few words: "flows, traces (up to 200MB)". */
414
- export function describeRecord(r) {
415
- if (!r)
416
- return undefined;
417
- const on = ["flows", "traces", "screenshots"].filter((k) => r[k]);
418
- if (!on.length)
419
- return undefined;
420
- const files = r.traces || r.screenshots;
421
- return `${on.join(", ")}${files ? ` (up to ${r.maxSize ?? "200MB"})` : ""}`;
422
- }
423
- export function hasSettings(patch) {
424
- return Object.keys(patch).length > 0;
425
- }
426
- /** A proxy for `show`: the server and where the credentials come from, never their value. */
427
- function describeProxy(p) {
428
- const who = p.username ? `, signs in as ${p.username} with ${p.password}` : "";
429
- return `${p.server}${who}`;
430
- }
431
- function describeHealth(h) {
432
- return [h.url, h.text ? `shows "${h.text}"` : "", h.selector ? `has ${h.selector}` : ""].filter(Boolean).join(" ");
433
- }
434
- function describeTabs(t) {
435
- const parts = [];
436
- if (t.max !== undefined)
437
- parts.push(t.max === 0 ? "no cap on open tabs" : `at most ${t.max} open`);
438
- if (t.popups)
439
- parts.push(t.popups === "keep" ? "popups kept" : "popups closed");
440
- if (t.park !== undefined)
441
- parts.push(t.park === "0" ? "never parked" : `parked after ${t.park}`);
442
- if (t.close !== undefined)
443
- parts.push(t.close === "0" ? "never closed when unused" : `closed after ${t.close}`);
444
- return parts.join(", ");
445
- }
446
- function describeBlock(b) {
447
- const n = b.patterns?.length ?? 0;
448
- return [b.trackers ? "trackers" : "", ...(b.types ?? []), n ? `${n} pattern${n === 1 ? "" : "s"}` : ""]
449
- .filter(Boolean)
450
- .join(", ");
451
- }
452
- /** What each humanize level does, for `show`. */
453
- const HUMANIZE_TEXT = {
454
- off: "Playwright's own (humanize off)",
455
- light: "human-like pointer and typing (light)",
456
- full: "human-like pointer, typing and scrolling (full)",
457
- adaptive: "light, full on sites that showed a challenge (adaptive)",
458
- };
459
- export function show(m, id, args, io) {
460
- const p = parseFlags(args, JSON_FLAG, 1);
461
- if (!m.identityExists(id, io.env))
462
- return fail(`identity "${id}" does not exist (turno identity add browser:${id})`);
463
- const { path, settings, problems } = m.checkIdentitySettings(id, io.env);
464
- const holder = m.inUseBy(id, io.env);
465
- const health = m.readHealth(id, io.env);
466
- if (bool(p, "json")) {
467
- emit(io, p, SHOW_JSON, {
468
- id: `browser:${id}`,
469
- dir: tildify(m.identityDir(id, io.env), io.env),
470
- settingsFile: tildify(path, io.env),
471
- settings: settings ?? null,
472
- problems,
473
- inUse: holder !== undefined,
474
- holder: holder ?? null,
475
- health: health ?? null,
476
- });
477
- return Exit.ok;
478
- }
479
- const s = style(io);
480
- const rows = [
481
- ["profile", tildify(m.identityDir(id, io.env), io.env)],
482
- [
483
- "settings",
484
- `${tildify(path, io.env)}${settings || problems.length ? "" : s.muted(" (none: Chrome's own time zone and languages)")}`,
485
- ],
486
- ];
487
- if (settings) {
488
- rows.push(["time zone", settings.timezone ?? s.muted("(the system's)")]);
489
- if (settings.locale)
490
- rows.push(["locale", settings.locale]);
491
- rows.push([
492
- "languages",
493
- settings.languages?.join(", ") ?? s.muted(settings.locale ? "(from the locale)" : "(Chrome's)"),
494
- ]);
495
- if (settings.region)
496
- rows.push(["region", settings.region]);
497
- rows.push(["health check", settings.health ? describeHealth(settings.health) : s.muted("(none)")]);
498
- if (settings.tabs)
499
- rows.push(["tabs", `${describeTabs(settings.tabs)}${s.muted(" (the rest as default)")}`]);
500
- if (settings.backgroundThrottling !== undefined)
501
- rows.push([
502
- "throttling",
503
- settings.backgroundThrottling ? "background tabs throttled" : "every tab at full speed",
504
- ]);
505
- if (settings.settle !== undefined)
506
- rows.push(["settle", settings.settle]);
507
- if (settings.block)
508
- rows.push(["blocking", describeBlock(settings.block) || s.muted("(nothing)")]);
509
- if (settings.cache)
510
- rows.push(["cache", `on, up to ${settings.cache.maxSize ?? "100MB"}`]);
511
- if (settings.keychain === "system")
512
- rows.push(["cookie key", "the system keychain (identity.json keychain)"]);
513
- if (settings.humanize)
514
- rows.push([
515
- "input",
516
- `${HUMANIZE_TEXT[settings.humanize.level] ?? settings.humanize.level}${settings.humanize.seed === undefined ? "" : s.muted(` (seed ${settings.humanize.seed})`)}`,
517
- ]);
518
- if (settings.sharing === "tabs")
519
- rows.push(["sharing", "every agent session at once, each in its own tabs"]);
520
- if (settings.tabLocks)
521
- rows.push([
522
- "tab locks",
523
- `${[
524
- settings.tabLocks.wait !== undefined ? `wait ${settings.tabLocks.wait}` : "",
525
- settings.tabLocks.release !== undefined ? `release after ${settings.tabLocks.release}` : "",
526
- ]
527
- .filter(Boolean)
528
- .join(", ")}${s.muted(settings.sharing === "tabs" ? "" : ' (used with "sharing": "tabs")')}`,
529
- ]);
530
- if (settings.engine === "lightpanda")
531
- rows.push(["engine", "Lightpanda (read mode)"]);
532
- if (settings.engine === "camoufox")
533
- rows.push(["engine", "Camoufox (its own Firefox profile)"]);
534
- if (settings.userAgent === "coherent")
535
- rows.push(["user agent", "the installed Chrome's own, checked at every launch (coherent)"]);
536
- if (settings.proxy)
537
- rows.push(["proxy", describeProxy(settings.proxy)]);
538
- if (settings.attach !== undefined)
539
- rows.push(["engine", `attach to your Chrome (${settings.attach})`]);
540
- const recorded = describeRecord(settings.record);
541
- if (recorded)
542
- rows.push(["recording", recorded]);
543
- const act = describeAct(settings.act);
544
- if (act)
545
- rows.push(["act", act]);
546
- if (settings.captcha)
547
- rows.push(["captcha", `on: ${settings.captcha.provider} at ${settings.captcha.endpoint}`]);
548
- if (settings.live?.enabled)
549
- rows.push([
550
- "live view",
551
- `on (turno browser live ${id}); a paused call waits up to ${settings.live.wait ?? "2m"}`,
552
- ]);
553
- rows.push(["created", settings.created]);
554
- rows.push(["updated", settings.updated]);
555
- }
556
- if (health) {
557
- const state = health.status === "ok"
558
- ? s.ok("signed in")
559
- : health.status === "needs_auth"
560
- ? s.err("NEEDS_AUTH")
561
- : s.warn("check failed");
562
- rows.push(["last check", `${state} ${s.muted(`${health.checkedAt}${health.detail ? `: ${health.detail}` : ""}`)}`]);
563
- }
564
- rows.push([
565
- "state",
566
- holder ? s.warn(holder.replace(/^browser identity "[^"]+" is /, "").replace(/\. .*$/, "")) : s.ok("free"),
567
- ]);
568
- io.out(s.bold(`browser:${id}`));
569
- const width = Math.max(...rows.map(([k]) => k.length));
570
- for (const [k, v] of rows)
571
- io.out(s.kv(k, v, width));
572
- for (const problem of problems)
573
- io.out(s.note("err", `identity.json ${problem}`));
574
- if (health?.status === "needs_auth")
575
- io.out(s.note("info", `sign in again: turno browser login ${id}`));
576
- return Exit.ok;
577
- }
578
- const SET_FLAGS = { ...SETTINGS_FLAGS, "dry-run": { type: "boolean" }, ...JSON_FLAG };
579
- /** The arguments of `set` after the identity, for the usage line. */
580
- export const SET_SYNOPSIS = "[--timezone <zone>] [--locale <tag>] [--languages <tag,...>] [--region <CC>] [--health-url <url>] [--health-text <text>] [--health-selector <css>] [--no-health] " +
581
- "[--tabs-max <n>] [--tabs-popups close|keep] [--tabs-park <duration>] [--tabs-close <duration>] [--no-tabs] [--background-throttling true|false] [--settle <duration>] " +
582
- "[--block-trackers true|false] [--block-types image,media,font] [--block-patterns <host|glob>,...] [--no-block] [--cache] [--cache-max-size <size>] [--no-cache] [--humanize off|light|full|adaptive] [--sharing session|tabs] [--tab-lock-wait <duration>] [--tab-lock-release <duration>] " +
583
- "[--engine chrome|lightpanda] [--attach auto|<dir>|<url>] [--record-flows true|false] [--record-traces true|false] [--record-screenshots true|false] [--record-max-size <size>] [--no-record] " +
584
- "[--act] [--act-sampling true|false] [--act-provider chat-completions] [--act-endpoint <url>] [--act-model <name>] [--act-key keychain:<item>] [--act-max-steps <n>] [--act-max-tokens <n>] [--act-timeout <duration>] [--no-act] " +
585
- "[--captcha-provider task-api] [--captcha-endpoint <url>] [--captcha-key keychain:<item>] [--captcha-timeout <duration>] [--no-captcha] [--live true|false] [--live-wait <duration>] [--no-live] " +
586
- "[--user-agent coherent] [--proxy-server <url>] [--proxy-username <name|keychain:item>] [--proxy-password keychain:<item>] [--no-proxy] [--dry-run] [--json]";
587
- /** More help for `set`: what each tuning flag writes to identity.json. */
588
- export const SET_DETAILS = `Each flag writes one key of identity.json; an empty value (--settle "") removes it, and
589
- --no-health, --no-tabs, --no-block and --no-cache remove a whole group. A flag of a group
590
- changes only its part: the rest of that group stays.
591
-
592
- How the host runs this identity's Chrome (read at every Chrome start):
593
- --tabs-max <n> most tabs open at once, 0 for no cap (default 8)
594
- --tabs-popups close|keep close popups the agent did not open (default close)
595
- --tabs-park <duration> park an unused tab on about:blank, "0" never (default 5m)
596
- --tabs-close <duration> close an unused tab, "0" never (default 15m)
597
- --background-throttling <bool> let Chrome slow tabs that are not in front (default false)
598
- --settle <duration> wait after each action for the work it started, "0" to "10s"
599
- --block-trackers <bool> block a built-in list of ad and analytics hosts
600
- --block-types <list> block image, media and font requests (never the page itself)
601
- --block-patterns <list> block host names (and subdomains) or URL globs with *
602
- --cache keep images, fonts, styles and scripts on disk (100MB)
603
- --cache-max-size <size> the cache's size, "1MB" to "10GB"; turns the cache on
604
- --sharing session|tabs "tabs": every agent session at once, each in its own locked
605
- tabs (default "session": one at a time); mcp.toml then needs
606
- exclusive = false for the identity's server
607
- --tab-lock-wait <duration> with tabs: how long a call waits for a tab another session
608
- holds, "0" (fail at once) to "10m" (default 10s)
609
- --tab-lock-release <duration> with tabs: a session without calls lets go of its tabs after
610
- this, "0" (free between calls) to "24h" (default 5m)
611
-
612
- Blocking without the cache turns Chrome's own HTTP cache off: use them together.
613
-
614
- Input:
615
- --humanize <level> off (default), light (the pointer travels a curve to a point
616
- inside the target, keys typed with human delays), full (plus
617
- overshoot, reading pauses, wheel scrolling) or adaptive
618
- (light, full on a site after a challenge page there)
619
-
620
- Which engine runs this identity (all off by default):
621
- --engine lightpanda read mode: Lightpanda instead of Chrome, for reading pages;
622
- needs lightpanda on PATH (turno browser doctor says how)
623
- --engine camoufox Camoufox (a Firefox build) with its own profile; not
624
- recommended for your own accounts; needs Camoufox and
625
- playwright-core (turno browser doctor says how); no captcha
626
- solving, and no picture in the live view
627
- --attach auto|<dir>|<url> use the Chrome you have open instead of the identity's own:
628
- "auto" is your default Chrome profile, after you turn on
629
- chrome://inspect/#remote-debugging; Chrome asks you to allow
630
- each connection, and the agent then sees all its windows
631
-
632
- What turno-browser records for this identity (all off by default; turno browser record):
633
- --record-flows <bool> keep every session's actions as a flow (auto-<time>, newest 20)
634
- --record-traces <bool> a Playwright trace of each browser session (turno browser traces)
635
- --record-screenshots <bool> a screenshot after each action
636
- --record-max-size <size> cap of the traces and screenshots, "10MB" to "10GB" (default 200MB)
637
- Vault sign-ins and passwords never reach a flow, a trace or a screenshot.
638
-
639
- Not recommended, off by default, for your own accounts only (they send page content to a third
640
- party you pick, and many sites' terms forbid them; the server lists their tools from its next start):
641
- --act natural language actions (browser_act, browser_extract,
642
- browser_observe) with your client's model (MCP sampling)
643
- --act-provider chat-completions a model API to use when the client has no sampling, with
644
- --act-endpoint <url> its base URL (https, or http on this machine),
645
- --act-model <name> the model name it expects and
646
- --act-key keychain:<item> its key in the secret store (turno secret set <item>)
647
- --act-sampling <bool> false: never ask the client, always use the provider
648
- --act-max-steps <n> most actions per call, 1 to 30 (default 10)
649
- --act-max-tokens <n> most model tokens per call (default 50000)
650
- --act-timeout <duration> longest call, "10s" to "10m" (default 2m)
651
- --captcha-provider task-api solve captcha widgets (browser_solve_captcha) through a solver
652
- --captcha-endpoint <url> service that speaks the createTask protocol, at this URL,
653
- --captcha-key keychain:<item> with its account key in the secret store
654
- --captcha-timeout <duration> longest wait for a solution (default 3m)
655
- --no-act, --no-captcha turn them off
656
-
657
- The live view and take-over (off by default; turno browser live, pause, resume):
658
- --live <bool> serve a view of the agent's tab on 127.0.0.1 and let you pause
659
- the agent to take the controls (from the next server start)
660
- --live-wait <duration> how long a paused call waits for you, "5s" to "30m" (default 2m)
661
-
662
- Network and user agent (not recommended, all off by default; for your own accounts and sites
663
- you may automate):
664
- --user-agent coherent the installed Chrome's own user agent and client hints, with
665
- this identity's languages and time zone, checked at every
666
- launch (a headless Chrome stops saying HeadlessChrome); turno
667
- never takes a typed user agent
668
- --proxy-server <url> send this identity's traffic through a proxy: http://,
669
- https://, socks4:// or socks5://host:port; its operator sees
670
- where you go, and sites see its address
671
- --proxy-username <name> the proxy user name, or keychain:<item>
672
- --proxy-password keychain:<item> the password, only from the secret store (turno secret set)
673
- --no-proxy remove the proxy`;
674
- /** The flags of `set`, for completion. */
675
- export const SET_FLAG_NAMES = ["--dry-run", "--json", ...SETTINGS_FLAG_NAMES];
676
- /**
677
- * The package's own validation, run on a copy: identity.json is copied to a throwaway data
678
- * folder and the patch written there, so `--dry-run` refuses exactly what the write would and
679
- * shows the file it would leave, without touching the real one.
680
- */
681
- function rehearse(m, id, patch, env) {
682
- const dir = mkdtempSync(join(env.TMPDIR || tmpdir(), "turno-identity-"));
683
- try {
684
- const copy = { ...env, TURNO_DATA_DIR: dir };
685
- const from = m.identitySettingsPath(id, env);
686
- const to = m.identitySettingsPath(id, copy);
687
- mkdirSync(dirname(to), { recursive: true, mode: 0o700 });
688
- if (existsSync(from))
689
- copyFileSync(from, to);
690
- return m.writeIdentitySettings(id, patch, copy);
691
- }
692
- finally {
693
- rmSync(dir, { recursive: true, force: true });
694
- }
695
- }
696
- /** What turning on natural language actions or captcha solving costs, said once at `set`. */
697
- function optInNotes(id, patch) {
698
- const notes = [];
699
- const restart = `its tools are listed once browser-${id} starts again (a new agent session, or turno mcp daemon restart)`;
700
- if (patch.act)
701
- notes.push(`natural language actions: each call sends the instruction and a snapshot of the page to the model (your client's, or the provider you set), with vault values and sensitive fields hidden; ${restart}. Undo with --no-act.`);
702
- if (patch.captcha)
703
- notes.push(`captcha solving: the solver service sees the page address and the captcha, and solving a site's captchas by machine may break its terms; use it only for your own accounts. Every use goes to the reputation log; ${restart}. Undo with --no-captcha.`);
704
- const own = "Meant for your own accounts and sites you may automate.";
705
- if (typeof patch.userAgent === "string")
706
- notes.push(`userAgent coherent: Chrome's real version and platform are kept, so a site sees one coherent browser; a site may still notice automation by other means. ${own}`);
707
- if (patch.proxy)
708
- notes.push(`proxy ${patch.proxy.server}: its operator sees where this identity goes, sites see the proxy's address instead of yours, and a sign-in from a new network can lock an account; many sites' terms forbid it. ${own}`);
709
- if (patch.engine === "camoufox")
710
- notes.push(`engine camoufox: a Firefox build that reports values other than the computer's own is something sites look for, the Chrome profile's sign-ins do not carry over, and it needs Camoufox and playwright-core (turno browser doctor). ${own}`);
711
- return notes;
712
- }
713
- /** What mcp.toml needs after `--sharing`: mcpd decides how many sessions reach the server. */
714
- function sharingNote(id, sharing) {
715
- return sharing === "tabs"
716
- ? `In mcp.toml, set exclusive = false for [server.browser-${id}] (and drop lease), then run \`turno mcp sync\`: mcpd then lets every session in, and each gets its own tabs.`
717
- : `In mcp.toml, set exclusive = true for [server.browser-${id}], then run \`turno mcp sync\`: one agent session at a time.`;
718
- }
719
- export function set(m, id, args, io) {
720
- const p = parseFlags(args, SET_FLAGS, 1);
721
- if (!m.identityExists(id, io.env))
722
- return fail(`identity "${id}" does not exist (turno identity add browser:${id})`);
723
- const patch = settingsPatch(p, m.checkIdentitySettings(id, io.env).settings);
724
- if (!hasSettings(patch))
725
- return fail(`nothing to set: pass ${SETTINGS_FLAG_NAMES.join(", ")} (an empty value removes one)`);
726
- const dryRun = bool(p, "dry-run");
727
- let settings;
728
- try {
729
- settings = dryRun ? rehearse(m, id, patch, io.env) : m.writeIdentitySettings(id, patch, io.env);
730
- }
731
- catch (err) {
732
- if (err.name === "IdentityError")
733
- return fail(flagMessage(err.message));
734
- throw err;
735
- }
736
- if (bool(p, "json")) {
737
- emit(io, p, SET_JSON, {
738
- id: `browser:${id}`,
739
- settingsFile: tildify(m.identitySettingsPath(id, io.env), io.env),
740
- dryRun,
741
- changes: patch,
742
- settings,
743
- });
744
- return Exit.ok;
745
- }
746
- if (dryRun) {
747
- io.out(`(dry run) would update identity.json of "${id}": ${JSON.stringify(patch)}`);
748
- return Exit.ok;
749
- }
750
- io.out(`updated identity.json of "${id}"; the next Chrome start of browser-${id} uses it\n`);
751
- const code = show(m, id, [], io);
752
- if (patch.sharing !== undefined)
753
- io.out(`\n${sharingNote(id, settings.sharing)}`);
754
- for (const note of optInNotes(id, patch))
755
- io.out(style(io).note("warn", note));
756
- if (typeof patch.attach === "string") {
757
- const s = style(io);
758
- io.out(s.note("warn", "attach mode: the agent works in your own Chrome and sees every window and signed-in site of that profile. " +
759
- "Turn on remote debugging at chrome://inspect/#remote-debugging and allow each connection Chrome asks about; " +
760
- 'turno closes only the tabs it opened. Undo with --attach "".'));
761
- }
762
- return code;
763
- }
764
- const DOCTOR_FLAGS = { fix: { type: "boolean" }, "no-launch": { type: "boolean" }, ...JSON_FLAG };
765
- const SECTIONS = [
766
- ["Chrome", (a) => a === "chrome"],
767
- ["System", (a) => a === "system"],
768
- ["Engines", (a) => a === "engines"],
769
- ["Identities", (a) => a === "identities" || a.startsWith("identity ")],
770
- ];
771
- /** The value of `--flag v` or `--flag=v` in a server's args. */
772
- function flagValue(args, flag) {
773
- for (let i = 0; i < args.length; i++) {
774
- if (args[i] === flag)
775
- return args[i + 1];
776
- if (args[i].startsWith(`${flag}=`))
777
- return args[i].slice(flag.length + 1);
778
- }
779
- return undefined;
780
- }
781
- /**
782
- * The mcp.toml servers that run turno-browser-mcp for an identity, for the doctor's check of
783
- * `exclusive` against the identity's `sharing`. An unreadable mcp.toml gives none (`turno doctor`
784
- * reports it).
785
- */
786
- export function servedIdentities(env) {
787
- let manifest;
788
- try {
789
- manifest = loadManifest(env);
790
- }
791
- catch {
792
- return [];
793
- }
794
- const out = [];
795
- for (const [name, server] of Object.entries(manifest.servers)) {
796
- if (server.kind !== "stdio")
797
- continue;
798
- const runs = [server.command, ...server.args].some((a) => basename(a) === "turno-browser-mcp");
799
- const identity = flagValue(server.args, "--identity");
800
- if (!runs || !identity)
801
- continue;
802
- const sharing = flagValue(server.args, "--sharing");
803
- out.push({
804
- name,
805
- identity: identity.replace(/^browser:/, ""),
806
- exclusive: server.exclusive,
807
- scope: server.scope,
808
- ...(sharing ? { sharing } : {}),
809
- });
810
- }
811
- return out;
812
- }
813
- export async function doctor(m, args, io) {
814
- const p = parseFlags(args, DOCTOR_FLAGS, 0);
815
- const json = bool(p, "json");
816
- const report = await m.runDoctor({
817
- env: io.env,
818
- fix: bool(p, "fix"),
819
- launch: !bool(p, "no-launch"),
820
- servers: servedIdentities(io.env),
821
- });
822
- const failed = report.checks.some((c) => c.level === "fail");
823
- const exit = failed ? Exit.failure : Exit.ok;
824
- const status = (c) => (c.level === "info" ? "skip" : c.level);
825
- const n = (l) => report.checks.filter((c) => c.level === l).length;
826
- if (json) {
827
- emit(io, p, DOCTOR_JSON, {
828
- ok: !failed,
829
- counts: { ok: n("ok"), warn: n("warn"), fail: n("fail"), skip: n("info") },
830
- fixed: report.fixed,
831
- checks: report.checks.map((c) => ({
832
- area: c.area,
833
- status: status(c),
834
- text: c.text,
835
- fix: c.level === "ok" ? null : (c.fix ?? null),
836
- auto: Boolean(c.auto) && (c.level === "warn" || c.level === "fail"),
837
- manual: c.level === "ok" ? null : (c.manual ?? null),
838
- })),
839
- });
840
- return exit;
841
- }
842
- const s = style(io);
843
- for (const f of report.fixed)
844
- io.out(s.check("ok", `fixed: ${f}`));
845
- if (report.fixed.length)
846
- io.out("");
847
- const ICON = { ok: "ok", warn: "warn", fail: "err", info: "skip" };
848
- let first = true;
849
- for (const [title, has] of SECTIONS) {
850
- const rows = report.checks.filter((c) => has(c.area));
851
- if (!rows.length)
852
- continue;
853
- if (!first)
854
- io.out("");
855
- first = false;
856
- io.out(s.header(title));
857
- let area = "";
858
- for (const c of rows) {
859
- if (c.area.startsWith("identity ") && c.area !== area)
860
- io.out(` ${s.bold(`browser:${c.area.slice("identity ".length)}`)}`);
861
- area = c.area;
862
- const indent = c.area.startsWith("identity ") ? 4 : 2;
863
- const text = c.level === "fail" ? s.err(c.text) : c.level === "info" ? s.muted(c.text) : c.text;
864
- io.out(s.note(ICON[c.level], text, indent));
865
- if (c.level === "ok")
866
- continue;
867
- const under = " ".repeat(indent + 2);
868
- const label = c.level === "info" ? "optional:" : "fix:";
869
- if (c.fix)
870
- io.out(s.wrap(`${under}${s.muted(label)} `, `${c.level === "info" ? s.muted(c.fix) : s.bold(c.fix)}${c.auto ? s.muted(" (runs with --fix)") : ""}`));
871
- else if (c.manual)
872
- io.out(s.wrap(`${under}${s.muted("manual:")} `, c.manual));
873
- }
874
- }
875
- io.out("");
876
- io.out([
877
- `${n("ok")} ok`,
878
- n("warn") ? `${n("warn")} warning${n("warn") === 1 ? "" : "s"}` : "",
879
- n("fail") ? `${n("fail")} failure${n("fail") === 1 ? "" : "s"}` : "",
880
- ]
881
- .filter(Boolean)
882
- .join(", "));
883
- return exit;
884
- }
885
- export function reputation(m, args, io, checkId) {
886
- const p = parseFlags(args, JSON_FLAG, 1);
887
- const id = p.positionals[0] === undefined ? undefined : checkId(p.positionals[0].replace(/^browser:/, ""));
888
- let report;
889
- try {
890
- report = m.reputationReport(io.env, id ? [id] : undefined);
891
- }
892
- catch (err) {
893
- return fail(err.message);
894
- }
895
- if (bool(p, "json")) {
896
- emit(io, p, REPUTATION_JSON, report.identities.map((i) => ({
897
- id: `browser:${i.id}`,
898
- file: tildify(i.file, io.env),
899
- total: i.total,
900
- sites: i.sites,
901
- })));
902
- return Exit.ok;
903
- }
904
- const s = style(io);
905
- if (!report.identities.length) {
906
- io.out("No browser identities yet. Create one with `turno identity add browser:<id>`.");
907
- return Exit.ok;
908
- }
909
- const TREND = { up: s.warn("up"), down: s.ok("down"), flat: s.muted("flat") };
910
- for (const [i, ident] of report.identities.entries()) {
911
- if (i)
912
- io.out("");
913
- io.out(s.header(`browser:${ident.id}`));
914
- if (!ident.sites.length) {
915
- io.out(` ${s.muted("no challenges recorded")}`);
916
- continue;
917
- }
918
- // The solved column shows only once a captcha solver answered (identity.json `captcha`).
919
- const solved = ident.sites.some((x) => x.solved > 0);
920
- const head = [
921
- "site",
922
- "total",
923
- "captcha",
924
- "verify",
925
- "block",
926
- ...(solved ? ["solved"] : []),
927
- "7d",
928
- "prev 7d",
929
- "trend",
930
- "last seen",
931
- ].map((h) => s.muted(h));
932
- const rows = ident.sites.map((x) => [
933
- x.site,
934
- String(x.total),
935
- String(x.captcha),
936
- String(x.verify),
937
- String(x.block),
938
- ...(solved ? [String(x.solved)] : []),
939
- String(x.last7d),
940
- String(x.prev7d),
941
- TREND[x.trend],
942
- x.lastSeen,
943
- ]);
944
- const right = { align: "right" };
945
- for (const l of s.table([head, ...rows], {
946
- columns: [{}, right, right, right, right, ...(solved ? [right] : []), right, right, {}, { drop: 1 }],
947
- }))
948
- io.out(l);
949
- }
950
- return Exit.ok;
951
- }
952
- //# sourceMappingURL=browser-identity.js.map