turno-cli 0.1.1 → 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 (121) hide show
  1. package/CHANGELOG.md +432 -0
  2. package/README.md +228 -73
  3. package/dist/accounts/audit.js +154 -12
  4. package/dist/accounts/builtin.js +100 -25
  5. package/dist/accounts/delegate.js +199 -35
  6. package/dist/accounts/policy.js +79 -0
  7. package/dist/accounts/registry.js +39 -21
  8. package/dist/agents/adapter.js +29 -0
  9. package/dist/agents/claude.js +246 -0
  10. package/dist/agents/codex.js +186 -0
  11. package/dist/agents/copilot.js +56 -0
  12. package/dist/agents/cursor.js +58 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +43 -13
  15. package/dist/cli/args.js +38 -6
  16. package/dist/cli/commands/accounts.js +119 -52
  17. package/dist/cli/commands/auto.js +121 -33
  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 +319 -138
  22. package/dist/cli/commands/complete.js +14 -3
  23. package/dist/cli/commands/completion.js +8 -2
  24. package/dist/cli/commands/config.js +186 -24
  25. package/dist/cli/commands/demo.js +321 -0
  26. package/dist/cli/commands/doctor.js +525 -123
  27. package/dist/cli/commands/handoff.js +33 -22
  28. package/dist/cli/commands/identity.js +192 -54
  29. package/dist/cli/commands/init.js +648 -0
  30. package/dist/cli/commands/limit.js +84 -16
  31. package/dist/cli/commands/mcp-call.js +240 -0
  32. package/dist/cli/commands/mcp-oauth.js +221 -0
  33. package/dist/cli/commands/mcp-observe.js +539 -0
  34. package/dist/cli/commands/mcp-share.js +201 -0
  35. package/dist/cli/commands/mcp.js +816 -187
  36. package/dist/cli/commands/mcpd.js +388 -76
  37. package/dist/cli/commands/migrate.js +6 -4
  38. package/dist/cli/commands/open.js +115 -27
  39. package/dist/cli/commands/profile.js +396 -78
  40. package/dist/cli/commands/resolve.js +14 -3
  41. package/dist/cli/commands/run.js +36 -6
  42. package/dist/cli/commands/secret.js +80 -76
  43. package/dist/cli/commands/session.js +17 -6
  44. package/dist/cli/commands/sessions.js +48 -12
  45. package/dist/cli/commands/setup.js +214 -164
  46. package/dist/cli/commands/status.js +227 -44
  47. package/dist/cli/commands/statusline.js +311 -114
  48. package/dist/cli/commands/ui.js +78 -68
  49. package/dist/cli/commands/undo.js +193 -18
  50. package/dist/cli/commands/uninstall.js +481 -0
  51. package/dist/cli/commands/upgrade.js +172 -79
  52. package/dist/cli/commands/usage.js +125 -51
  53. package/dist/cli/commands/version.js +21 -7
  54. package/dist/cli/commands/which.js +9 -24
  55. package/dist/cli/compile-cache.js +32 -0
  56. package/dist/cli/diagnostics.js +184 -0
  57. package/dist/cli/exit.js +65 -0
  58. package/dist/cli/group.js +24 -12
  59. package/dist/cli/help.js +62 -0
  60. package/dist/cli/highlight.js +236 -0
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +186 -1
  63. package/dist/cli/launch.js +52 -39
  64. package/dist/cli/launchers.js +161 -95
  65. package/dist/cli/main.js +201 -31
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +459 -0
  69. package/dist/cli/registry.js +61 -6
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +561 -0
  73. package/dist/cli/style.js +311 -0
  74. package/dist/cli/topics.js +142 -0
  75. package/dist/core/config.js +181 -23
  76. package/dist/core/exhausted.js +6 -8
  77. package/dist/core/fsutil.js +39 -0
  78. package/dist/core/journal.js +294 -16
  79. package/dist/core/manifest.js +153 -6
  80. package/dist/core/paths.js +14 -13
  81. package/dist/core/profiles.js +160 -10
  82. package/dist/core/resolve.js +139 -23
  83. package/dist/core/secrets.js +68 -23
  84. package/dist/core/sessions.js +13 -20
  85. package/dist/core/state-file.js +107 -0
  86. package/dist/core/update.js +31 -18
  87. package/dist/core/version.js +57 -10
  88. package/dist/demo/server.js +42 -0
  89. package/dist/mcpd/cache.js +23 -10
  90. package/dist/mcpd/calllog.js +254 -0
  91. package/dist/mcpd/client-names.js +46 -0
  92. package/dist/mcpd/connectors.js +188 -18
  93. package/dist/mcpd/daemon.js +472 -115
  94. package/dist/mcpd/folder-sets.js +42 -0
  95. package/dist/mcpd/gateway.js +473 -51
  96. package/dist/mcpd/health.js +313 -0
  97. package/dist/mcpd/importer.js +453 -36
  98. package/dist/mcpd/instances.js +453 -65
  99. package/dist/mcpd/jsonrpc.js +11 -1
  100. package/dist/mcpd/launchd.js +65 -48
  101. package/dist/mcpd/middleware.js +144 -0
  102. package/dist/mcpd/modern.js +686 -0
  103. package/dist/mcpd/oauth.js +845 -0
  104. package/dist/mcpd/peerpid.js +134 -6
  105. package/dist/mcpd/pressure.js +88 -0
  106. package/dist/mcpd/rss.js +166 -0
  107. package/dist/mcpd/service.js +191 -0
  108. package/dist/mcpd/share.js +217 -0
  109. package/dist/mcpd/state.js +183 -0
  110. package/dist/mcpd/sync.js +72 -87
  111. package/dist/mcpd/systemd.js +83 -0
  112. package/dist/mcpd/tokens.js +85 -0
  113. package/dist/mcpd/upstream.js +163 -46
  114. package/dist/statusline/cost.js +167 -44
  115. package/dist/statusline/input.js +78 -0
  116. package/dist/statusline/render.js +9 -3
  117. package/dist/ui/fonts.js +8 -3
  118. package/dist/ui/settings.js +33 -16
  119. package/npm-shrinkwrap.json +1102 -0
  120. package/package.json +10 -9
  121. package/dist/cli/commands/available.js +0 -18
