turno-cli 0.3.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.
@@ -0,0 +1,118 @@
1
+ import { spawn } from "node:child_process";
2
+ import { JSON_FLAG, bool, parseFlags } from "../args.js";
3
+ import { Exit } from "../exit.js";
4
+ import { fail } from "../io.js";
5
+ import { emit, jsonOutput } from "../output.js";
6
+ import { style } from "../style.js";
7
+ /** `turno browser live|pause|resume <id> --json`. */
8
+ export const LIVE_JSON = jsonOutput([
9
+ "identity",
10
+ "pid",
11
+ "port",
12
+ "started",
13
+ "paused",
14
+ "waiting",
15
+ "busy",
16
+ "wait",
17
+ "browser",
18
+ "engine",
19
+ "view",
20
+ "showing",
21
+ "pinned",
22
+ "hidden",
23
+ "viewers",
24
+ "tabs",
25
+ ]);
26
+ const openInBrowser = async (url, io) => {
27
+ const { openInvocation } = await import("./open.js");
28
+ const inv = openInvocation(undefined, url, io.env);
29
+ await new Promise((resolve, reject) => {
30
+ const child = spawn(inv.command, inv.args, { stdio: "ignore", env: io.env, detached: true });
31
+ child.on("error", reject);
32
+ child.on("spawn", () => {
33
+ child.unref();
34
+ resolve();
35
+ });
36
+ });
37
+ };
38
+ function needIdentity(mod, id, sub, io) {
39
+ if (!id)
40
+ return fail(`browser ${sub} needs an identity id (for example: turno browser ${sub} school)`);
41
+ mod.assertIdentityId(id);
42
+ if (!mod.identityExists(id, io.env))
43
+ return fail(`identity "${id}" does not exist (turno identity add browser:${id})`);
44
+ return id;
45
+ }
46
+ /** `120000` as "2m", `90000` as "90s". */
47
+ function seconds(ms) {
48
+ return ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000}m` : `${Math.round(ms / 1000)}s`;
49
+ }
50
+ /** Why there is no live view to talk to: off, or no server running now. */
51
+ function notServing(mod, id, io) {
52
+ const on = mod.checkIdentitySettings(id, io.env).settings?.live?.enabled === true;
53
+ return fail(on
54
+ ? `no turno-browser-mcp serves "${id}" right now. The live view starts with the server (an agent session that uses browser-${id} starts it).`
55
+ : `the live view is off for "${id}" (the default). Turn it on with turno browser set ${id} --live true; it starts with the next turno-browser-mcp for this identity.`);
56
+ }
57
+ function describe(status, io) {
58
+ const s = style(io);
59
+ const state = status.paused
60
+ ? `paused for ${seconds(Math.max(0, Date.now() - Date.parse(status.paused.since)))} (${status.paused.by})${status.waiting ? `, ${status.waiting} call${status.waiting === 1 ? "" : "s"} waiting` : ""}`
61
+ : status.busy
62
+ ? "the agent is working"
63
+ : "the agent is idle";
64
+ io.out(`${s.bold(status.identity)} ${state}`);
65
+ io.out(s.muted(` browser ${status.browser ? `running (${status.engine})` : "not running"}; a paused call waits up to ${seconds(status.wait)}`));
66
+ if (!status.view.available && status.view.reason)
67
+ io.out(s.note("info", status.view.reason, 2));
68
+ for (const t of status.tabs)
69
+ io.out(` ${t.id === status.showing ? "*" : " "} ${t.title || "(no title)"} ${s.muted(t.url)}${t.session ? s.muted(` [${t.session}]`) : ""}`);
70
+ }
71
+ const LIVE_FLAGS = { "no-open": { type: "boolean" }, ...JSON_FLAG };
72
+ export async function live(mod, args, io, open = openInBrowser) {
73
+ const p = parseFlags(args, LIVE_FLAGS, 1);
74
+ const id = needIdentity(mod, p.positionals[0], "live", io);
75
+ const status = await mod.liveStatus(id, io.env);
76
+ if (!status)
77
+ return notServing(mod, id, io);
78
+ if (bool(p, "json")) {
79
+ emit(io, p, LIVE_JSON, status);
80
+ return Exit.ok;
81
+ }
82
+ describe(status, io);
83
+ if (!status.view.available || bool(p, "no-open"))
84
+ return Exit.ok;
85
+ await open(await mod.liveLink(id, io.env), io);
86
+ io.err(style(io).muted(`opened the live view of "${id}" in your browser (the link works once; run this again for a new one)`));
87
+ return Exit.ok;
88
+ }
89
+ export async function pause(mod, args, io) {
90
+ const p = parseFlags(args, JSON_FLAG, 1);
91
+ const id = needIdentity(mod, p.positionals[0], "pause", io);
92
+ if (!(await mod.liveStatus(id, io.env)))
93
+ return notServing(mod, id, io);
94
+ const status = await mod.livePause(id, io.env);
95
+ if (bool(p, "json")) {
96
+ emit(io, p, LIVE_JSON, status);
97
+ return Exit.ok;
98
+ }
99
+ io.out(`paused "${id}": the agent's next call waits up to ${seconds(status.wait)} for you. Act in the browser${status.view.available ? ` or the live view (turno browser live ${id})` : ""}, then: turno browser resume ${id}`);
100
+ return Exit.ok;
101
+ }
102
+ export async function resume(mod, args, io) {
103
+ const p = parseFlags(args, JSON_FLAG, 1);
104
+ const id = needIdentity(mod, p.positionals[0], "resume", io);
105
+ const before = await mod.liveStatus(id, io.env);
106
+ if (!before)
107
+ return notServing(mod, id, io);
108
+ const status = await mod.liveResume(id, io.env);
109
+ if (bool(p, "json")) {
110
+ emit(io, p, LIVE_JSON, status);
111
+ return Exit.ok;
112
+ }
113
+ io.out(before?.paused
114
+ ? `resumed "${id}": the agent's waiting calls go on, and each is told what changed.`
115
+ : `"${id}" was not paused.`);
116
+ return Exit.ok;
117
+ }
118
+ //# sourceMappingURL=browser-live.js.map
@@ -4,7 +4,10 @@ import { group } from "../group.js";
4
4
  import { fail, needsAnswer, paint } from "../io.js";
