turno-cli 0.1.0 → 0.2.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 (105) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +143 -75
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/core/version.js +6 -0
  74. package/dist/demo/server.js +34 -0
  75. package/dist/mcpd/cache.js +18 -4
  76. package/dist/mcpd/calllog.js +253 -0
  77. package/dist/mcpd/client-names.js +51 -0
  78. package/dist/mcpd/connectors.js +148 -17
  79. package/dist/mcpd/daemon.js +452 -116
  80. package/dist/mcpd/folder-sets.js +39 -0
  81. package/dist/mcpd/gateway.js +441 -47
  82. package/dist/mcpd/health.js +269 -0
  83. package/dist/mcpd/importer.js +356 -36
  84. package/dist/mcpd/instances.js +425 -65
  85. package/dist/mcpd/jsonrpc.js +8 -0
  86. package/dist/mcpd/launchd.js +65 -48
  87. package/dist/mcpd/modern.js +648 -0
  88. package/dist/mcpd/oauth.js +791 -0
  89. package/dist/mcpd/peerpid.js +122 -6
  90. package/dist/mcpd/pressure.js +85 -0
  91. package/dist/mcpd/rss.js +151 -0
  92. package/dist/mcpd/service.js +167 -0
  93. package/dist/mcpd/state.js +183 -0
  94. package/dist/mcpd/sync.js +55 -80
  95. package/dist/mcpd/systemd.js +80 -0
  96. package/dist/mcpd/tokens.js +89 -0
  97. package/dist/mcpd/upstream.js +154 -44
  98. package/dist/statusline/cost.js +154 -44
  99. package/dist/statusline/input.js +66 -0
  100. package/dist/statusline/render.js +9 -3
  101. package/dist/ui/fonts.js +8 -3
  102. package/dist/ui/settings.js +27 -15
  103. package/npm-shrinkwrap.json +1093 -0
  104. package/package.json +9 -9
  105. package/dist/cli/commands/available.js +0 -18