@@ -1,38 +1,45 @@
1
1
  import { existsSync, statSync } from "node:fs";
2
2
  import { resolve as resolvePath } from "node:path";
3
- import { adapter, agentProfileDir, isAgentId, AGENT_IDS } from "../../agents/index.js";
3
+ import { delimiter } from "node:path";
4
+ import { DEFAULT_AGENT, adapter, agentHub, agentProfileDir, isAgentId, AGENT_IDS, } from "../../agents/index.js";
4
5
  import { editConfig } from "../../core/config-edit.js";
5
6
  import { loadConfig } from "../../core/config.js";
6
7
  import { exhaustedUntil } from "../../core/exhausted.js";
7
8
  import { Journal } from "../../core/journal.js";
8
9
  import { expandHome, paths, tildify } from "../../core/paths.js";
9
10
  import { agentOf, listProfiles } from "../../core/profiles.js";
10
- import { resolveProfile } from "../../core/resolve.js";
11
- import { addArrayTable, ensureTable, removeArrayTables, removeTable, setValue } from "../../core/toml-edit.js";
11
+ import { candidateRoots, folderMcpSet, resolveProfile } from "../../core/resolve.js";
12
+ import { addArrayTable, ensureTable, removeArrayTables, removeTable, setValue, } from "../../core/toml-edit.js";
12
13
  import { NAMED_COLORS } from "../../statusline/render.js";