5
5
  import { OPTIONAL, loadOptional, notInstalled } from "../optional.js";
6
6
  import { emit, jsonOutput } from "../output.js";
7
+ import { ACTION_NAMES, DO_DETAILS, DO_JSON, DO_FLAG_NAMES, DO_SYNOPSIS, browserDo, defaultDoDeps, } from "./browser-do.js";
8
+ import * as flowCmd from "./browser-flows.js";
7
9
  import * as ident from "./browser-identity.js";
10
+ import * as liveCmd from "./browser-live.js";
8
11
  import * as session from "./browser-session.js";
9
12
  import { vaultCommand } from "./browser-vault.js";
10
13
  /** `turno browser bench --json`: turno-browser's report. */
@@ -15,7 +18,7 @@ const IDENTITIES_JSON = jsonOutput(["id", "inUse", "dir"]);
15
18
  * The API version this turno was built against. Typed by the package's own constant, so a
16
19
  * change of its API_VERSION in the workspace fails the typecheck until this line follows.
17
20
  */
18
- export const BROWSER_API = { major: 1, minor: 2 };
21
+ export const BROWSER_API = { major: 1, minor: 10 };
19
22
  export const INSTALL_HINT = OPTIONAL.browser.install;
20
23
  export const NOT_INSTALLED = notInstalled(OPTIONAL.browser);
21
24
  /** A turno-browser this command can drive: its API object has the calls every subcommand needs. */
