turno-cli 0.2.0 → 0.3.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 (112) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.md +127 -39
  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-identity.js +514 -0
  19. package/dist/cli/commands/browser-session.js +102 -0
  20. package/dist/cli/commands/browser-vault.js +193 -0
  21. package/dist/cli/commands/browser.js +159 -59
  22. package/dist/cli/commands/complete.js +13 -3
  23. package/dist/cli/commands/completion.js +4 -0
  24. package/dist/cli/commands/config.js +90 -13
  25. package/dist/cli/commands/demo.js +36 -7
  26. package/dist/cli/commands/doctor.js +170 -36
  27. package/dist/cli/commands/identity.js +99 -12
  28. package/dist/cli/commands/init.js +42 -10
  29. package/dist/cli/commands/limit.js +65 -9
  30. package/dist/cli/commands/mcp-call.js +240 -0
  31. package/dist/cli/commands/mcp-oauth.js +33 -6
  32. package/dist/cli/commands/mcp-observe.js +128 -23
  33. package/dist/cli/commands/mcp-share.js +201 -0
  34. package/dist/cli/commands/mcp.js +203 -42
  35. package/dist/cli/commands/mcpd.js +76 -12
  36. package/dist/cli/commands/open.js +26 -3
  37. package/dist/cli/commands/profile.js +212 -30
  38. package/dist/cli/commands/resolve.js +8 -1
  39. package/dist/cli/commands/run.js +24 -4
  40. package/dist/cli/commands/secret.js +23 -38
  41. package/dist/cli/commands/session.js +16 -5
  42. package/dist/cli/commands/sessions.js +7 -1
  43. package/dist/cli/commands/setup.js +83 -11
  44. package/dist/cli/commands/status.js +67 -15
  45. package/dist/cli/commands/statusline.js +7 -2
  46. package/dist/cli/commands/ui.js +17 -5
  47. package/dist/cli/commands/undo.js +39 -7
  48. package/dist/cli/commands/uninstall.js +24 -5
  49. package/dist/cli/commands/upgrade.js +113 -76
  50. package/dist/cli/commands/usage.js +11 -10
  51. package/dist/cli/commands/version.js +20 -8
  52. package/dist/cli/commands/which.js +5 -3
  53. package/dist/cli/diagnostics.js +184 -0
  54. package/dist/cli/exit.js +65 -0
  55. package/dist/cli/group.js +20 -8
  56. package/dist/cli/help.js +6 -1
  57. package/dist/cli/hints.js +30 -0
  58. package/dist/cli/io.js +24 -8
  59. package/dist/cli/launch.js +31 -2
  60. package/dist/cli/launchers.js +25 -10
  61. package/dist/cli/main.js +52 -18
  62. package/dist/cli/optional.js +144 -0
  63. package/dist/cli/output.js +123 -0
  64. package/dist/cli/picker.js +17 -5
  65. package/dist/cli/registry.js +20 -2
  66. package/dist/cli/safe.js +87 -0
  67. package/dist/cli/secret-input.js +63 -0
  68. package/dist/cli/security.js +31 -9
  69. package/dist/cli/style.js +35 -5
  70. package/dist/cli/topics.js +142 -0
  71. package/dist/core/config.js +39 -3
  72. package/dist/core/fsutil.js +2 -10
  73. package/dist/core/journal.js +19 -11
  74. package/dist/core/manifest.js +28 -1
  75. package/dist/core/paths.js +6 -112
  76. package/dist/core/profiles.js +28 -8
  77. package/dist/core/resolve.js +13 -3
  78. package/dist/core/secrets.js +4 -154
  79. package/dist/core/state-file.js +107 -0
  80. package/dist/core/update.js +14 -11
  81. package/dist/core/version.js +57 -10
  82. package/dist/demo/server.js +10 -2
  83. package/dist/mcpd/cache.js +6 -7
  84. package/dist/mcpd/calllog.js +10 -9
  85. package/dist/mcpd/client-names.js +8 -13
  86. package/dist/mcpd/connectors.js +42 -3
  87. package/dist/mcpd/daemon.js +29 -8
  88. package/dist/mcpd/folder-sets.js +5 -2
  89. package/dist/mcpd/gateway.js +57 -29
  90. package/dist/mcpd/health.js +69 -25
  91. package/dist/mcpd/importer.js +106 -9
  92. package/dist/mcpd/instances.js +59 -31
  93. package/dist/mcpd/jsonrpc.js +3 -1
  94. package/dist/mcpd/middleware.js +144 -0
  95. package/dist/mcpd/modern.js +57 -19
  96. package/dist/mcpd/oauth.js +71 -17
  97. package/dist/mcpd/peerpid.js +15 -3
  98. package/dist/mcpd/pressure.js +4 -1
  99. package/dist/mcpd/rss.js +34 -19
  100. package/dist/mcpd/service.js +28 -4
  101. package/dist/mcpd/share.js +217 -0
  102. package/dist/mcpd/state.js +16 -16
  103. package/dist/mcpd/sync.js +22 -12
  104. package/dist/mcpd/systemd.js +4 -1
  105. package/dist/mcpd/tokens.js +4 -8
  106. package/dist/mcpd/upstream.js +12 -5
  107. package/dist/statusline/cost.js +17 -4
  108. package/dist/statusline/input.js +15 -3
  109. package/dist/ui/fonts.js +1 -1
  110. package/dist/ui/settings.js +6 -1
  111. package/npm-shrinkwrap.json +12 -3
  112. package/package.json +7 -6