13
- import { DRY_RUN, JSON_FLAG, bool, 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";
14
16
  import { group } from "../group.js";
15
- import { fail } from "../io.js";
16
- import { launcherPath } from "../launch.js";
17
- import { isGenerated, launcherName } from "../launchers.js";
18
- import { checkName, setupProfiles } from "./setup.js";
19
- import { authStatus } from "./usage.js";
17
+ import { nextStep } from "../hints.js";
18
+ import { confirm, fail, needsAnswer, plural } from "../io.js";
19
+ import { emit, jsonOutput } from "../output.js";
20
+ import { profileColor, style } from "../style.js";
21
+ import { findOnPath, launcherPath } from "../launch.js";
22
+ import { isGenerated, launcherName, refuseNpx } from "../launchers.js";
23
+ import { checkName, localCopies, setupProfiles } from "./setup.js";
24
+ import { authStatus, shortTime } from "./usage.js";
20
25
  /** A named color, or a 256-color code. */
21
- export function parseColor(v) {
26
+ export function parseColor(v, label = "--color") {
22
27
  if (/^\d+$/.test(v)) {
23
28
  const n = Number(v);
24
29
  if (n > 255)
25
- fail(`--color ${v}: a 256-color code goes from 0 to 255`);
30
+ fail(`${label} ${v}: a 256-color code goes from 0 to 255`);
26
31
  return n;
27
32
  }
28
33
  if (NAMED_COLORS[v.toLowerCase()] === undefined)
29
- fail(`--color ${v}: use a number (0-255) or one of ${Object.keys(NAMED_COLORS).join(", ")}`);
34
+ fail(`${label} ${v}: use a number (0-255) or one of ${Object.keys(NAMED_COLORS).join(", ")}`);
30
35
  return v.toLowerCase();
31
36
  }
32
37
  export async function profilesData(env, config, withAccounts = true) {
33
38
  const names = listProfiles(config, env);
34
39
  // Account details come from `claude auth status`; other agents show whether they are set up.
35
- const auth = withAccounts ? await Promise.all(names.map((n) => (agentOf(n, config) === "claude" ? 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
+ : [];
36
43
  return names.map((name, i) => {
37
44
  const s = auth[i];
38
45
  const agent = agentOf(name, config);
@@ -42,99 +49,206 @@ export async function profilesData(env, config, withAccounts = true) {
42
49
  agent,
43
50
  dir: tildify(dir, env),
44
51
  setUp: existsSync(dir) && Boolean(launcherPath(name, env, agent)),
45
- ...(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
+ : {}),
46
55
  color: config.profiles[name]?.color ?? null,
47
56
  browser: config.profiles[name]?.browser ?? "chrome",
48
- 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),
49
62
  projects: config.projects.filter((r) => r.profile === name).length,
50
63
  exhaustedUntil: exhaustedUntil(name, env) ?? null,
51
64
  };
52
65
  });
53
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
+ ]);
54
81
  async function list(args, io) {
55
82
  const p = parseFlags(args, JSON_FLAG, 0);
56
83
  const config = loadConfig(io.env);
57
84
  const rows = await profilesData(io.env, config);
58
85
  if (bool(p, "json")) {
59
- printJson(io.out, rows);
86
+ emit(io, p, LIST_JSON, rows);
60
87
  return 0;
61
88
  }
62
89
  if (!rows.length) {
63
90
  io.out("No profiles yet. Create one with: turno profile add <name>");
64
91
  return 0;
65
92
  }
66
- const w = Math.max(...rows.map((r) => r.name.length));
67
- for (const r of rows) {
68
- const who = r.setUp
69
- ? r.agent !== "claude"
70
- ? `${adapter(r.agent).label} (${launcherName(r.name, r.agent)})`
71
- : r.email
72
- ? `${r.email}${r.plan ? ` · ${r.plan}` : ""}`
73
- : "not logged in"
74
- : `not set up (turno profile repair ${r.name})`;
75
- const extra = [r.roles.join(", "), r.projects ? `${r.projects} projects` : "", r.exhaustedUntil ? "exhausted" : ""].filter(Boolean).join(" · ");
76
- io.out(`${r.name.padEnd(w)} ${who}${extra ? ` (${extra})` : ""}`);
77
- }
93
+ for (const line of renderProfiles(rows, config, io))
94
+ io.out(line);
78
95
  return 0;
79
96
  }
97
+ /**
98
+ * `turno profile list` as lines: each profile as its pill, its agent, its account, how many
99
+ * folders use it, and its roles. Plain text (a pipe, NO_COLOR) keeps one row per profile
100
+ * starting with its name.
101
+ */
102
+ export function renderProfiles(rows, config, io, now = Date.now() / 1000) {
103
+ const s = style(io);
104
+ const table = rows.map((r) => {
105
+ const a = adapter(r.agent);
106
+ const who = !r.setUp
107
+ ? s.warn(`not set up (turno profile repair ${r.name})`)
108
+ : !a.accountDetails
109
+ ? s.muted(s.color ? "-" : launcherName(r.name, r.agent))
110
+ : r.email
111
+ ? `${r.email}${r.plan ? s.muted(` · ${r.plan}`) : ""}`
112
+ : s.warn("not logged in");
113
+ const exhausted = r.exhaustedUntil && r.exhaustedUntil > now ? s.warn(`exhausted until ${shortTime(r.exhaustedUntil)}`) : "";
114
+ const flags = [r.roles.join(", "), exhausted].filter(Boolean).join(s.muted(" · "));
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
+ ];
122
+ });
123
+ if (!s.color)
124
+ return s.table(table, { indent: 0 });
125
+ // turno reads no account for agents without account details: a "-" there, not the launcher.
126
+ const head = ["", "agent", "account", "folders", "role"].map((h) => s.muted(h));
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
+ ];
133
+ }
134
+ /** The PATH line for a shell, or undefined when `dir` is on PATH. */
135
+ export function pathAdvice(env, dir = paths(env).bin) {
136
+ if ((env.PATH ?? "").split(delimiter).some((d) => d.replace(/\/+$/, "") === dir))
137
+ return undefined;
138
+ const shell = (env.SHELL ?? "").split("/").pop();
139
+ const shown = tildify(dir, env).replace(/^~/, "$HOME");
140
+ if (shell === "fish")
141
+ return `Add to ~/.config/fish/config.fish: fish_add_path ${shown.replace("$HOME", "~")}`;
142
+ const rc = shell === "bash" ? "~/.bashrc" : "~/.zshrc";
143
+ return `Add to ${rc}: export PATH="${shown}:$PATH"`;
144
+ }
145
+ /** Warn when the folder of the launchers is not on PATH, so `claude-<name>` would not be found. */
146
+ export function warnPath(io, launcher) {
147
+ const advice = pathAdvice(io.env);
148
+ if (!advice)
149
+ return false;
150
+ io.err(`warning: ${tildify(paths(io.env).bin, io.env)} is not on your PATH, so ${launcher} will not be found. ${advice}`);
151
+ return true;
152
+ }
153
+ /**
154
+ * Before moving the person's own files aside: ask in a terminal, or need --yes. Returns false
155
+ * when the person said no.
156
+ */
157
+ async function approveAside(cmd, names, io, yes) {
158
+ const own = localCopies(names, io.env).filter((x) => x.items.length);
159
+ if (!own.length || yes)
160
+ return true;
161
+ const text = own.map((x) => `${tildify(x.dir, io.env)} has its own ${x.items.join(", ")}`).join("; ");
162
+ const what = `${text}. turno moves ${own.length === 1 && own[0].items.length === 1 ? "it" : "them"} to .aside-<time>/ in that folder and links the shared ones instead.`;
163
+ io.err(what);
164
+ if (!io.ask)
165
+ needsAnswer(cmd);
166
+ if (await confirm(io, "Go ahead?"))
167
+ return true;
168
+ io.err("Nothing changed.");
169
+ return false;
170
+ }
171
+ const ADD_SPEC = {
172
+ agent: { type: "string" },
173
+ color: { type: "string" },
174
+ browser: { type: "string" },
175
+ ...DRY_RUN,
176
+ yes: { type: "boolean", short: "y" },
177
+ verbose: { type: "boolean", short: "v" },
178
+ };
80
179
  async function add(args, io) {
81
- const p = parseFlags(args, { color: { type: "string" }, browser: { type: "string" }, agent: { type: "string" }, ...DRY_RUN }, 1);
180
+ const p = parseFlags(args, ADD_SPEC, 1);
82
181
  const name = p.positionals[0];
83
182
  if (!name)
84
- return fail("usage: turno profile add <name> [--agent claude|codex|copilot|cursor] [--color <c>] [--browser chrome|default]");
183
+ return fail(`usage: turno profile add <name> [--agent ${AGENT_IDS.join("|")}] [--color <c>] [--browser chrome|default]`);
85
184
  checkName(name);
86
- const agent = str(p, "agent") ?? "claude";
185
+ const agent = str(p, "agent") ?? DEFAULT_AGENT;
87
186
  if (!isAgentId(agent))
88
187
  fail(`--agent must be one of ${AGENT_IDS.join(", ")}`);
89
188
  const color = str(p, "color");
189
+ const parsedColor = color ? parseColor(color) : undefined;
90
190
  const browser = str(p, "browser");
91
191
  if (browser && browser !== "chrome" && browser !== "default")
92
192
  fail("--browser must be chrome or default");
93
193
  const dry = bool(p, "dry-run");
194
+ if (!dry) {
195
+ refuseNpx();
196
+ if (!(await approveAside("profile add", [name], io, bool(p, "yes"))))
197
+ return 1;
198
+ }
94
199
  const journal = new Journal(io.env, `profile add ${name}`, dry);
95
200
  const table = `profiles.${name}`;
96
201
  const { changed } = editConfig(io.env, journal, (t) => {
97
202
  let text = ensureTable(t, table);
98
- if (agent !== "claude")
203
+ if (agent !== DEFAULT_AGENT)
99
204
  text = setValue(text, table, "agent", agent);
100
- if (color)
101
- text = setValue(text, table, "color", parseColor(color));
205
+ if (parsedColor !== undefined)
206
+ text = setValue(text, table, "color", parsedColor);
102
207
  if (browser)
103
208
  text = setValue(text, table, "browser", browser);
104
209
  return text;
105
210
  });
106
211
  io.out(`${changed ? "+" : "="} [${table}] in ${tildify(paths(io.env).configFile, io.env)}${dry ? " (dry run)" : ""}`);
212
+ const a = adapter(agent);
213
+ if (!findOnPath(a.command, io.env))
214
+ io.err(`warning: ${a.command} is not installed yet (${a.install}); the profile works once it is`);
107
215
  if (dry) {
108
216
  io.out(`(dry run) would set up ${tildify(agentProfileDir(name, agent, io.env), io.env)} and the ${launcherName(name, agent)} command`);
109
217
  return 0;
110
218
  }
111
- setupProfiles([name], io);
112
- io.out("");
113
- const login = {
114
- claude: `run claude-${name} and sign in with /login`,
115
- codex: `run codex-${name} login`,
116
- copilot: `run copilot-${name} and sign in with /login`,
117
- cursor: `run cursor-agent-${name} login`,
118
- };
119
- io.out(`Next: ${login[agent]}. turno profile list shows the profile.`);
219
+ // The same journal as the config.toml change: one `turno undo` reverts the whole profile add.
220
+ setupProfiles([name], io, { verbose: bool(p, "verbose"), journal });
221
+ const launcher = launcherName(name, agent);
222
+ const offPath = warnPath(io, launcher);
223
+ // `turno <name>` works without ~/.local/bin on PATH.
224
+ const run = offPath ? `turno ${name}` : launcher;
225
+ const sub = adapter(agent).loginSubcommand;
226
+ nextStep(io, `${sub ? `run ${run} ${sub}` : `run ${run} and sign in with /login`}. turno profile list shows the profile.`);
120
227
  const hint = journal.hint();
121
228
  if (hint)
122
229
  io.out(hint);
123
230
  return 0;
124
231
  }
232
+ const REPAIR_SPEC = { yes: { type: "boolean", short: "y" }, verbose: { type: "boolean", short: "v" } };
125
233
  async function repair(args, io) {
126
- const p = parseFlags(args, {});
234
+ const p = parseFlags(args, REPAIR_SPEC);
127
235
  const names = p.positionals.length ? p.positionals : listProfiles(loadConfig(io.env), io.env);
128
236
  if (!names.length)
129
237
  return fail("no profiles to repair (turno profile add <name>)");
130
- setupProfiles(names, io);
238
+ for (const n of names)
239
+ checkName(n);
240
+ refuseNpx();
241
+ if (!(await approveAside("profile repair", names, io, bool(p, "yes"))))
242
+ return 1;
243
+ setupProfiles(names, io, { verbose: bool(p, "verbose") });
131
244
  return 0;
132
245
  }
133
246
  async function remove(args, io) {
134
247
  const p = parseFlags(args, DRY_RUN, 1);
135
- const name = p.positionals[0];
136
- if (!name)
137
- return fail("usage: turno profile remove <name>");
248
+ const dry = bool(p, "dry-run");
249
+ const picked = !p.positionals[0];
250
+ const name = p.positionals[0] ??
251
+ (await (await import("../picker.js")).pickProfile(io, { command: "profile remove", title: "Profile to remove" }));
138
252
  const config = loadConfig(io.env);
139
253
  if (!listProfiles(config, io.env).includes(name))
140
254
  fail(`no profile '${name}'`);
@@ -142,20 +256,24 @@ async function remove(args, io) {
142
256
  if (config[role] === name)
143
257
  fail(`${name} is the ${role} profile; point ${role} elsewhere first (turno config set ${role} <profile>)`);
144
258
  }
145
- const dry = bool(p, "dry-run");
259
+ // A profile chosen in the picker is confirmed: one key should not remove an account.
260
+ if (picked && !dry && !(await confirm(io, `Remove ${name} from config.toml and its launcher? Its folder stays.`))) {
261
+ io.err("Nothing changed.");
262
+ return 1;
263
+ }
146
264
  const journal = new Journal(io.env, `profile remove ${name}`, dry);
147
265
  let rules = 0;
148
266
  editConfig(io.env, journal, (t) => {
149
267
  const r = removeArrayTables(removeTable(t, `profiles.${name}`), "projects", (e) => e.profile === name);
150
268
  rules = r.removed;
151
- return r.text;
269
+ return keepSets(r.text, config.projects.filter((x) => x.profile === name), io.env);
152
270
  });
153
271
  const agent = agentOf(name, config);
154
272
  const launcher = launcherPath(name, io.env, agent);
155
273
  if (launcher && isGenerated(launcher))
156
274
  journal.remove(launcher);
157
275
  const d = dry ? " (dry run)" : "";
158
- io.out(`- [profiles.${name}] and ${rules} project rules from config.toml${d}`);
276
+ io.out(`- [profiles.${name}] and ${plural(rules, "project rule")} from config.toml${d}`);
159
277
  if (launcher)
160
278
  io.out(`- ${tildify(launcher, io.env)}${d}`);
161
279
  io.out(`${tildify(agentProfileDir(name, agent, io.env), io.env)} stays (sign-in, history); delete it by hand when you no longer need it.`);
@@ -164,6 +282,26 @@ async function remove(args, io) {
164
282
  io.out(hint);
165
283
  return 0;
166
284
  }
285
+ /** The server set keys of a rule, to write back when its profile part goes. */
286
+ function setKeys(rule) {
287
+ return { ...(rule?.mcp ? { mcp: rule.mcp } : {}), ...(rule?.mcpDeny ? { mcp_deny: rule.mcpDeny } : {}) };
288
+ }
289
+ /** Write back, as rules of their own, the server sets of removed profile rules: the folder keeps them. */
290
+ function keepSets(text, removed, env) {
291
+ let out = text;
292
+ for (const r of removed)
293
+ if (r.mcp || r.mcpDeny)
294
+ out = addArrayTable(out, "projects", { path: tildify(r.path, env), ...setKeys(r) });
295
+ return out;
296
+ }
297
+ /** "only docs, not mail": what a folder's server set lets sessions see. */
298
+ function setText(set) {
299
+ const parts = [
300
+ set.mcp ? `only ${set.mcp.join(", ") || "none"}` : "",
301
+ set.mcpDeny ? `${set.mcp ? "not" : "all but"} ${set.mcpDeny.join(", ")}` : "",
302
+ ];
303
+ return parts.filter(Boolean).join(", ");
304
+ }
167
305
  function folder(arg, io) {
168
306
  const dir = resolvePath(expandHome(arg ?? process.cwd(), io.env));
169
307
  let ok = false;
@@ -177,25 +315,141 @@ function folder(arg, io) {
177
315
  fail(`no such folder: ${arg ?? dir}`);
178
316
  return dir;
179
317
  }
180
- async function which(args, io) {
181
- const p = parseFlags(args, JSON_FLAG, 1);
318
+ /** How a folder resolves for each agent that has profiles (Claude Code always). */
319
+ /** Each agent's resolution of `dir`; `roots` is computed once (one git call) for all of them. */
320
+ export function resolveAll(dir, config, env, roots = candidateRoots(dir)) {
321
+ const agents = AGENT_IDS.filter((a) => a === DEFAULT_AGENT || listProfiles(config, env, a).length > 0);
322
+ return agents.map((agent) => ({ agent, r: resolveProfile(dir, config, env, roots, agent) }));
323
+ }
324
+ /** "work (project ~/code)", or the plain agent and its home. */
325
+ export function usingText(agent, r, env, config) {
326
+ if (r.note)
327
+ return `${r.chosen} (${r.assigned} ${r.note})`;
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})` };
377
+ }
378
+ export async function whichCommand(args, io) {
379
+ const p = parseFlags(args, WHICH_SPEC, 1);
182
380
  const dir = folder(p.positionals[0], io);
183
- const r = resolveProfile(dir, loadConfig(io.env), io.env);
381
+ const config = loadConfig(io.env);
382
+ const roots = candidateRoots(dir);
383
+ const all = resolveAll(dir, config, io.env, roots);
384
+ const r = all[0].r;
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
+ }
184
397
  if (bool(p, "json")) {
185
- printJson(io.out, { dir: tildify(dir, io.env), assigned: r.assigned || null, chosen: r.chosen || null, reason: r.reason, note: r.note || null });
186
- return 0;
398
+ const one = (x) => ({
399
+ assigned: x.assigned || null,
400
+ chosen: x.chosen || null,
401
+ reason: x.reason,
402
+ note: x.note || null,
403
+ });
404
+ const mcp = set ? { rule: tildify(set.path, io.env), allow: set.mcp ?? null, deny: set.mcpDeny ?? null } : null;
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;
187
429
  }
188
430
  io.out(tildify(dir, io.env));
189
431
  io.out(` assigned: ${r.assigned || "none"} (${r.reason})`);
190
- 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")}`);
435
+ for (const { agent, r: x } of all.slice(1))
436
+ io.out(` ${agent}: ${usingText(agent, x, io.env)}`);
437
+ if (set)
438
+ io.out(` mcp: ${setText(set)} (rule ${tildify(set.path, io.env)})`);
191
439
  return 0;
192
440
  }
193
441
  async function assign(args, io) {
194
442
  const p = parseFlags(args, DRY_RUN, 2);
195
- const [dirArg, name] = p.positionals;
196
- if (!dirArg || !name)
197
- return fail("usage: turno profile assign <dir> <profile>");
443
+ const [dirArg, given] = p.positionals;
444
+ if (dirArg &&
445
+ !given &&
446
+ !existsSync(expandHome(dirArg, io.env)) &&
447
+ listProfiles(loadConfig(io.env), io.env).includes(dirArg)) {
448
+ fail(`no such folder: ${dirArg} (to give this folder the profile ${dirArg}: turno profile assign . ${dirArg})`);
449
+ }
198
450
  const dir = folder(dirArg, io);
451
+ const name = given ??
452
+ (await (await import("../picker.js")).pickProfile(io, { command: "profile assign", title: `Profile for ${tildify(dir, io.env)}`, dir }));
199
453
  const config = loadConfig(io.env);
200
454
  if (!listProfiles(config, io.env).includes(name))
201
455
  fail(`no profile '${name}' (turno profile list)`);
@@ -203,15 +457,26 @@ async function assign(args, io) {
203
457
  const journal = new Journal(io.env, `profile assign ${tildify(dir, io.env)} ${name}`, dry);
204
458
  const shown = tildify(dir, io.env);
205
459
  // One rule per folder and agent: a Codex rule does not replace the folder's Claude Code rule.
460
+ // A rule with only a server set is not a profile rule and stays; a replaced rule
461
+ // passes its set on to the new one.
206
462
  const agent = agentOf(name, config);
207
- editConfig(io.env, journal, (t) => {
208
- const r = removeArrayTables(t, "projects", (e) => resolvePath(expandHome(e.path ?? "", io.env)) === dir && agentOf(e.profile ?? "", config) === agent);
209
- return addArrayTable(r.text, "projects", { path: shown, profile: name });
210
- });
463
+ const same = (e) => e.profile !== undefined &&
464
+ resolvePath(expandHome(e.path ?? "", io.env)) === dir &&
465
+ agentOf(e.profile, config) === agent;
466
+ const carried = config.projects.find((r) => same(r) && (r.mcp || r.mcpDeny));
467
+ editConfig(io.env, journal, (t) => addArrayTable(removeArrayTables(t, "projects", same).text, "projects", {
468
+ path: shown,
469
+ profile: name,
470
+ ...setKeys(carried),
471
+ }));
211
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);
212
475
  const hint = journal.hint();
213
476
  if (hint)
214
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)`);
215
480
  return 0;
216
481
  }
217
482
  async function unassign(args, io) {
@@ -219,11 +484,14 @@ async function unassign(args, io) {
219
484
  const dir = resolvePath(expandHome(p.positionals[0] ?? process.cwd(), io.env));
220
485
  const dry = bool(p, "dry-run");
221
486
  const journal = new Journal(io.env, `profile unassign ${tildify(dir, io.env)}`, dry);
487
+ const config = loadConfig(io.env);
488
+ // Profile rules only: the folder keeps its server set.
489
+ const own = (e) => e.profile !== undefined && resolvePath(expandHome(e.path ?? "", io.env)) === dir;
222
490
  let removed = 0;
223
491
  editConfig(io.env, journal, (t) => {
224
- const r = removeArrayTables(t, "projects", (e) => resolvePath(expandHome(e.path ?? "", io.env)) === dir);
492
+ const r = removeArrayTables(t, "projects", own);
225
493
  removed = r.removed;
226
- return r.text;
494
+ return removed ? keepSets(r.text, config.projects.filter(own), io.env) : t;
227
495
  });
228
496
  if (!removed) {
229
497
  io.out(`${tildify(dir, io.env)} has no rule of its own (turno profile which explains what applies)`);
@@ -235,25 +503,75 @@ async function unassign(args, io) {
235
503
  io.out(hint);
236
504
  return 0;
237
505
  }
238
- export const command = group("profile", "Claude Code accounts: list, add, repair, remove, and which folders use each", {
239
- list: { summary: "each profile, its account and roles", synopsis: "[--json]", flags: ["--json"], run: list },
506
+ export const command = group("profile", "accounts (profiles) for each agent: list, add, repair, remove, and which folders use each", {
507
+ list: {
508
+ summary: "each profile, its account and roles",
509
+ synopsis: "[--json]",
510
+ flags: ["--json"],
511
+ json: LIST_JSON,
512
+ run: list,
513
+ },
240
514
  add: {
241
- summary: "declare a profile in config.toml and set up its folder and launcher (claude-<name>, codex-<name>, ...)",
242
- synopsis: "<name> [--agent claude|codex|copilot|cursor] [--color <c>] [--browser chrome|default] [--dry-run]",
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",
516
+ synopsis: "<name> [--agent claude|codex|copilot|cursor] [--color <c>] [--browser chrome|default] [--dry-run] [--yes] [-v]",
243
517
  args: ["any"],
244
- flags: ["--agent", "--color", "--browser", "--dry-run"],
518
+ flags: flagsOf(ADD_SPEC),
245
519
  run: add,
246
520
  },
247
- repair: { summary: "relink shared folders and rewrite launchers (all profiles by default)", synopsis: "[profile...]", args: ["profile"], run: repair },
521
+ repair: {
522
+ summary: "relink shared folders and rewrite launchers (all profiles by default); turno undo reverts it",
523
+ synopsis: "[profile...] [--yes] [-v]",
524
+ args: ["profile"],
525
+ flags: flagsOf(REPAIR_SPEC),
526
+ run: repair,
527
+ },
248
528
  remove: {
249
- summary: "drop a profile from config.toml and its launcher (its folder stays)",
250
- synopsis: "<name> [--dry-run]",
529
+ summary: "drop a profile from config.toml and its launcher (its folder stays); without a name, choose one and confirm",
530
+ synopsis: "[name] [--dry-run]",
251
531
  args: ["profile"],
252
532
  flags: ["--dry-run"],
253
533
  run: remove,
254
534
  },
255
- which: { summary: "which profile auto uses in a folder, and why", synopsis: "[dir] [--json]", args: ["dir"], flags: ["--json"], run: which },
256
- assign: { summary: "make a folder (and everything under it) use a profile", synopsis: "<dir> <profile> [--dry-run]", args: ["dir", "profile"], flags: ["--dry-run"], run: assign },
257
- unassign: { summary: "remove a folder's own rule", synopsis: "[dir] [--dry-run]", args: ["dir"], flags: ["--dry-run"], run: unassign },
258
- }, { fallback: "list" });
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
+ },
549
+ assign: {
550
+ summary: "make a folder (and everything under it) use a profile; without a profile, choose one from a list",
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,
562
+ },
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
+ });
259
577
  //# sourceMappingURL=profile.js.map