@@ -153,7 +156,7 @@ function add(mod, args, io) {
153
156
  io.out(`identity "${id}" ready at ${tildify(info.dir, io.env)}`);
154
157
  io.out(`settings (time zone, languages, health check) in ${tildify(mod.identitySettingsPath(id, io.env), io.env)}`);
155
158
  io.out(`\nAdd this to ${tildify(paths(io.env).mcpFile, io.env)}, then run \`turno mcp sync\`:\n`);
156
- io.out(mod.manifestSnippet(id));
159
+ io.out(settings.sharing === "tabs" ? mod.manifestSnippet(id, { sharing: "tabs" }) : mod.manifestSnippet(id));
157
160
  io.out(`Sign in to your sites once with \`turno identity login browser:${id}\`.`);
158
161
  return 0;
159
162
  }
@@ -223,13 +226,27 @@ export async function dispatch(mod, sub, rest, io, deps = defaultDeps) {
223
226
  return await ident.doctor(mod, rest, io);
224
227
  case "reputation":
225
228
  return ident.reputation(mod, rest, io, (id) => checkId(mod, id, "reputation"));
229
+ case "flows":
230
+ return flowCmd.flows(mod, rest, io);
231
+ case "replay":
232
+ return await flowCmd.replay(mod, rest, io);
233
+ case "traces":
234
+ return await flowCmd.traces(mod, rest, io);
235
+ case "record":
236
+ return flowCmd.record(mod, rest, io);
237
+ case "live":
238
+ return await liveCmd.live(mod, rest, io, deps.openUrl);
239
+ case "pause":
240
+ return await liveCmd.pause(mod, rest, io);
241
+ case "resume":
242
+ return await liveCmd.resume(mod, rest, io);
226
243
  default:
227
244
  return fail(`unknown browser command "${sub}"`);
228
245
  }
229
246
  }
230
247
  catch (err) {
231
248
  const name = err.name;
232
- if (name === "IdentityError" || name === "VaultError" || name === "SealError")
249
+ if (["IdentityError", "VaultError", "SealError", "FlowError", "LiveError"].includes(name))
233
250
  return fail(err.message);
234
251
  throw err;
235
252
  }
@@ -238,9 +255,25 @@ const FOOTER = `A developer diagnostic for browser engine compatibility. It need
238
255
  turno-browser package (${INSTALL_HINT}).
239
256
  Identities are persistent Chrome profiles served by turno-browser-mcp, one session at a time
240
257
  through mcpd; turno identity manages them too (browser:<id>). Ids use lowercase letters,
241
- digits, "-" and "_", for example "school".`;
258
+ digits, "-" and "_", for example "school".
259
+ turno browser do <id> <action> runs one action (open, snapshot, click, type, read...) on an
260
+ identity's browser through mcpd, for coding agents that prefer shell commands (do --help).`;
261
+ /**
262
+ * `turno browser <id> <action>`, the short form of `turno browser do <id> <action>`: taken when
263
+ * the first word is not a browser subcommand and the second is an action. An identity named like
264
+ * a subcommand (`show`, `flows`) needs the long form, and the docs and the skill use the long form
265
+ * so a later subcommand can never change what a written command does.
266
+ */
267
+ function shortDo(args, subs) {
268
+ const [first, second] = args;
269
+ return (first !== undefined &&
270
+ second !== undefined &&
271
+ !(first in subs) &&
272
+ /^[a-z0-9][a-z0-9_-]*$/.test(first) &&
273
+ ACTION_NAMES.includes(second));
274
+ }
242
275
  /** The `browser` command, with its loader and prompt injectable for tests. */