@@ -13,6 +13,10 @@ const USAGE = [
13
13
  "always open in the default browser. Only http(s) and mailto links are accepted.",
14
14
  "Claude Code calls this through $BROWSER. Typed in a terminal outside a profile's session,",
15
15
  "a claude.ai link without a profile shows the profiles to choose from.",
16
+ "",
17
+ "Examples:",
18
+ " $ turno open https://claude.ai/new",
19
+ " $ turno open work https://claude.ai/new",
16
20
  ].join("\n");
17
21
  /** claude.ai and claude.com links (and their subdomains) open with the profile's account. */
18
22
  export function isClaudeUrl(url) {
@@ -58,12 +62,26 @@ export function openInvocation(profile, url, env = process.env, platform = proce
58
62
  if (!chrome || !existsSync(chromeApp(env)))
59
63
  return { command: "open", args: [url] };
60
64
  ensurePrivateDir(chrome.dir, env);
61
- return { command: "open", args: ["-na", "Google Chrome", "--args", `--user-data-dir=${chrome.dir}`, `--profile-directory=${chrome.name}`, url] };
65
+ return {
66
+ command: "open",
67
+ args: [
68
+ "-na",
69
+ "Google Chrome",
70
+ "--args",
71
+ `--user-data-dir=${chrome.dir}`,
72
+ `--profile-directory=${chrome.name}`,
73
+ url,
74
+ ],
75
+ };
62
76
  }
63
77
  const bin = chrome && (env.TURNO_CHROME_BIN || LINUX_CHROMES.map((c) => findOnPath(c, env)).find(Boolean));
64
78
  if (chrome && bin) {
65
79
  ensurePrivateDir(chrome.dir, env);
66
- return { command: bin, args: [`--user-data-dir=${chrome.dir}`, `--profile-directory=${chrome.name}`, url], detach: true };
80
+ return {
81
+ command: bin,
82
+ args: [`--user-data-dir=${chrome.dir}`, `--profile-directory=${chrome.name}`, url],
83
+ detach: true,
84
+ };
67
85
  }
68
86
  if (!findOnPath("xdg-open", env))
69
87
  fail("cannot open links: xdg-open is not installed (package xdg-utils)");
@@ -86,7 +104,12 @@ async function chooseProfile(url, io) {
86
104
  if (io.env.CLAUDE_CONFIG_DIR && profileFromConfigDir(io.env.CLAUDE_CONFIG_DIR, config, io.env))
87
105
  return undefined;
88
106
  const { pickProfile } = await import("../picker.js");
89
- return pickProfile(io, { command: "open", title: "Open the link with", agent: "claude", ...(config.system ? { initial: config.system } : {}) });
107
+ return pickProfile(io, {
108
+ command: "open",
109
+ title: "Open the link with",
110
+ agent: "claude",
111
+ ...(config.system ? { initial: config.system } : {}),
112
+ });
90
113
  }
91
114
  export const command = {
92
115
  summary: "open a claude.ai link with an account (default: the session's)",
@@ -1,7 +1,7 @@
1
1
  import { existsSync, statSync } from "node:fs";
2
2
  import { resolve as resolvePath } from "node:path";
3
3
  import { delimiter } from "node:path";
4
- import { DEFAULT_AGENT, adapter, agentHub, agentProfileDir, isAgentId, AGENT_IDS } from "../../agents/index.js";
4
+ import { DEFAULT_AGENT, adapter, agentHub, agentProfileDir, isAgentId, AGENT_IDS, } from "../../agents/index.js";
5
5
  import { editConfig } from "../../core/config-edit.js";
6
6
  import { loadConfig } from "../../core/config.js";
7
7
  import { exhaustedUntil } from "../../core/exhausted.js";
@@ -9,11 +9,14 @@ import { Journal } from "../../core/journal.js";
9
9
  import { expandHome, paths, tildify } from "../../core/paths.js";
10
10
  import { agentOf, listProfiles } from "../../core/profiles.js";
11
11
  import { candidateRoots, folderMcpSet, resolveProfile } from "../../core/resolve.js";
12
- import { addArrayTable, ensureTable, removeArrayTables, removeTable, setValue } from "../../core/toml-edit.js";
12
+ import { addArrayTable, ensureTable, removeArrayTables, removeTable, setValue, } from "../../core/toml-edit.js";
13
13
  import { NAMED_COLORS } from "../../statusline/render.js";
14
- import { DRY_RUN, JSON_FLAG, bool, flagsOf, parseFlags, printJson, str } from "../args.js";
14
+ import { DRY_RUN, JSON_FLAG, bool, flagsOf, parseFlags, str } from "../args.js";
15
+ import { Exit, exitName } from "../exit.js";
15
16
  import { group } from "../group.js";
17
+ import { nextStep } from "../hints.js";
16
18
  import { confirm, fail, needsAnswer, plural } from "../io.js";
19
+ import { emit, jsonOutput } from "../output.js";
17
20
  import { profileColor, style } from "../style.js";
18
21
  import { findOnPath, launcherPath } from "../launch.js";
19
22
  import { isGenerated, launcherName, refuseNpx } from "../launchers.js";
@@ -34,7 +37,9 @@ export function parseColor(v, label = "--color") {
34
37
  export async function profilesData(env, config, withAccounts = true) {
35
38
  const names = listProfiles(config, env);
36
39
  // Account details come from `claude auth status`; other agents show whether they are set up.
37
- const auth = withAccounts ? await Promise.all(names.map((n) => (adapter(agentOf(n, config)).accountDetails ? authStatus(n, env) : undefined))) : [];
40
+ const auth = withAccounts
41
+ ? await Promise.all(names.map((n) => (adapter(agentOf(n, config)).accountDetails ? authStatus(n, env) : undefined)))
42
+ : [];
38
43
  return names.map((name, i) => {
39
44
  const s = auth[i];
40
45
  const agent = agentOf(name, config);
@@ -44,21 +49,41 @@ export async function profilesData(env, config, withAccounts = true) {
44
49
  agent,
45
50
  dir: tildify(dir, env),
46
51
  setUp: existsSync(dir) && Boolean(launcherPath(name, env, agent)),
47
- ...(withAccounts ? { email: s?.loggedIn ? (s.email ?? null) : null, plan: s?.loggedIn ? (s.subscriptionType ?? null) : null } : {}),
52
+ ...(withAccounts
53
+ ? { email: s?.loggedIn ? (s.email ?? null) : null, plan: s?.loggedIn ? (s.subscriptionType ?? null) : null }
54
+ : {}),
48
55
  color: config.profiles[name]?.color ?? null,
49
56
  browser: config.profiles[name]?.browser ?? "chrome",
50
- roles: [config.system === name && "system", config.default === name && "default", config.fallback === name && "fallback"].filter(Boolean),
57
+ roles: [
58
+ config.system === name && "system",
59
+ config.default === name && "default",
60
+ config.fallback === name && "fallback",
61
+ ].filter(Boolean),
51
62
  projects: config.projects.filter((r) => r.profile === name).length,
52
63
  exhaustedUntil: exhaustedUntil(name, env) ?? null,
53
64
  };
54
65
  });
55
66
  }
67
+ /** `turno profile list --json`: one element per profile. */
68
+ const LIST_JSON = jsonOutput([
69
+ "name",
70
+ "agent",
71
+ "dir",
72
+ "setUp",
73
+ "email",
74
+ "plan",
75
+ "color",
76
+ "browser",
77
+ "roles",
78
+ "projects",
79
+ "exhaustedUntil",
80
+ ]);
56
81
  async function list(args, io) {
57
82
  const p = parseFlags(args, JSON_FLAG, 0);
58
83
  const config = loadConfig(io.env);
59
84
  const rows = await profilesData(io.env, config);
60
85
  if (bool(p, "json")) {
61
- printJson(io, rows);
86
+ emit(io, p, LIST_JSON, rows);
62
87
  return 0;
63
88
  }
64
89
  if (!rows.length) {
@@ -87,13 +112,24 @@ export function renderProfiles(rows, config, io, now = Date.now() / 1000) {
87
112
  : s.warn("not logged in");
88
113
  const exhausted = r.exhaustedUntil && r.exhaustedUntil > now ? s.warn(`exhausted until ${shortTime(r.exhaustedUntil)}`) : "";
89
114
  const flags = [r.roles.join(", "), exhausted].filter(Boolean).join(s.muted(" · "));
90
- return [s.profile(r.name, profileColor(config.profiles, r.name)), s.muted(a.label), who, s.muted(r.projects ? plural(r.projects, "folder") : "no folders"), flags];
115
+ return [
116
+ s.profile(r.name, profileColor(config.profiles, r.name)),
117
+ s.muted(a.label),
118
+ who,
119
+ s.muted(r.projects ? plural(r.projects, "folder") : "no folders"),
120
+ flags,
121
+ ];
91
122
  });
92
123
  if (!s.color)
93
124
  return s.table(table, { indent: 0 });
94
125
  // turno reads no account for agents without account details: a "-" there, not the launcher.
95
126
  const head = ["", "agent", "account", "folders", "role"].map((h) => s.muted(h));
96
- return [s.header("Profiles"), ...s.table([head, ...table], { columns: [{}, { drop: 2 }, {}, { drop: 1 }, {}] }), "", s.muted("turno <name> opens one; turno profile assign <dir> gives a folder its profile.")];
127
+ return [
128
+ s.header("Profiles"),
129
+ ...s.table([head, ...table], { columns: [{}, { drop: 2 }, {}, { drop: 1 }, {}] }),
130
+ "",
131
+ s.muted("turno <name> opens one; turno profile assign <dir> gives a folder its profile."),
132
+ ];
97
133
  }
98
134
  /** The PATH line for a shell, or undefined when `dir` is on PATH. */
99
135
  export function pathAdvice(env, dir = paths(env).bin) {
@@ -187,7 +223,7 @@ async function add(args, io) {
187
223
  // `turno <name>` works without ~/.local/bin on PATH.
188
224
  const run = offPath ? `turno ${name}` : launcher;
189
225
  const sub = adapter(agent).loginSubcommand;
190
- io.out(`Next: ${sub ? `run ${run} ${sub}` : `run ${run} and sign in with /login`}. turno profile list shows the profile.`);
226
+ nextStep(io, `${sub ? `run ${run} ${sub}` : `run ${run} and sign in with /login`}. turno profile list shows the profile.`);
191
227
  const hint = journal.hint();
192
228
  if (hint)
193
229
  io.out(hint);
@@ -211,7 +247,8 @@ async function remove(args, io) {
211
247
  const p = parseFlags(args, DRY_RUN, 1);
212
248
  const dry = bool(p, "dry-run");
213
249
  const picked = !p.positionals[0];
214
- const name = p.positionals[0] ?? (await (await import("../picker.js")).pickProfile(io, { command: "profile remove", title: "Profile to remove" }));
250
+ const name = p.positionals[0] ??
251
+ (await (await import("../picker.js")).pickProfile(io, { command: "profile remove", title: "Profile to remove" }));
215
252
  const config = loadConfig(io.env);
216
253
  if (!listProfiles(config, io.env).includes(name))
217
254
  fail(`no profile '${name}'`);
@@ -245,7 +282,7 @@ async function remove(args, io) {
245
282
  io.out(hint);
246
283
  return 0;
247
284
  }
248
- /** The server set keys of a rule (ADR 0031), to write back when its profile part goes. */
285
+ /** The server set keys of a rule, to write back when its profile part goes. */
249
286
  function setKeys(rule) {
250
287
  return { ...(rule?.mcp ? { mcp: rule.mcp } : {}), ...(rule?.mcpDeny ? { mcp_deny: rule.mcpDeny } : {}) };
251
288
  }
@@ -259,7 +296,10 @@ function keepSets(text, removed, env) {
259
296
  }
260
297
  /** "only docs, not mail": what a folder's server set lets sessions see. */
261
298
  function setText(set) {
262
- const parts = [set.mcp ? `only ${set.mcp.join(", ") || "none"}` : "", set.mcpDeny ? `${set.mcp ? "not" : "all but"} ${set.mcpDeny.join(", ")}` : ""];
299
+ const parts = [
300
+ set.mcp ? `only ${set.mcp.join(", ") || "none"}` : "",
301
+ set.mcpDeny ? `${set.mcp ? "not" : "all but"} ${set.mcpDeny.join(", ")}` : "",
302
+ ];
263
303
  return parts.filter(Boolean).join(", ");
264
304
  }
265
305
  function folder(arg, io) {
@@ -282,28 +322,116 @@ export function resolveAll(dir, config, env, roots = candidateRoots(dir)) {
282
322
  return agents.map((agent) => ({ agent, r: resolveProfile(dir, config, env, roots, agent) }));
283
323
  }
284
324
  /** "work (project ~/code)", or the plain agent and its home. */
285
- export function usingText(agent, r, env) {
325
+ export function usingText(agent, r, env, config) {
286
326
  if (r.note)
287
327
  return `${r.chosen} (${r.assigned} ${r.note})`;
288
- return r.chosen ? `${r.chosen} (${r.reason})` : `plain ${adapter(agent).command} with ${tildify(agentHub(agent, env), env)} (${r.reason})`;
328
+ if (r.chosen)
329
+ return `${r.chosen} (${r.reason})`;
330
+ if (agent === DEFAULT_AGENT && config?.system === "")
331
+ return `${NO_DEFAULT_ACCOUNT} (${r.reason})`;
332
+ return `plain ${adapter(agent).command} with ${tildify(agentHub(agent, env), env)} (${r.reason})`;
333
+ }
334
+ /** What a folder without a Claude Code profile uses when `system = ""`: nothing, turno auto exits 3. */
335
+ export const NO_DEFAULT_ACCOUNT = 'no profile: system = "" (turno auto exits 3)';
336
+ export const WHICH_SPEC = { ...JSON_FLAG, check: { type: "boolean" }, agent: { type: "string" } };
337
+ /** `turno profile which --json`; `check` only with --check. */
338
+ export const WHICH_JSON = jsonOutput(["dir", "assigned", "chosen", "reason", "note", "agents", "mcp", "check"]);
339
+ /**
340
+ * Whether the folder has a profile ready to open: 0 yes; 3 no rule and no default,
341
+ * or a rule naming a missing profile; 4 the profile's account is not signed in (agents turno
342
+ * reads an account for: Claude Code); 1 its launcher is missing or the sign-in is unknown.
343
+ */
344
+ export async function checkFolder(where, agent, r, config, env) {
345
+ const a = adapter(agent);
346
+ const assign = `turno profile assign ${where} <profile>`;
347
+ if (!r.chosen)
348
+ return {
349
+ exitCode: Exit.noProfile,
350
+ message: `${where} has no ${a.label} profile (${r.reason}); give it one: ${assign}`,
351
+ };
352
+ if (!listProfiles(config, env, agent).includes(r.chosen)) {
353
+ return {
354
+ exitCode: Exit.noProfile,
355
+ message: `${where} uses the ${r.chosen} profile (${r.reason}), but there is no such profile: turno profile add ${r.chosen}${agent === DEFAULT_AGENT ? "" : ` --agent ${agent}`}, or ${assign}`,
356
+ };
357
+ }
358
+ if (!launcherPath(r.chosen, env, agent))
359
+ return {
360
+ exitCode: Exit.failure,
361
+ message: `${r.chosen} is not set up (its launcher is missing): turno profile repair ${r.chosen}`,
362
+ };
363
+ if (a.accountDetails) {
364
+ const s = await authStatus(r.chosen, env);
365
+ if (!s)
366
+ return {
367
+ exitCode: Exit.failure,
368
+ message: `could not tell whether ${r.chosen} is signed in (claude auth status gave no answer)`,
369
+ };
370
+ if (!s.loggedIn)
371
+ return {
372
+ exitCode: Exit.notSignedIn,
373
+ message: `${r.chosen} is not signed in: run ${launcherName(r.chosen, agent)}, then /login`,
374
+ };
375
+ }
376
+ return { exitCode: Exit.ok, message: `${where} uses ${r.chosen} (${r.reason})` };
289
377
  }
290
378
  export async function whichCommand(args, io) {
291
- const p = parseFlags(args, JSON_FLAG, 1);
379
+ const p = parseFlags(args, WHICH_SPEC, 1);
292
380
  const dir = folder(p.positionals[0], io);
293
381
  const config = loadConfig(io.env);
294
382
  const roots = candidateRoots(dir);
295
383
  const all = resolveAll(dir, config, io.env, roots);
296
384
  const r = all[0].r;
297
385
  const set = folderMcpSet(roots, config.projects, r.chosen || undefined);
386
+ const wanted = str(p, "agent");
387
+ if (wanted !== undefined && !bool(p, "check"))
388
+ fail("--agent goes with --check");
389
+ if (wanted !== undefined && !isAgentId(wanted))
390
+ fail(`--agent must be ${AGENT_IDS.slice(0, -1).join(", ")} or ${AGENT_IDS.at(-1)}`);
391
+ let check;
392
+ if (bool(p, "check")) {
393
+ const agent = (wanted ?? DEFAULT_AGENT);
394
+ const x = agent === DEFAULT_AGENT ? r : resolveProfile(dir, config, io.env, roots, agent);
395
+ check = await checkFolder(tildify(dir, io.env), agent, x, config, io.env);
396
+ }
298
397
  if (bool(p, "json")) {
299
- const one = (x) => ({ assigned: x.assigned || null, chosen: x.chosen || null, reason: x.reason, note: x.note || null });
398
+ const one = (x) => ({
399
+ assigned: x.assigned || null,
400
+ chosen: x.chosen || null,
401
+ reason: x.reason,
402
+ note: x.note || null,
403
+ });
300
404
  const mcp = set ? { rule: tildify(set.path, io.env), allow: set.mcp ?? null, deny: set.mcpDeny ?? null } : null;
301
- printJson(io, { dir: tildify(dir, io.env), ...one(r), agents: Object.fromEntries(all.map(({ agent, r: x }) => [agent, one(x)])), mcp });
302
- return 0;
405
+ const checked = check
406
+ ? {
407
+ check: {
408
+ ok: check.exitCode === Exit.ok,
409
+ code: exitName(check.exitCode),
410
+ exitCode: check.exitCode,
411
+ message: check.message,
412
+ },
413
+ }
414
+ : {};
415
+ emit(io, p, WHICH_JSON, {
416
+ dir: tildify(dir, io.env),
417
+ ...one(r),
418
+ agents: Object.fromEntries(all.map(({ agent, r: x }) => [agent, one(x)])),
419
+ mcp,
420
+ ...checked,
421
+ });
422
+ return check?.exitCode ?? 0;
423
+ }
424
+ if (check) {
425
+ // Quiet when ready, for hooks and scripts; one line on stderr when not.
426
+ if (check.exitCode !== Exit.ok)
427
+ io.err(`turno: ${check.message}`);
428
+ return check.exitCode;
303
429
  }
304
430
  io.out(tildify(dir, io.env));
305
431
  io.out(` assigned: ${r.assigned || "none"} (${r.reason})`);
306
- io.out(r.note ? ` using now: ${r.chosen} (${r.assigned} ${r.note})` : ` using now: ${r.chosen || "plain claude"}`);
432
+ io.out(r.note
433
+ ? ` using now: ${r.chosen} (${r.assigned} ${r.note})`
434
+ : ` using now: ${r.chosen || (config.system === "" ? NO_DEFAULT_ACCOUNT : "plain claude")}`);
307
435
  for (const { agent, r: x } of all.slice(1))
308
436
  io.out(` ${agent}: ${usingText(agent, x, io.env)}`);
309
437
  if (set)
@@ -313,7 +441,10 @@ export async function whichCommand(args, io) {
313
441
  async function assign(args, io) {
314
442
  const p = parseFlags(args, DRY_RUN, 2);
315
443
  const [dirArg, given] = p.positionals;
316
- if (dirArg && !given && !existsSync(expandHome(dirArg, io.env)) && listProfiles(loadConfig(io.env), io.env).includes(dirArg)) {
444
+ if (dirArg &&
445
+ !given &&
446
+ !existsSync(expandHome(dirArg, io.env)) &&
447
+ listProfiles(loadConfig(io.env), io.env).includes(dirArg)) {
317
448
  fail(`no such folder: ${dirArg} (to give this folder the profile ${dirArg}: turno profile assign . ${dirArg})`);
318
449
  }
319
450
  const dir = folder(dirArg, io);
@@ -326,16 +457,26 @@ async function assign(args, io) {
326
457
  const journal = new Journal(io.env, `profile assign ${tildify(dir, io.env)} ${name}`, dry);
327
458
  const shown = tildify(dir, io.env);
328
459
  // One rule per folder and agent: a Codex rule does not replace the folder's Claude Code rule.
329
- // A rule with only a server set (ADR 0031) is not a profile rule and stays; a replaced rule
460
+ // A rule with only a server set is not a profile rule and stays; a replaced rule
330
461
  // passes its set on to the new one.
331
462
  const agent = agentOf(name, config);
332
- const same = (e) => e.profile !== undefined && resolvePath(expandHome(e.path ?? "", io.env)) === dir && agentOf(e.profile, config) === agent;
463
+ const same = (e) => e.profile !== undefined &&
464
+ resolvePath(expandHome(e.path ?? "", io.env)) === dir &&
465
+ agentOf(e.profile, config) === agent;
333
466
  const carried = config.projects.find((r) => same(r) && (r.mcp || r.mcpDeny));
334
- editConfig(io.env, journal, (t) => addArrayTable(removeArrayTables(t, "projects", same).text, "projects", { path: shown, profile: name, ...setKeys(carried) }));
467
+ editConfig(io.env, journal, (t) => addArrayTable(removeArrayTables(t, "projects", same).text, "projects", {
468
+ path: shown,
469
+ profile: name,
470
+ ...setKeys(carried),
471
+ }));
335
472
  io.out(`${shown} -> ${name}${dry ? " (dry run)" : ""}`);
473
+ if (!dry && existsSync(agentProfileDir(name, agent, io.env)))
474
+ (await import("./setup.js")).applyRuleFolders(name, io, journal);
336
475
  const hint = journal.hint();
337
476
  if (hint)
338
477
  io.out(hint);
478
+ if (!dry)
479
+ nextStep(io, `${agent === DEFAULT_AGENT ? "turno auto" : `turno auto --agent ${agent}`} in ${shown} opens ${name} (turno profile which ${shown} says why)`);
339
480
  return 0;
340
481
  }
341
482
  async function unassign(args, io) {
@@ -344,7 +485,7 @@ async function unassign(args, io) {
344
485
  const dry = bool(p, "dry-run");
345
486
  const journal = new Journal(io.env, `profile unassign ${tildify(dir, io.env)}`, dry);
346
487
  const config = loadConfig(io.env);
347
- // Profile rules only: the folder keeps its server set (ADR 0031).
488
+ // Profile rules only: the folder keeps its server set.
348
489
  const own = (e) => e.profile !== undefined && resolvePath(expandHome(e.path ?? "", io.env)) === dir;
349
490
  let removed = 0;
350
491
  editConfig(io.env, journal, (t) => {
@@ -363,7 +504,13 @@ async function unassign(args, io) {
363
504
  return 0;
364
505
  }
365
506
  export const command = group("profile", "accounts (profiles) for each agent: list, add, repair, remove, and which folders use each", {
366
- list: { summary: "each profile, its account and roles", synopsis: "[--json]", flags: ["--json"], run: list },
507
+ list: {
508
+ summary: "each profile, its account and roles",
509
+ synopsis: "[--json]",
510
+ flags: ["--json"],
511
+ json: LIST_JSON,
512
+ run: list,
513
+ },
367
514
  add: {
368
515
  summary: "declare a profile in config.toml and set up its folder and launcher (claude-<name>, codex-<name>, ...); asks before moving your own files aside (--yes skips the question), -v lists every shared item; turno undo reverts all of it",
369
516
  synopsis: "<name> [--agent claude|codex|copilot|cursor] [--color <c>] [--browser chrome|default] [--dry-run] [--yes] [-v]",
@@ -385,11 +532,46 @@ export const command = group("profile", "accounts (profiles) for each agent: lis
385
532
  flags: ["--dry-run"],
386
533
  run: remove,
387
534
  },
388
- which: { summary: "which profile auto uses in a folder for each agent, and why", synopsis: "[dir] [--json]", args: ["dir"], flags: ["--json"], run: whichCommand },
535
+ which: {
536
+ summary: "which profile auto uses in a folder for each agent, and why; --check answers with the exit code instead",
537
+ synopsis: "[dir] [--json] [--check [--agent <agent>]]",
538
+ args: ["dir"],
539
+ flags: flagsOf(WHICH_SPEC),
540
+ details: [
541
+ "--check prints nothing and exits 0 when the folder has a profile that is set up",
542
+ "and signed in; 3 when it has no profile, 4 when the account is not signed in, 1",
543
+ "when the launcher is missing, with one line on stderr that says why (turno help",
544
+ "exit-codes). It checks the Claude Code profile, or the one of --agent.",
545
+ ].join("\n"),
546
+ json: WHICH_JSON,
547
+ run: whichCommand,
548
+ },
389
549
  assign: {
390
550
  summary: "make a folder (and everything under it) use a profile; without a profile, choose one from a list",
391
- synopsis: "[dir] [profile] [--dry-run]", args: ["dir", "profile"], flags: ["--dry-run"], run: assign
551
+ synopsis: "[dir] [profile] [--dry-run]",
552
+ args: ["dir", "profile"],
553
+ flags: ["--dry-run"],
554
+ run: assign,
555
+ },
556
+ unassign: {
557
+ summary: "remove a folder's own rule",
558
+ synopsis: "[dir] [--dry-run]",
559
+ args: ["dir"],
560
+ flags: ["--dry-run"],
561
+ run: unassign,
392
562
  },
393
- unassign: { summary: "remove a folder's own rule", synopsis: "[dir] [--dry-run]", args: ["dir"], flags: ["--dry-run"], run: unassign },
394
- }, { fallback: "list" });
563
+ }, {
564
+ fallback: "list",
565
+ examples: [
566
+ "turno profile list --json=name,email",
567
+ "turno profile add work",
568
+ "turno profile add school --agent codex --color green",
569
+ "turno profile repair",
570
+ "turno profile remove old --dry-run",
571
+ "turno profile which ~/code/acme",
572
+ "turno profile which --check || turno profile assign . work",
573
+ "turno profile assign ~/code/acme work",
574
+ "turno profile unassign ~/code/acme",
575
+ ],
576
+ });
395
577
  //# sourceMappingURL=profile.js.map
@@ -2,6 +2,9 @@ import { resolve as resolvePath } from "node:path";
2
2
  import { loadConfig } from "../../core/config.js";
3
3
  import { resolveProfile } from "../../core/resolve.js";
4
4
  import { JSON_FLAG, bool, flagsOf, parseFlags } from "../args.js";
5
+ import { emitLine, jsonOutput } from "../output.js";
6
+ /** `turno resolve --json`: one line, read by status lines. */
7
+ const RESOLVE_JSON = jsonOutput(["chosen", "assigned", "reason", "note", "exhaustedUntil"]);
5
8
  /** Field separator of the machine output read by status lines. */
6
9
  export const SEP = "\x1f";
7
10
  export const command = {
@@ -15,12 +18,16 @@ export const command = {
15
18
  hidden: true,
16
19
  args: ["dir"],
17
20
  flags: flagsOf(JSON_FLAG),
21
+ json: RESOLVE_JSON,
18
22
  async run(args, io) {
19
23
  const p = parseFlags(args, JSON_FLAG, 1);
20
24
  const json = bool(p, "json");
21
25
  const dir = p.positionals[0];
22
26
  const r = resolveProfile(resolvePath(dir ?? process.cwd()), loadConfig(io.env), io.env);
23
- io.out(json ? JSON.stringify(r) : [r.chosen, r.assigned, r.reason, r.note].join(SEP));
27
+ if (json)
28
+ emitLine(io, p, RESOLVE_JSON, r);
29
+ else
30
+ io.out([r.chosen, r.assigned, r.reason, r.note].join(SEP));
24
31
  return 0;
25
32
  },
26
33
  };
@@ -3,21 +3,41 @@ import { command as auto } from "./auto.js";
3
3
  export const command = {
4
4
  summary: "open a profile with its agent (turno <profile> is the short form), or auto",
5
5
  usage: [
6
- "Usage: turno run <profile|auto> [agent args]",
6
+ "Usage: turno run <profile|auto> [--no-gateway] [agent args]",
7
7
  "",
8
8
  "Everything after the profile goes to its agent, for example:",
9
9
  " turno run work --resume",
10
10
  "",
11
11
  "Without a profile, a terminal shows the profiles to choose from. When this",
12
12
  "folder resolves to a profile, auto comes first, named with it: auto (work).",
13
+ "",
14
+ "Safe mode: --no-gateway (or TURNO_SAFE=1) opens the profile with its account",
15
+ "but without turno's gateway: no mcpd entries, no gateway token, and for Claude",
16
+ "Code no status line (and no hooks). If a problem goes away in safe mode, it",
17
+ "comes from turno. Claude Code gets --strict-mcp-config with the profile's other",
18
+ "servers, Codex -c mcp_servers.<name>.enabled=false and Copilot",
19
+ "--disable-mcp-server for each gateway entry; Cursor has no switch for one run,",
20
+ "so its entries start without the token and mcpd refuses them.",
21
+ "",
22
+ "Examples:",
23
+ " $ turno run work",
24
+ " $ turno run work --resume # arguments go to the agent",
25
+ " $ turno run auto",
26
+ " $ turno run work --no-gateway # safe mode",
27
+ " $ TURNO_SAFE=1 turno work",
13
28
  ].join("\n"),
14
29
  args: ["profile-or-auto"],
15
- async run(args, io) {
16
- let [name, ...rest] = args;
30
+ flags: ["--no-gateway"],
31
+ async run(given, io) {
32
+ // `turno run --no-gateway work` as well as `turno run work --no-gateway`.
33
+ const lead = given[0] === "--no-gateway";
34
+ let [name, ...rest] = lead ? given.slice(1) : given;
35
+ if (lead)
36
+ rest = ["--no-gateway", ...rest];
17
37
  if (!name) {
18
38
  const { pickProfile } = await import("../picker.js");
19
39
  name = await pickProfile(io, { command: "run", title: "Profile to open", extra: ["auto"], auto: true });
20
- rest = [];
40
+ rest = lead ? ["--no-gateway"] : [];
21
41
  }
22
42
  return name === "auto" ? auto.run(rest, io) : launchProfile(name, rest, io);
23
43
  },
@@ -2,7 +2,10 @@ import { readFileSync } from "node:fs";
2
2
  import { paths, tildify } from "../../core/paths.js";
3
3
  import { SecretError, requireSecretStore } from "../../core/secrets.js";
4
4
  import { JSON_FLAG, bool, flagsOf, parseFlags } from "../args.js";
5
+ import { nextStep } from "../hints.js";
5
6
  import { fail, needsAnswer, noInputReason } from "../io.js";
7
+ import { answerFields, emit, jsonOutput } from "../output.js";
8
+ import { readHidden, readStdinText, stdinIsTty } from "../secret-input.js";
6
9
  const USAGE = `Usage:
7
10
  turno secret set <service> read a value from stdin and store it
8
11
  turno secret has <service> exit 0 when the item exists
@@ -12,41 +15,14 @@ const USAGE = `Usage:
12
15
  Reference it in mcp.toml as "keychain:<service>". Values are never printed and never passed
13
16
  as a command argument. The store is the login Keychain on macOS and the Secret Service
14
17
  (libsecret's secret-tool, attributes service=turno account=<service>) on Linux. Without
15
- either, use "env:NAME" references.`;
18
+ either, use "env:NAME" references.
19
+
20
+ Examples:
21
+ $ printf %s "$TOKEN" | turno secret set github-token
22
+ $ turno secret has github-token
23
+ $ turno secret list --json`;
16
24
  async function readStdin() {
17
- if (process.stdin.isTTY) {
18
- process.stderr.write("value (input hidden, end with Enter): ");
19
- return new Promise((resolve) => {
20
- const stdin = process.stdin;
21
- let value = "";
22
- stdin.setRawMode(true);
23
- stdin.resume();
24
- stdin.setEncoding("utf8");
25
- const onData = (ch) => {
26
- if (ch === "\r" || ch === "\n" || ch === "\u0004") {
27
- stdin.setRawMode(false);
28
- stdin.pause();
29
- stdin.off("data", onData);
30
- process.stderr.write("\n");
31
- resolve(value);
32
- }
33
- else if (ch === "\u0003") {
34
- process.exit(130);
35
- }
36
- else if (ch === "\u007f") {
37
- value = value.slice(0, -1);
38
- }
39
- else {
40
- value += ch;
41
- }
42
- };
43
- stdin.on("data", onData);
44
- });
45
- }
46
- const chunks = [];
47
- for await (const c of process.stdin)
48
- chunks.push(c);
49
- return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
25
+ return stdinIsTty() ? readHidden("value (input hidden, end with Enter): ") : readStdinText();
50
26
  }
51
27
  /** The store, with its SecretError turned into a one-line usage error. */
52
28
  function store(io) {
@@ -61,8 +37,11 @@ function store(io) {
61
37
  export function keychainRefs(text) {
62
38
  return [...new Set([...text.matchAll(/"keychain:([^"\\]+)"/g)].map((m) => m[1]))].sort();
63
39
  }
40
+ /** `turno secret list --json`: one element per keychain: reference in mcp.toml. */
41
+ const LIST_JSON = jsonOutput(["service", "stored"]);
64
42
  async function list(args, io) {
65
- const json = bool(parseFlags(args, JSON_FLAG, 0), "json");
43
+ const p = parseFlags(args, JSON_FLAG, 0);
44
+ const json = bool(p, "json");
66
45
  let text = "";
67
46
  try {
68
47
  text = readFileSync(paths(io.env).mcpFile, "utf8");
@@ -74,7 +53,7 @@ async function list(args, io) {
74
53
  const s = refs.length ? store(io) : undefined;
75
54
  const found = s ? await Promise.all(refs.map((r) => s.has(r))) : [];
76
55
  if (json) {
77
- io.out(JSON.stringify(refs.map((r, i) => ({ service: r, stored: found[i] })), null, 2));
56
+ emit(io, p, LIST_JSON, refs.map((r, i) => ({ service: r, stored: found[i] })));
78
57
  return 0;
79
58
  }
80
59
  if (!refs.length)
@@ -86,7 +65,12 @@ async function list(args, io) {
86
65
  export const command = {
87
66
  summary: "store MCP secrets in the Keychain (macOS) or the Secret Service (Linux)",
88
67
  usage: USAGE,
89
- subcommands: { set: { args: ["any"] }, has: { args: ["any"] }, rm: { args: ["any"] }, list: { flags: flagsOf(JSON_FLAG) } },
68
+ subcommands: {
69
+ set: { args: ["any"] },
70
+ has: { args: ["any"] },
71
+ rm: { args: ["any"] },
72
+ list: { flags: flagsOf(JSON_FLAG) },
73
+ },
90
74
  async run(args, io) {
91
75
  const [sub] = args;
92
76
  const rest = args.slice(1);
@@ -95,7 +79,7 @@ export const command = {
95
79
  return 0;
96
80
  }
97
81
  if (sub === "list" || sub === undefined)
98
- return list(rest, io);
82
+ return answerFields(rest, LIST_JSON, io) ? 0 : list(rest, io);
99
83
  // One service name and no flags: an unknown flag must not become a service name.
100
84
  const service = parseFlags(rest, {}, 1).positionals[0];
101
85
  if (!service)
@@ -112,6 +96,7 @@ export const command = {
112
96
  return fail("empty value");
113
97
  await s.set(service, value);
114
98
  io.out(`stored keychain:${service}`);
99
+ nextStep(io, `use it in mcp.toml as "keychain:${service}"; turno secret list shows which references are stored`);
115
100
  return 0;
116
101
  }
117
102
  case "has":