@@ -0,0 +1,616 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { dirname, join, resolve as resolvePath } from "node:path";
3
+ import { AGENT_IDS, DEFAULT_AGENT, adapter, agentHub, agentProfileDir, isAgentId, mcpFileFor } from "../../agents/index.js";
4
+ import { editConfig, migrationPending, MigrationPending, readConfigText } from "../../core/config-edit.js";
5
+ import { loadConfig, parseConfig } from "../../core/config.js";
6
+ import { Journal } from "../../core/journal.js";
7
+ import { loadManifest, parseManifest } from "../../core/manifest.js";
8
+ import { expandHome, paths, tildify } from "../../core/paths.js";
9
+ import { agentOf, listProfiles } from "../../core/profiles.js";
10
+ import { addArrayTable, ensureTable, setValue } from "../../core/toml-edit.js";
11
+ import { DRY_RUN, bool, flagsOf, parseFlags, str } from "../args.js";
12
+ import { highlightTomlLine, tomlState } from "../highlight.js";
13
+ import { colors, confirm, fail, needsAnswer, paint, plural, wrap } from "../io.js";
14
+ import { duration, profileColor, spinner, style, visibleWidth } from "../style.js";
15
+ import { launcherPath } from "../launch.js";
16
+ import { findOnPath, launcherName, refuseNpx } from "../launchers.js";
17
+ import { resolveAll, warnPath } from "./profile.js";
18
+ import { RESERVED, checkName, localCopies, setupProfiles } from "./setup.js";
19
+ // Detection -----------------------------------------------------------------------------------
20
+ function isDir(p) {
21
+ try {
22
+ return statSync(p).isDirectory();
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /** `~/.claude-x`, `~/.codex-y`, ... that look like an agent home and are not turno profiles yet. */
29
+ function foundFolders(env, known, notes) {
30
+ const home = paths(env).home;
31
+ let entries = [];
32
+ try {
33
+ entries = readdirSync(home).sort();
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ const out = [];
39
+ const taken = new Map();
40
+ for (const agent of AGENT_IDS) {
41
+ const prefix = adapter(agent).dirPrefix;
42
+ for (const entry of entries) {
43
+ if (!entry.startsWith(prefix))
44
+ continue;
45
+ const name = entry.slice(prefix.length);
46
+ const dir = join(home, entry);
47
+ if (!isDir(dir) || !adapter(agent).homeMarkers.some((m) => existsSync(join(dir, m))))
48
+ continue;
49
+ if (known.has(name))
50
+ continue;
51
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(name) || RESERVED.has(name)) {
52
+ notes.push(`${tildify(dir, env)} looks like a ${adapter(agent).label} home, but "${name}" cannot be a profile name; left alone`);
53
+ continue;
54
+ }
55
+ const other = taken.get(name);
56
+ if (other) {
57
+ notes.push(`${tildify(dir, env)}: a ${adapter(other).label} profile named ${name} is already proposed; add this one by hand with another name`);
58
+ continue;
59
+ }
60
+ taken.set(name, agent);
61
+ out.push({ name, agent, adopted: true });
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+ /**
67
+ * Folder -> the accounts of the default agent it was used with ("" is the plain account of its
68
+ * hub), from the folders its configs remember (Claude Code's `projects`).
69
+ */
70
+ function folderOwners(env, profiles) {
71
+ const owners = new Map();
72
+ const m = adapter(DEFAULT_AGENT).mcp;
73
+ if (!m.foldersUsed)
74
+ return owners;
75
+ const add = (dir, who) => {
76
+ const d = resolvePath(dir);
77
+ owners.set(d, (owners.get(d) ?? new Set()).add(who));
78
+ };
79
+ for (const d of m.foldersUsed(m.hubFile(env)))
80
+ add(d, "");
81
+ for (const name of profiles)
82
+ for (const d of m.foldersUsed(mcpFileFor(name, DEFAULT_AGENT, env)))
83
+ add(d, name);
84
+ return owners;
85
+ }
86
+ const within = (dir, root) => dir === root || dir.startsWith(`${root}/`);
87
+ /**
88
+ * Folder rules from where each account was used: a folder (under HOME) used by exactly one
89
+ * profile gets a rule for it. Two or more such folders side by side, under a parent that holds
90
+ * no folder of anyone else, become one rule for the parent (never HOME itself). Folders an
91
+ * existing rule already covers get nothing.
92
+ */
93
+ export function inferRules(owners, home, ruled, dirExists = isDir) {
94
+ const covered = (d) => ruled.some((r) => within(d, r));
95
+ const only = (d) => {
96
+ const s = owners.get(d);
97
+ return s && s.size === 1 ? [...s][0] : undefined;
98
+ };
99
+ const cand = new Map();
100
+ for (const dir of owners.keys()) {
101
+ const who = only(dir);
102
+ if (!who || !within(dir, home) || dir === home || !dirExists(dir) || covered(dir))
103
+ continue;
104
+ cand.set(dir, who);
105
+ }
106
+ const byParent = new Map();
107
+ for (const dir of cand.keys())
108
+ byParent.set(dirname(dir), [...(byParent.get(dirname(dir)) ?? []), dir]);
109
+ for (const [parent, kids] of byParent) {
110
+ if (kids.length < 2 || !within(parent, home) || parent === home || covered(parent))
111
+ continue;
112
+ const who = cand.get(kids[0]);
113
+ if (kids.some((k) => cand.get(k) !== who))
114
+ continue;
115
+ if ([...owners.keys()].some((d) => within(d, parent) && only(d) !== who))
116
+ continue;
117
+ for (const k of kids)
118
+ cand.delete(k);
119
+ cand.set(parent, who);
120
+ }
121
+ // A folder under another proposed folder of the same profile needs no rule of its own.
122
+ for (const [dir, who] of [...cand]) {
123
+ if ([...cand].some(([other, o]) => other !== dir && within(dir, other) && o === who))
124
+ cand.delete(dir);
125
+ }
126
+ return [...cand].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, profile]) => ({ path, profile }));
127
+ }
128
+ // Text diff -----------------------------------------------------------------------------------
129
+ /** Line diff of two texts (longest common subsequence): " " same, "+" added, "-" removed. */
130
+ export function lineDiff(before, after) {
131
+ const a = before === "" ? [] : before.replace(/\n$/, "").split("\n");
132
+ const b = after === "" ? [] : after.replace(/\n$/, "").split("\n");
133
+ const n = a.length;
134
+ const m = b.length;
135
+ const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
136
+ for (let i = n - 1; i >= 0; i--)
137
+ for (let j = m - 1; j >= 0; j--)
138
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
139
+ const out = [];
140
+ let i = 0;
141
+ let j = 0;
142
+ while (i < n || j < m) {
143
+ if (i < n && j < m && a[i] === b[j]) {
144
+ out.push([" ", a[i]]);
145
+ i++;
146
+ j++;
147
+ }
148
+ else if (j < m && (i === n || lcs[i][j + 1] >= lcs[i + 1][j]))
149
+ out.push(["+", b[j++]]);
150
+ else
151
+ out.push(["-", a[i++]]);
152
+ }
153
+ return out;
154
+ }
155
+ /** The diff with two lines of context around each change; skipped runs show as "...". */
156
+ function printDiff(io, before, after) {
157
+ const st = style(io);
158
+ const d = lineDiff(before, after);
159
+ const near = d.map((_, k) => d.slice(Math.max(0, k - 2), k + 3).some(([op]) => op !== " "));
160
+ // Added and unchanged lines are the new text in order: highlight them as one TOML text.
161
+ const toml = tomlState();
162
+ let gap = false;
163
+ for (const [k, [op, line]] of d.entries()) {
164
+ const shown = op === "-" || !colors(io) ? line : highlightTomlLine(line, toml);
165
+ if (!near[k]) {
166
+ if (!gap)
167
+ io.out(paint(io, " ...", "2"));
168
+ gap = true;
169
+ continue;
170
+ }
171
+ gap = false;
172
+ io.out(op === "+" ? st.wrap(` ${paint(io, "+", "32")}`, shown) : op === "-" ? st.wrap(" ", paint(io, `-${line}`, "31")) : st.wrap(" ", shown));
173
+ }
174
+ }
175
+ /** New text shown as all added lines: a green `+`, then the line highlighted as TOML. */
176
+ function printAdded(io, text) {
177
+ const toml = tomlState();
178
+ const st = style(io);
179
+ for (const line of text.replace(/\n$/, "").split("\n"))
180
+ io.out(st.wrap(` ${paint(io, "+", "32")}`, colors(io) ? highlightTomlLine(line, toml) : line));
181
+ }
182
+ // Plan ----------------------------------------------------------------------------------------
183
+ const SPEC = {
184
+ ...DRY_RUN,
185
+ yes: { type: "boolean", short: "y" },
186
+ profile: { type: "string", multiple: true },
187
+ skip: { type: "string", multiple: true },
188
+ default: { type: "string" },
189
+ "no-mcp": { type: "boolean" },
190
+ start: { type: "boolean" },
191
+ "no-start": { type: "boolean" },
192
+ };
193
+ function list(p, name) {
194
+ const v = p.values[name];
195
+ return Array.isArray(v) ? v : [];
196
+ }
197
+ /** `work`, `cx:codex`. */
198
+ function parseProfileArg(arg) {
199
+ const [name = "", agent = DEFAULT_AGENT, ...rest] = arg.split(":");
200
+ if (rest.length || !isAgentId(agent))
201
+ fail(`--profile ${arg}: use <name> or <name>:<agent> (${AGENT_IDS.join(", ")})`);
202
+ checkName(name);
203
+ return { name, agent, adopted: false };
204
+ }
205
+ /** Yes unless the answer starts with n. */
206
+ async function askYes(io, question) {
207
+ const a = (await io.ask(`${question} [Y/n] `)).trim().toLowerCase();
208
+ return !a.startsWith("n");
209
+ }
210
+ /**
211
+ * The mcp.toml init proposes. Offline: npx servers get a command name guessed from the package,
212
+ * and `resolveMcp` asks npm for the real one only once the person has said to write.
213
+ */
214
+ async function mcpPlan(io, skip, profiles) {
215
+ if (skip)
216
+ return { kind: "skip" };
217
+ const file = paths(io.env).mcpFile;
218
+ if (existsSync(file)) {
219
+ let servers = 0;
220
+ try {
221
+ servers = Object.keys(loadManifest(io.env).servers).length;
222
+ }
223
+ catch {
224
+ /* turno mcp list shows the error */
225
+ }
226
+ return { kind: "keep", servers };
227
+ }
228
+ const { collectSources, foundSummary, importServers, mergeSources } = await import("../../mcpd/importer.js");
229
+ const { sources, problems } = collectSources(io.env, process.cwd(), profiles);
230
+ for (const pr of problems)
231
+ io.err(style(io).wrap("", `${paint(io, "warning", "33")}: ${pr}`));
232
+ const merged = mergeSources(sources);
233
+ const names = Object.keys(merged.servers);
234
+ if (!names.length)
235
+ return { kind: "none" };
236
+ const report = await importServers(merged.servers);
237
+ parseManifest(report.toml); // never write something that cannot be read back
238
+ return { kind: "import", summary: foundSummary(names, merged.from), notes: [...merged.notes, ...report.notes], report, servers: names, merged: merged.servers };
239
+ }
240
+ /** The manifest to write, with command names from npm (the only network call of init). */
241
+ async function resolveMcp(io, plan) {
242
+ const { importServers } = await import("../../mcpd/importer.js");
243
+ const { binOf } = await import("./mcp.js");
244
+ const report = await importServers(plan.merged, { binOf: (pkg) => binOf(io, pkg) });
245
+ parseManifest(report.toml);
246
+ return { toml: report.toml, notes: report.notes.filter((n) => n.includes("npm did not name")) };
247
+ }
248
+ async function makePlan(args, io, ask) {
249
+ const p = parseFlags(args, SPEC, 0);
250
+ const env = io.env;
251
+ if (migrationPending(env))
252
+ throw new MigrationPending(env);
253
+ const config = loadConfig(env);
254
+ const existing = listProfiles(config, env);
255
+ const notes = [];
256
+ for (const n of existing) {
257
+ const agent = agentOf(n, config);
258
+ if (!existsSync(agentProfileDir(n, agent, env)) || !launcherPath(n, env, agent))
259
+ notes.push(`profile ${n} is not set up yet: turno profile repair ${n}`);
260
+ }
261
+ const agents = AGENT_IDS.map((id) => ({ id, installed: Boolean(findOnPath(adapter(id).command, env)) }));
262
+ const skip = new Set(list(p, "skip"));
263
+ const wanted = list(p, "profile").map(parseProfileArg);
264
+ for (const w of wanted)
265
+ if (existing.includes(w.name))
266
+ fail(`--profile ${w.name}: that profile exists already`);
267
+ const known = new Set([...existing, ...wanted.map((w) => w.name)]);
268
+ const profiles = [...wanted];
269
+ for (const f of foundFolders(env, known, notes)) {
270
+ if (skip.has(f.name))
271
+ continue;
272
+ const dir = tildify(agentProfileDir(f.name, f.agent, env), env);
273
+ if (ask && !(await askYes(io, `Use ${dir} as the ${adapter(f.agent).label} profile ${f.name}?`)))
274
+ continue;
275
+ profiles.push(f);
276
+ }
277
+ if (ask && !existing.length && !profiles.length) {
278
+ const claudeHere = agents[0].installed || existsSync(paths(env).hub);
279
+ const fallbackAgent = claudeHere ? undefined : agents.find((a) => a.installed)?.id;
280
+ const suggestion = fallbackAgent ? `work:${fallbackAgent} personal:${fallbackAgent}` : "work personal";
281
+ const answer = (await io.ask(`Profiles to create (names; name:codex for another agent) [${suggestion}]: `)).trim() || suggestion;
282
+ if (!/^none$/i.test(answer)) {
283
+ for (const word of answer.split(/[\s,]+/).filter(Boolean)) {
284
+ const np = parseProfileArg(word);
285
+ if (!known.has(np.name))
286
+ profiles.push(np);
287
+ known.add(np.name);
288
+ }
289
+ }
290
+ }
291
+ // Folder rules for profiles of the default agent, from the projects each account was used in.
292
+ const claude = [...existing.filter((n) => agentOf(n, config) === DEFAULT_AGENT), ...profiles.filter((n) => n.agent === DEFAULT_AGENT).map((n) => n.name)];
293
+ const ruled = config.projects.map((r) => resolvePath(expandHome(r.path, env)));
294
+ const rules = inferRules(folderOwners(env, claude), paths(env).home, ruled);
295
+ let def = str(p, "default");
296
+ if (def !== undefined && !claude.includes(def))
297
+ fail(`--default ${def}: name a Claude Code profile (${claude.join(", ") || "none yet"})`);
298
+ if (def === undefined && !config.default && ask && claude.length) {
299
+ const suggestion = claude.includes("personal") ? "personal" : "none";
300
+ const answer = (await io.ask(`Default profile for folders without a rule (none: plain claude) [${suggestion}]: `)).trim() || suggestion;
301
+ if (answer !== "none") {
302
+ if (!claude.includes(answer))
303
+ fail(`${answer} is not a Claude Code profile here (${claude.join(", ")})`);
304
+ def = answer;
305
+ }
306
+ }
307
+ const folders = [...existing.map((name) => ({ name, agent: agentOf(name, config) })), ...profiles.filter((np) => np.adopted)];
308
+ const mcp = await mcpPlan(io, bool(p, "no-mcp"), folders);
309
+ const plan = { agents, existing, profiles, rules, ...(def ? { default: def } : {}), mcp, notes };
310
+ const before = readConfigText(env);
311
+ return { plan, before, after: editText(before, plan, env) };
312
+ }
313
+ function editText(text, plan, env) {
314
+ let t = text;
315
+ if (plan.default)
316
+ t = setValue(t, undefined, "default", plan.default);
317
+ for (const np of plan.profiles) {
318
+ t = ensureTable(t, `profiles.${np.name}`);
319
+ if (np.agent !== DEFAULT_AGENT)
320
+ t = setValue(t, `profiles.${np.name}`, "agent", np.agent);
321
+ }
322
+ for (const r of plan.rules)
323
+ t = addArrayTable(t, "projects", { path: tildify(r.path, env), profile: r.profile });
324
+ return t;
325
+ }
326
+ // Output --------------------------------------------------------------------------------------
327
+ const KEY = "not installed".length;
328
+ /** ` ✓ key value`, the value wrapped under its column within the terminal width. */
329
+ function field(io, st, state, key, value) {
330
+ const lead = ` ${st.check(state, "")}`;
331
+ const col = visibleWidth(lead) + KEY + 1;
332
+ // Wrapped on a terminal; whole lines in a pipe, so a search finds them.
333
+ const lines = st.color ? wrap(value, Math.max(30, st.width - col)) : [value];
334
+ io.out(`${lead}${st.muted(key.padEnd(KEY))} ${lines[0]}`);
335
+ for (const l of lines.slice(1))
336
+ io.out(`${" ".repeat(col)}${l}`);
337
+ }
338
+ function printFound(io, plan, st) {
339
+ const env = io.env;
340
+ const label = (id) => adapter(id).label;
341
+ const installed = plan.agents.filter((a) => a.installed).map((a) => `${label(a.id)} (${adapter(a.id).command})`);
342
+ const missing = plan.agents.filter((a) => !a.installed).map((a) => label(a.id));
343
+ io.out(st.header("Found"));
344
+ field(io, st, installed.length ? "ok" : "warn", "agents", installed.join(", ") || "none on PATH");
345
+ if (missing.length)
346
+ field(io, st, "skip", "not installed", missing.join(", "));
347
+ if (plan.existing.length)
348
+ field(io, st, "ok", "profiles", plan.existing.join(", "));
349
+ const adopted = plan.profiles.filter((np) => np.adopted);
350
+ if (adopted.length)
351
+ field(io, st, "ok", "folders", `${adopted.map((np) => tildify(agentProfileDir(np.name, np.agent, env), env)).join(", ")} (made by hand)`);
352
+ const m = plan.mcp;
353
+ if (m.kind === "keep")
354
+ field(io, st, "ok", "mcp.toml", `${tildify(paths(env).mcpFile, env)} with ${plural(m.servers, "server")} (kept as it is)`);
355
+ else if (m.kind === "import")
356
+ field(io, st, "ok", "MCP", m.summary.replace(/^found /, ""));
357
+ else if (m.kind === "none")
358
+ field(io, st, "skip", "MCP", "none in Claude Code, Codex, Cursor or Copilot CLI configs");
359
+ for (const n of plan.notes)
360
+ io.err(st.note("info", st.muted(`note: ${n}`)));
361
+ }
362
+ /** What setting up each profile does to its folder: shared links, and own files moved aside. */
363
+ function printProfiles(io, plan, config, st) {
364
+ const env = io.env;
365
+ if (!plan.profiles.length)
366
+ return;
367
+ const own = new Map(localCopies(plan.profiles.map((np) => np.name), env, config).map((x) => [x.name, x.items]));
368
+ const rows = [];
369
+ const asides = new Map();
370
+ for (const np of plan.profiles) {
371
+ const dir = tildify(agentProfileDir(np.name, np.agent, env), env);
372
+ const hub = tildify(agentHub(np.agent, env), env);
373
+ rows.push([
374
+ st.icon("add"),
375
+ st.profile(np.name, profileColor(config.profiles, np.name)),
376
+ adapter(np.agent).label,
377
+ `${dir}${np.adopted ? st.muted(" (exists)") : ""}`,
378
+ `${st.muted("command")} ${st.bold(launcherName(np.name, np.agent))}`,
379
+ st.muted(`shares ${hub}`),
380
+ ]);
381
+ const items = own.get(np.name) ?? [];
382
+ if (items.length)
383
+ asides.set(rows.length - 1, `moves your own ${items.join(", ")} to ${dir}/.aside-<time>/ (turno undo puts ${items.length === 1 ? "it" : "them"} back)`);
384
+ }
385
+ for (const [i, lines] of st.tableRows(rows, { columns: [{}, {}, { drop: 2 }, {}, {}, { drop: 3 }] }).entries()) {
386
+ for (const line of lines)
387
+ io.out(line);
388
+ const aside = asides.get(i);
389
+ if (aside)
390
+ io.out(st.wrap(` ${st.warn(st.icon("warn"))} `, st.muted(aside)));
391
+ }
392
+ }
393
+ function printPlan(io, plan, before, after, st) {
394
+ const env = io.env;
395
+ printFound(io, plan, st);
396
+ io.out("");
397
+ io.out(st.header("Plan"));
398
+ printProfiles(io, plan, parseConfig(after, paths(env).configFile, env), st);
399
+ if (after !== before) {
400
+ io.out("");
401
+ io.out(` ${st.bold(tildify(paths(env).configFile, env))}${before ? "" : st.muted(" (new file)")}`);
402
+ printDiff(io, before, after);
403
+ }
404
+ if (plan.mcp.kind === "import") {
405
+ const m = plan.mcp;
406
+ io.out("");
407
+ io.out(` ${st.bold(tildify(paths(env).mcpFile, env))}${st.muted(" (new file, mode 600)")}`);
408
+ printAdded(io, m.report.preview);
409
+ for (const n of groupNotes(m.notes))
410
+ io.err(st.note("info", st.muted(n)));
411
+ if (m.report.literalSecrets.length) {
412
+ io.err(st.note("warn", `${st.warn("warning")}: mcp.toml keeps literal secrets (${m.report.literalSecrets.join(", ")}); move them to the Keychain afterwards with: turno mcp import --write --move-secrets --force`));
413
+ }
414
+ }
415
+ if (!plan.default && !loadConfig(env).default && plan.profiles.some((np) => np.agent === DEFAULT_AGENT)) {
416
+ io.out("");
417
+ io.out(st.wrap(" ", st.muted("No default profile: folders without a rule open plain claude (set one with --default <profile>).")));
418
+ }
419
+ }
420
+ const SCOPE_UNKNOWN = 'scope project: unknown server, one process per project folder; set scope = "shared" if it ignores its folder';
421
+ /**
422
+ * Importer notes with the same text for several servers, as one note: `name: text` for one
423
+ * server, `a, b: text` for more, and plain words for the common scope note.
424
+ */
425
+ export function groupNotes(notes) {
426
+ const groups = new Map();
427
+ const order = [];
428
+ for (const n of notes) {
429
+ const m = /^([\w.@/-]+): (.+)$/.exec(n);
430
+ const key = m ? m[2] : n;
431
+ if (!groups.has(key))
432
+ order.push(key);
433
+ groups.set(key, [...(groups.get(key) ?? []), ...(m ? [m[1]] : [])]);
434
+ }
435
+ return order.map((text) => {
436
+ const names = groups.get(text);
437
+ if (!names.length)
438
+ return text;
439
+ if (names.length === 1)
440
+ return `${names[0]}: ${text}`;
441
+ if (text === SCOPE_UNKNOWN) {
442
+ return `scope project for ${names.join(", ")} (unknown servers: one process per project folder; set scope = "shared" for those that ignore their folder)`;
443
+ }
444
+ return `${names.join(", ")}: ${text}`;
445
+ });
446
+ }
447
+ /** `codex-cx login`, `claude-work (then /login)`. */
448
+ function loginHint(agent, command) {
449
+ const sub = adapter(agent).loginSubcommand;
450
+ return sub ? `${command} ${sub}` : `${command} (then /login)`;
451
+ }
452
+ /** Whether the plan leaves MCP servers for the gateway to serve. */
453
+ function hasServers(plan) {
454
+ return plan.mcp.kind === "import" || (plan.mcp.kind === "keep" && plan.mcp.servers > 0);
455
+ }
456
+ /**
457
+ * The launcher to try first: the profile this folder now resolves to, when init made it or it
458
+ * exists; else the first new profile.
459
+ */
460
+ function tryLauncher(io, plan) {
461
+ try {
462
+ const config = loadConfig(io.env);
463
+ const chosen = resolveAll(process.cwd(), config, io.env)[0]?.r.chosen;
464
+ if (chosen && listProfiles(config, io.env).includes(chosen))
465
+ return launcherName(chosen, agentOf(chosen, config));
466
+ }
467
+ catch {
468
+ /* fall back below */
469
+ }
470
+ const first = plan.profiles[0];
471
+ return first ? launcherName(first.name, first.agent) : undefined;
472
+ }
473
+ function printNext(io, plan, started, st) {
474
+ const steps = [];
475
+ if (plan.profiles.length)
476
+ steps.push([`sign in once per profile where needed: ${plan.profiles.map((np) => loginHint(np.agent, launcherName(np.name, np.agent))).join(", ")}`, ""]);
477
+ if (hasServers(plan) && !started) {
478
+ steps.push(["turno mcp daemon start", "the gateway, as a login service"]);
479
+ steps.push(["turno mcp sync", "point every profile at it"]);
480
+ }
481
+ steps.push(["turno ui install", "optional: the status line and its font"]);
482
+ io.out(st.header("Next"));
483
+ const w = Math.max(...steps.filter(([, why]) => why).map(([c]) => c.length));
484
+ for (const [i, [cmd, why]] of steps.entries()) {
485
+ if (why)
486
+ io.out(` ${st.muted(`${i + 1}.`)} ${st.bold(cmd.padEnd(w))} ${st.muted(`(${why})`)}`);
487
+ else
488
+ for (const [k, l] of (st.color ? wrap(cmd, st.width - 5) : [cmd]).entries())
489
+ io.out(` ${k ? " " : st.muted(`${i + 1}.`)} ${l}`);
490
+ }
491
+ const launcher = tryLauncher(io, plan);
492
+ if (launcher)
493
+ io.out(`\n${st.lead("next", `${st.bold("Try it:")} ${st.accent(launcher)}`)}`);
494
+ }
495
+ // Command -------------------------------------------------------------------------------------
496
+ async function run(args, io) {
497
+ const p = parseFlags(args, SPEC, 0);
498
+ const dry = bool(p, "dry-run");
499
+ const yes = bool(p, "yes");
500
+ if (bool(p, "start") && bool(p, "no-start"))
501
+ fail("--start and --no-start do not go together");
502
+ // Questions only when a person can answer and has not answered everything with --yes.
503
+ const ask = !dry && !yes && Boolean(io.ask);
504
+ const { plan, before, after } = await makePlan(args, io, ask);
505
+ const st = style(io);
506
+ const writesMcp = plan.mcp.kind === "import";
507
+ if (after === before && !writesMcp && !plan.profiles.length) {
508
+ printFound(io, plan, st);
509
+ io.out("");
510
+ io.out(st.lead("ok", "Nothing to set up: turno already knows this machine. turno doctor checks it."));
511
+ return 0;
512
+ }
513
+ printPlan(io, plan, before, after, st);
514
+ io.out("");
515
+ // Start the gateway and connect the profiles in the same run: asked in a terminal (yes by
516
+ // default), --start with --yes, never with --no-start. Both steps go in init's journal.
517
+ let start = hasServers(plan) && bool(p, "start");
518
+ if (hasServers(plan) && !bool(p, "no-start") && !bool(p, "start") && ask) {
519
+ start = await askYes(io, "Also start the gateway and connect the profiles to it (turno mcp daemon start, turno mcp sync)?");
520
+ }
521
+ if (dry) {
522
+ if (start)
523
+ io.out(st.wrap("", "Then: start the gateway as a login service and point every profile at it (turno mcp daemon start, turno mcp sync)."));
524
+ io.out(st.wrap("", `${st.lead("info", "Nothing written (dry run).")} ${st.bold(`turno init --yes${hasServers(plan) ? " --start" : ""}`)} writes all of it; one turno undo reverts it.`));
525
+ return 0;
526
+ }
527
+ // Launchers keep the path of this turno; a path into npx's cache disappears.
528
+ if (plan.profiles.length)
529
+ refuseNpx();
530
+ if (!yes) {
531
+ if (!io.ask)
532
+ needsAnswer("init");
533
+ if (!(await confirm(io, "Write all of this?"))) {
534
+ io.err("Nothing changed.");
535
+ return 1;
536
+ }
537
+ }
538
+ const env = io.env;
539
+ const started = Date.now();
540
+ const journal = new Journal(env, "init");
541
+ io.out(st.header("Write"));
542
+ // config.toml first: setting up a profile reads its agent from it.
543
+ editConfig(env, journal, (text) => (text === before ? after : editText(text, plan, env)));
544
+ io.out(` ${st.check("ok", `wrote ${tildify(paths(env).configFile, env)}`)}`);
545
+ if (plan.mcp.kind === "import") {
546
+ const spin = spinner(io, "asking npm for the command names of MCP packages");
547
+ let resolved;
548
+ try {
549
+ resolved = await resolveMcp(io, plan.mcp);
550
+ }
551
+ finally {
552
+ spin.stop();
553
+ }
554
+ journal.write(paths(env).mcpFile, resolved.toml, 0o600);
555
+ io.out(` ${st.check("ok", `wrote ${tildify(paths(env).mcpFile, env)} ${st.muted(`(${plural(plan.mcp.servers.length, "server")}, mode 600)`)}`)}`);
556
+ for (const n of resolved.notes)
557
+ io.err(st.note("warn", st.muted(n), 4));
558
+ }
559
+ // Setup lines sit under the Write header.
560
+ // Two columns narrower, so what setup wraps still fits after the indent.
561
+ const indented = { ...io, env: { ...io.env, COLUMNS: String(st.width - 2) }, out: (line = "") => io.out(line ? line.replace(/^/gm, " ") : line) };
562
+ if (plan.profiles.length)
563
+ setupProfiles(plan.profiles.map((np) => np.name), indented, { journal, brief: true });
564
+ let gatewayUp = false;
565
+ if (start) {
566
+ io.out("");
567
+ io.out(st.header("Gateway"));
568
+ const { startDaemonService } = await import("./mcpd.js");
569
+ const { syncProfiles } = await import("./mcp.js");
570
+ gatewayUp = (await startDaemonService(io, { journal })) === 0;
571
+ io.out("");
572
+ io.out(st.header("Sync"));
573
+ await syncProfiles(io, { journal });
574
+ }
575
+ io.out("");
576
+ io.out(st.wrap(st.color ? `${st.icon("ok")} ` : "ok ", `${st.bold("Done")} in ${duration(Date.now() - started)}. ${st.muted("Undo all of it with:")} ${st.bold(`turno undo ${journal.stamp}`)}`));
577
+ if (start)
578
+ io.out(st.muted(" (the gateway keeps running until turno mcp daemon stop)"));
579
+ const first = plan.profiles[0];
580
+ if (first)
581
+ warnPath(io, launcherName(first.name, first.agent));
582
+ io.out("");
583
+ printNext(io, plan, gatewayUp, st);
584
+ return 0;
585
+ }
586
+ const USAGE = `Usage: turno init [--dry-run] [--yes] [--profile <name[:agent]>]... [--skip <name>]...
587
+ [--default <profile>] [--no-mcp] [--start | --no-start]
588
+
589
+ Sets turno up in one step. It looks for installed agents, turno profiles, agent folders made by
590
+ hand (~/.claude-<name>, ~/.codex-<name>, ...), MCP servers in every agent config, and the
591
+ folders each Claude Code account was used in. Then it proposes profiles, folder rules, a default
592
+ and mcp.toml, prints the whole change, and writes it as one journal: turno undo <stamp> reverts
593
+ all of it. It never moves your own files without showing it first.
594
+
595
+ In a terminal it asks before adopting each folder, which profiles to create when there are none,
596
+ and the default; without one, --yes is required and flags give the answers.
597
+
598
+ --dry-run print the plan and the diff, write nothing
599
+ -y, --yes write without asking (adopts every folder found but those in --skip)
600
+ --profile <p[:a]> create this profile (agent claude, codex, copilot or cursor)
601
+ --skip <name> leave a found folder alone
602
+ --default <p> profile for folders without a rule
603
+ --no-mcp do not create mcp.toml
604
+ --start also start the gateway and point every profile at it (with --yes)
605
+ --no-start leave the gateway and the agent configs alone
606
+
607
+ When there are MCP servers, init in a terminal also offers to start the gateway as a login
608
+ service and point every profile at it (turno mcp daemon start, turno mcp sync), in the same
609
+ journal. With --yes it does that only with --start.`;
610
+ export const command = {
611
+ summary: "set turno up in one step: find agents, profiles, folders and MCP servers, show the diff, write it (one undo)",
612
+ usage: USAGE,
613
+ flags: flagsOf(SPEC),
614
+ run,
615
+ };
616
+ //# sourceMappingURL=init.js.map