243
- export function browserCommand(deps = defaultDeps) {
276
+ export function browserCommand(deps = defaultDeps, doDeps = defaultDoDeps) {
244
277
  const withModule = (sub) => async (args, io) => {
245
278
  const mod = await deps.load(io);
246
279
  if (!mod) {
@@ -299,6 +332,87 @@ export function browserCommand(deps = defaultDeps) {
299
332
  ownHelp: true,
300
333
  run: (args, io) => vaultCommand(deps).run(args, io),
301
334
  },
335
+ record: {
336
+ summary: "what an identity records (flows, traces, screenshots); turn it on or off",
337
+ synopsis: "<id> [--flows] [--traces] [--screenshots] [--max-size <size>] [--off] [--dry-run] [--json]",
338
+ details: `With no flag, shows what the identity records and where. --flows, --traces and --screenshots
339
+ turn those on (the next Chrome start uses them), --off turns everything off; turn one off with
340
+ turno browser set <id> --record-traces false. All are off by default.
341
+
342
+ flows every session's actions saved as a flow (auto-<time>, newest 20 kept)
343
+ traces a Playwright trace of each browser session (turno browser traces)
344
+ screenshots a screenshot after each action
345
+
346
+ Vault sign-ins never reach a flow, a trace or a screenshot: the trace stops before a fill and
347
+ starts again after the page navigates, and a password or one-time code is never saved.`,
348
+ flags: ["--flows", "--traces", "--screenshots", "--max-size", "--off", "--dry-run", "--json"],
349
+ json: flowCmd.RECORD_JSON,
350
+ run: withModule("record"),
351
+ },
352
+ flows: {
353
+ summary: "an identity's saved flows; name one to see its steps, --remove to delete it",
354
+ synopsis: "<id> [<flow>] [--remove] [--dry-run] [--json]",
355
+ flags: ["--remove", "--dry-run", "--json"],
356
+ json: flowCmd.FLOWS_JSON,
357
+ run: withModule("flows"),
358
+ },
359
+ replay: {
360
+ summary: "run a saved flow on the identity's Chrome, without an agent",
361
+ synopsis: "<id> <flow> [--param <name=value>]... [--from <step>] [--headless] [--json]",
362
+ details: `Runs the flow through turno-browser-mcp, the same way an agent's browser_replay does. A
363
+ sensitive parameter is never a value on the command line: pass --param <name>=keychain:<item>
364
+ (store it once with turno secret set <item>), or type it at the hidden prompt. When a step fails,
365
+ the report says which locators it tried; --from continues at a later step.`,
366
+ flags: ["--param", "--from", "--headless", "--json"],
367
+ json: flowCmd.REPLAY_JSON,
368
+ run: withModule("replay"),
369
+ },
370
+ traces: {
371
+ summary: "an identity's recordings (traces, screenshots); --open shows a trace in the viewer",
372
+ synopsis: "<id> [<recording>] [--open] [--segment <n>] [--json]",
373
+ details: `--open serves the trace on 127.0.0.1 with the trace viewer patchright-core ships and opens it
374
+ in your default browser; Ctrl-C stops it. A recording has one trace per stretch of activity (a
375
+ vault sign-in or the idle limit ends one): --segment picks one, the last by default.`,
376
+ flags: ["--open", "--segment", "--json"],
377
+ json: flowCmd.TRACES_JSON,
378
+ run: withModule("traces"),
379
+ },
380
+ live: {
381
+ summary: "watch the agent in an identity's browser and take the controls (opens the live view)",
382
+ synopsis: "<id> [--no-open] [--json]",
383
+ details: `Shows what the agent is doing (paused or not, its tabs) and opens the live view in your
384
+ default browser: the agent's tab as a picture, Pause and Resume buttons, and while the agent is
385
+ paused, your clicks, keys and scrolls go to the page. The view is served on 127.0.0.1 only; the
386
+ link it opens works once. Off by default: turn it on with turno browser set <id> --live true
387
+ (it starts with the next turno-browser-mcp for the identity).
388
+
389
+ Read mode (Lightpanda) has no pixels, attach mode is your own Chrome, which you already see, and
390
+ Camoufox (Firefox) has no Chrome screencast: there the view is off, and pause and resume still work. A page that holds a vault or password
391
+ value is never shown until it navigates.`,
392
+ flags: ["--no-open", "--json"],
393
+ json: liveCmd.LIVE_JSON,
394
+ run: withModule("live"),
395
+ },
396
+ pause: {
397
+ summary: "pause the agent in an identity's browser: its next call waits until you resume",
398
+ synopsis: "<id> [--json]",
399
+ details: `A call that is running finishes; the next one waits up to the identity's live wait (2m by
400
+ default), then fails and tells the agent you still have the browser. A batch or replay stops at its
401
+ next step. In a headed Chrome the agent's tab comes to the front. Needs the live view on.`,
402
+ flags: ["--json"],
403
+ json: liveCmd.LIVE_JSON,
404
+ run: withModule("pause"),
405
+ },
406
+ resume: {
407
+ summary: "give the browser back to the agent; each waiting call is told what changed",
408
+ synopsis: "<id> [--json]",
409
+ details: `The waiting calls go on. Each starts with a note: how long the pause lasted and what changed
410
+ (the current tab's URL and title, tabs opened and closed, your input in the view). When something
411
+ changed, a call that does more than read does not run, and the agent gets a fresh snapshot instead.`,
412
+ flags: ["--json"],
413
+ json: liveCmd.LIVE_JSON,
414
+ run: withModule("resume"),
415
+ },
302
416
  export: {
303
417
  summary: "write an identity's cookies and site storage to a file encrypted with a passphrase",
304
418
  synopsis: "<id> --out <file> [--expires 7d] [--force]",
@@ -324,6 +438,15 @@ export function browserCommand(deps = defaultDeps) {
324
438
  flags: ["--url"],
325
439
  run: withModule("login"),
326
440
  },
441
+ do: {
442
+ summary: "one action on an identity's browser from the shell: open, snapshot, click, type, read...",
443
+ synopsis: DO_SYNOPSIS,
444
+ details: DO_DETAILS,
445
+ ownHelp: true,
446
+ json: DO_JSON,
447
+ flags: [...DO_FLAG_NAMES],
448
+ run: (args, io) => browserDo(args, io, doDeps),
449
+ },
327
450
  bench: {
328
451
  summary: "check how each browser engine loads reference test pages and your URLs (asks first)",
329
452
  synopsis: "[--engine <name>]... [--url <url>]... [--only-urls] [--yes] [--json]",
@@ -332,7 +455,7 @@ export function browserCommand(deps = defaultDeps) {
332
455
  run: withModule("bench"),
333
456
  },
334
457
  };
335
- return group("browser", "developer tool: compare browser engines (needs turno-browser)", subs, {
458
+ const command = group("browser", "developer tool: compare browser engines (needs turno-browser)", subs, {
336
459
  footer: FOOTER,
337
460
  examples: [
338
461
  "turno browser identities",
@@ -341,16 +464,34 @@ export function browserCommand(deps = defaultDeps) {
341
464
  "turno browser set school --health-url https://mail.example.com/ --health-text Inbox",
342
465
  "turno browser set school --tabs-max 5 --tabs-popups keep --settle 250ms",
343
466
  "turno browser set school --block-trackers true --cache --json",
467
+ "turno browser set school --humanize light",
468
+ "turno browser set school --sharing tabs",
344
469
  "turno browser login school --url https://example.com",
345
470
  "turno browser doctor --fix",
346
471
  "turno browser reputation school --json",
347
472
  "turno browser vault add school mail --url https://mail.example.com --username alice",
473
+ "turno browser record school --flows --traces",
474
+ "turno browser flows school",
475
+ "turno browser replay school submit-timesheet --param password=keychain:school-password",
476
+ "turno browser traces school --open",
477
+ "turno browser set school --live true",
478
+ "turno browser live school",
479
+ "turno browser pause school",
480
+ "turno browser resume school",
348
481
  "turno browser export school --out school.session --expires 2d",
349
482
  "turno browser import school.session --as school-laptop",
350
483
  "turno browser remove school --dry-run",
351
484
  "turno browser bench --only-urls --url https://example.com --yes",
485
+ "turno browser do school open https://example.com",
486
+ "turno browser do school snapshot",
487
+ "turno browser do school click e12",
488
+ "turno browser do school end",
352
489
  ],
353
490
  });
491
+ return {
492
+ ...command,
493
+ run: (args, io) => (shortDo(args, subs) ? browserDo(args, io, doDeps) : command.run(args, io)),
494
+ };
354
495
  }
355
496
  export const command = browserCommand();
356
497
  //# sourceMappingURL=browser.js.map
@@ -243,7 +243,9 @@ export const command = group("identity", "who acts on outside services: service
243
243
  "turno identity set browser:school --tabs-max 5 --tabs-park 10m --background-throttling true",
244
244
  "turno identity set browser:school --block-trackers true --block-types image,font --cache-max-size 200MB",
245
245
  "turno identity set browser:school --settle 500ms --dry-run --json",
246
+ "turno identity set browser:school --humanize adaptive",
246
247
  "turno identity set browser:school --no-block --no-cache",
248
+ "turno identity set browser:school --sharing tabs",
247
249
  "turno identity prefer ~/code/acme linear=linear:work",
248
250
  "turno identity remove linear:work --dry-run",
249
251
  "turno identity log --verify",
@@ -70,14 +70,14 @@ export function callArguments(json, pairs) {
70
70
  return out;
71
71
  }
72
72
  /** The profile a session in `cwd` would use: --profile, else the folder's Claude Code profile, else the hub's. */
73
- function callerProfile(given, env, cwd) {
73
+ export function callerProfile(given, env, cwd) {
74
74
  if (given)
75
75
  return given;
76
76
  const config = loadConfig(env);
77
77
  return resolveProfile(cwd, config, env).chosen || config.system || "default";
78
78
  }
79
79
  /** One line from an SDK transport error: the gateway's `{ "error": ... }` text when it sent one. */
80
- function gatewayMessage(err) {
80
+ export function gatewayMessage(err) {
81
81
  const e = err;
82
82
  const message = e?.message ?? String(err);
83
83
  const status = typeof e?.code === "number" && e.code >= 400 && e.code < 600 ? e.code : undefined;
@@ -44,6 +44,19 @@ const ENVIRONMENT = [
44
44
  ["TURNO_NO_UPDATE_NOTIFIER", "1: same as TURNO_NO_UPDATE_CHECK (the name gh uses)"],
45
45
  ["TURNO_REGISTRY", "npm registry for update checks (default: npm_config_registry, else registry.npmjs.org)"],
46
46
  ["TURNO_BROWSER_IDLE", "turno-browser closes Chrome after this long without a tool call (default: 15m)"],
47
+ ["TURNO_LIGHTPANDA_PATH", "the Lightpanda binary turno-browser's read mode runs (default: lightpanda on PATH)"],
48
+ [
49
+ "TURNO_BROWSER_SESSION",
50
+ "the session name of turno browser do (same as --session; default: default), to keep several apart",
51
+ ],
52
+ [
53
+ "TURNO_CAMOUFOX_PATH",
54
+ "the Camoufox executable turno-browser's camoufox engine runs (default: the newest in Camoufox's cache)",
55
+ ],
56
+ [
57
+ "TURNO_PLAYWRIGHT_CORE",
58
+ "the playwright-core folder the camoufox engine runs on (default: the one next to turno-browser)",
59
+ ],
47
60
  ],
48
61
  },
49
62
  {
@@ -97,7 +97,7 @@ async function portChecks(env) {
97
97
  return out;
98
98
  }
99
99
  const ours = await answersAsMcpd(port, token);
100
- const owner = await portOwner(port, { env });
100
+ const owner = await portOwner(port, { env, ...(ours?.pid !== undefined ? { pid: ours.pid } : {}) });
101
101
  const uid = process.getuid?.();
102
102
  if (ours) {
103
103
  if (owner?.uid !== undefined && uid !== undefined && owner.uid !== uid) {
@@ -6,6 +6,7 @@ import { promisify } from "node:util";
6
6
  import { effectiveLaunch, variantKey } from "../core/manifest.js";
7
7
  import { fingerprint } from "./cache.js";
8
8
  import { ErrorCode, rpcError } from "./jsonrpc.js";
9
+ import { SESSION_CAPABILITY, SESSION_ENDED, sessionIdOf } from "./middleware.js";
9
10
  import { LoginRequiredError } from "./oauth.js";
10
11
  import { effectiveIdle } from "./pressure.js";
11
12
  import { Upstream } from "./upstream.js";
@@ -97,6 +98,13 @@ export function descriptionFingerprint(server, variant) {
97
98
  b: server.builtin ?? null,
98
99
  });
99
100
  }
101
+ /** A server that declared `SESSION_CAPABILITY` hears that a session it served ended. */
102
+ function tellSessionEnded(inst, session) {
103
+ const experimental = inst.upstream.init?.capabilities.experimental;
104
+ if (typeof experimental !== "object" || experimental === null || !(SESSION_CAPABILITY in experimental))
105
+ return;
106
+ inst.upstream.notify(SESSION_ENDED, { session });
107
+ }
100
108
  /**
101
109
  * Fingerprint of the whole definition (launch, scope, cwd, exclusive, idle, lease, timeouts),
102
110
  * except who gets it and which tools they see: tool filters apply per request, so a
@@ -157,11 +165,13 @@ export class InstanceManager {
157
165
  /** A client session ended: cancel its calls, drop it from every instance and release its leases. */
158
166
  detach(client) {
159
167
  this.clients.delete(client);
168
+ const session = sessionIdOf(client);
160
169
  for (const inst of this.instances.values()) {
161
170
  const cancelled = inst.upstream.forgetClient(client);
162
171
  if (cancelled)
163
172
  this.opts.log?.(`cancelled ${cancelled} call(s) of a closed session on ${inst.upstream.label}`);
164
- inst.clients.delete(client);
173
+ if (inst.clients.delete(client) && session)
174
+ tellSessionEnded(inst, session);
165
175
  for (const [uri, subs] of inst.subscriptions) {
166
176
  if (subs.delete(client) && subs.size === 0) {
167
177
  inst.subscriptions.delete(uri);
@@ -23,6 +23,19 @@ import { ErrorCode, rpcError } from "./jsonrpc.js";
23
23
  * import, erased at build): if the two ever differ, the typecheck fails.
24
24
  */
25
25
  export const SESSION_META = "io.turno/session";
26
+ /**
27
+ * A server that declares this experimental capability in `initialize` hears, with
28
+ * `SESSION_ENDED`, when a client session that made a call to it ends (`InstanceManager.detach`).
29
+ * turno-browser uses it to free that session's tabs at once (`"sharing": "tabs"`).
30
+ */
31
+ export const SESSION_CAPABILITY = "io.turno/sessions";
32
+ export const SESSION_ENDED = "notifications/io.turno/session_ended";
33
+ /** The session id of each client handle, made on its first call. */
34
+ const sessionIds = new WeakMap();
35
+ /** The id the `session` stage gave this client, or undefined when it made no call. */
36
+ export function sessionIdOf(client) {
37
+ return sessionIds.get(client);
38
+ }
26
39
  const BUILT_IN = ["filter", "calllog", "session"];
27
40
  const STAGE_NAME = /^[a-z][a-z0-9-]*$/;
28
41
  /** A profile's tool filter for a client's server, or undefined when it filters nothing. */
@@ -84,14 +97,13 @@ function callLogStage(sink) {
84
97
  * against mcpd. A value the client sent under the same key is replaced.
85
98
  */
86
99
  function sessionStage() {
87
- const ids = new WeakMap();
88
100
  return {
89
101
  name: "session",
90
102
  run(call, next) {
91
- let id = ids.get(call.client);
103
+ let id = sessionIds.get(call.client);
92
104
  if (!id) {
93
105
  id = randomUUID();
94
- ids.set(call.client, id);
106
+ sessionIds.set(call.client, id);
95
107
  }
96
108
  const meta = typeof call.params._meta === "object" && call.params._meta !== null
97
109
  ? call.params._meta
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { readFileSync, readdirSync, readlinkSync } from "node:fs";
3
+ import { connect } from "node:net";
3
4
  import { join } from "node:path";
4
5
  import { promisify } from "node:util";
5
6
  const run = promisify(execFile);
@@ -104,7 +105,39 @@ export async function peerPid(remotePort, self = process.pid, opts = {}) {
104
105
  }
105
106
  return lsofPeer(remotePort, self, opts.env ?? process.env);
106
107
  }
107
- /** Which process listens on 127.0.0.1:`port`, as far as this user can tell. Undefined when unknown or free. */
108
+ /** Whether something accepts TCP connections on 127.0.0.1:`port`, the address mcpd binds. */
109
+ function listensOn(port, timeoutMs = 1000) {
110
+ return new Promise((resolve) => {
111
+ const socket = connect({ host: "127.0.0.1", port });
112
+ const done = (yes) => {
113
+ socket.destroy();
114
+ resolve(yes);
115
+ };
116
+ socket.setTimeout(timeoutMs, () => done(true)); // accepted the SYN but slow to finish: busy
117
+ socket.once("connect", () => done(true));
118
+ socket.once("error", () => done(false));
119
+ });
120
+ }
121
+ function parseLsof(stdout) {
122
+ const owner = {};
123
+ for (const line of stdout.split("\n")) {
124
+ if (line.startsWith("p") && owner.pid === undefined)
125
+ owner.pid = Number(line.slice(1));
126
+ else if (line.startsWith("c") && owner.command === undefined)
127
+ owner.command = line.slice(1);
128
+ else if (line.startsWith("u") && owner.uid === undefined)
129
+ owner.uid = Number(line.slice(1));
130
+ }
131
+ return owner.pid !== undefined ? owner : undefined;
132
+ }
133
+ /**
134
+ * Which process listens on 127.0.0.1:`port`, as far as this user can tell. Undefined when the
135
+ * port is free; an empty object when something listens but the system cannot say what.
136
+ *
137
+ * On macOS lsof scans every process and can take many seconds on a busy machine, so a free port
138
+ * is told by a refused connection without lsof, and `opts.pid` (a process expected to hold the
139
+ * port) is checked alone first.
140
+ */
108
141
  export async function portOwner(port, opts = {}) {
109
142
  const platform = opts.platform ?? process.platform;
110
143
  if (platform === "linux") {
@@ -123,25 +156,26 @@ export async function portOwner(port, opts = {}) {
123
156
  return { uid: row.uid, ...(pid ? { pid } : {}), ...(command ? { command } : {}) };
124
157
  }
125
158
  }
126
- try {
127
- const { stdout } = await run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], {
128
- timeout: 3000,
129
- env: opts.env ?? process.env,
130
- });
131
- const owner = {};
132
- for (const line of stdout.split("\n")) {
133
- if (line.startsWith("p") && owner.pid === undefined)
134
- owner.pid = Number(line.slice(1));
135
- else if (line.startsWith("c") && owner.command === undefined)
136
- owner.command = line.slice(1);
137
- else if (line.startsWith("u") && owner.uid === undefined)
138
- owner.uid = Number(line.slice(1));
139
- }
140
- return owner.pid !== undefined ? owner : undefined;
141
- }
142
- catch {
159
+ if (!(await listensOn(port)))
143
160
  return undefined;
161
+ const lsof = async (args) => {
162
+ try {
163
+ const { stdout } = await run("lsof", ["-nP", ...args, `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], {
164
+ timeout: 3000,
165
+ env: opts.env ?? process.env,
166
+ });
167
+ return parseLsof(stdout);
168
+ }
169
+ catch {
170
+ return undefined; // lsof exits 1 when it finds nothing; also missing or too slow
171
+ }
172
+ };
173
+ if (opts.pid !== undefined) {
174
+ const own = await lsof(["-a", "-p", String(opts.pid)]);
175
+ if (own)
176
+ return own;
144
177
  }
178
+ return (await lsof([])) ?? {};
145
179
  }
146
180
  /** "node (pid 123, uid 501)" for messages. */
147
181
  export function describeOwner(o) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "turno-cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "turno-cli",
9
- "version": "0.3.0",
9
+ "version": "0.4.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "1.32.2",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "turno-cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Switch accounts in your coding agents and keep the conversation, the MCP sign-ins and the browser session.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^26.6.6",
54
- "turno-browser": "0.3.0",
54
+ "turno-browser": "0.4.0",
55
55
  "turno-fonts": "0.1.2",
56
56
  "typescript": "^7.0.2",
57
57
  "vitest": "^5.1.0"