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
@@ -0,0 +1,459 @@
1
+ /**
2
+ * Choose a profile when a command needs one and the argument is missing. A small
3
+ * picker with no dependencies: arrow keys or j/k move, typing filters, Enter chooses, Esc or
4
+ * Ctrl-C cancels. It draws on stderr and reads stdin in raw mode, only when both are terminals;
5
+ * the terminal is restored on every way out (a choice, a cancel, an error, a signal).
6
+ *
7
+ * Where nobody can answer (no terminal, --no-input, an agent session: `io.ask` is unset) the
8
+ * command fails with exit 2 and the valid values instead.
9
+ *
10
+ * The key handling is a pure state machine (`parseKeys`, `reduce`), so tests drive it without a
11
+ * terminal. Loaded lazily by the commands that use it.
12
+ */
13
+ import { Exit } from "./exit.js";
14
+ import { DEFAULT_AGENT, adapter } from "../agents/index.js";
15
+ import { loadConfig } from "../core/config.js";
16
+ import { exhaustedUntil } from "../core/exhausted.js";
17
+ import { agentOf, listProfiles } from "../core/profiles.js";
18
+ import { candidateRoots, resolveProfile } from "../core/resolve.js";
19
+ import { CliError, fail, needsAnswer } from "./io.js";
20
+ import { launcherPath } from "./launch.js";
21
+ import { profileColor, style, visibleWidth } from "./style.js";
22
+ /** Rows a page key moves. */
23
+ const PAGE = 5;
24
+ /** Items that match the query: the name first, then the other fields; case does not matter. */
25
+ export function matching(state) {
26
+ const q = state.query.trim().toLowerCase();
27
+ if (!q)
28
+ return [...state.items];
29
+ const byName = state.items.filter((i) => i.value.toLowerCase().includes(q));
30
+ const byOther = state.items.filter((i) => !byName.includes(i) && i.search.toLowerCase().includes(q));
31
+ return [...byName, ...byOther];
32
+ }
33
+ /** The first state: the cursor on `initial` when it is one of the items. */
34
+ export function initialState(items, initial) {
35
+ return {
36
+ items,
37
+ query: "",
38
+ cursor: Math.max(0, items.findIndex((i) => i.value === initial)),
39
+ };
40
+ }
41
+ /** The item under the cursor, if any matches. */
42
+ export function selected(state) {
43
+ return matching(state)[state.cursor];
44
+ }
45
+ /** The same state with new items (accounts arrived), the cursor kept on the same value. */
46
+ export function withItems(state, items) {
47
+ const value = selected(state)?.value;
48
+ const next = { ...state, items };
49
+ const idx = matching(next).findIndex((i) => i.value === value);
50
+ return { ...next, cursor: Math.max(0, idx) };
51
+ }
52
+ /** A new query: the cursor stays on the same item while it still matches, else goes to the first. */
53
+ function requery(state, query) {
54
+ const value = selected(state)?.value;
55
+ const next = { ...state, query };
56
+ const idx = matching(next).findIndex((i) => i.value === value);
57
+ return { ...next, cursor: Math.max(0, idx) };
58
+ }
59
+ /**
60
+ * One key applied to the state. j and k move while the filter is empty (once typing starts they
61
+ * are letters); arrows and Ctrl-N/Ctrl-P always move. Enter with nothing matching does nothing.
62
+ */
63
+ export function reduce(state, key) {
64
+ const n = matching(state).length;
65
+ const move = (to) => ({ state: { ...state, cursor: n ? Math.min(Math.max(to, 0), n - 1) : 0 } });
66
+ switch (key.name) {
67
+ case "up":
68
+ return move(state.cursor - 1 < 0 ? n - 1 : state.cursor - 1);
69
+ case "down":
70
+ return move(state.cursor + 1 >= n ? 0 : state.cursor + 1);
71
+ case "pageUp":
72
+ return move(state.cursor - PAGE);
73
+ case "pageDown":
74
+ return move(state.cursor + PAGE);
75
+ case "home":
76
+ return move(0);
77
+ case "end":
78
+ return move(n - 1);
79
+ case "cancel":
80
+ return { state, outcome: { kind: "cancel" } };
81
+ case "enter": {
82
+ const item = selected(state);
83
+ return item ? { state, outcome: { kind: "pick", value: item.value } } : { state };
84
+ }
85
+ case "backspace":
86
+ return { state: requery(state, [...state.query].slice(0, -1).join("")) };
87
+ case "clear":
88
+ return { state: requery(state, "") };
89
+ case "char":
90
+ if (!state.query && (key.ch === "j" || key.ch === "k"))
91
+ return reduce(state, { name: key.ch === "j" ? "down" : "up" });
92
+ if (!state.query && key.ch === " ")
93
+ return { state };
94
+ return { state: requery(state, state.query + key.ch) };
95
+ }
96
+ }
97
+ const CSI_KEYS = {
98
+ A: "up",
99
+ B: "down",
100
+ H: "home",
101
+ F: "end",
102
+ "1~": "home",
103
+ "7~": "home",
104
+ "4~": "end",
105
+ "8~": "end",
106
+ "5~": "pageUp",
107
+ "6~": "pageDown",
108
+ };
109
+ /**
110
+ * Keys in a chunk of raw terminal input. A lone Esc (no sequence after it) cancels; escape
111
+ * sequences the picker does not use are skipped whole.
112
+ */
113
+ export function parseKeys(chunk) {
114
+ const keys = [];
115
+ const chars = [...chunk];
116
+ for (let i = 0; i < chars.length; i++) {
117
+ const c = chars[i];
118
+ if (c === "\x1b") {
119
+ const next = chars[i + 1];
120
+ if (next === "[" || next === "O") {
121
+ let j = i + 2;
122
+ let params = "";
123
+ while (j < chars.length && /[0-9;]/.test(chars[j]))
124
+ params += chars[j++];
125
+ const final = chars[j] ?? "";
126
+ const name = CSI_KEYS[final === "~" ? `${params}~` : final];
127
+ if (name)
128
+ keys.push({ name });
129
+ i = j;
130
+ continue;
131
+ }
132
+ keys.push({ name: "cancel" });
133
+ // Alt+key arrives as Esc then the key: both belong to the cancel.
134
+ if (next !== undefined)
135
+ i++;
136
+ continue;
137
+ }
138
+ if (c === "\r" || c === "\n")
139
+ keys.push({ name: "enter" });
140
+ else if (c === "\x03" || c === "\x04")
141
+ keys.push({ name: "cancel" });
142
+ else if (c === "\x7f" || c === "\b")
143
+ keys.push({ name: "backspace" });
144
+ else if (c === "\x15")
145
+ keys.push({ name: "clear" });
146
+ else if (c === "\x0e")
147
+ keys.push({ name: "down" });
148
+ else if (c === "\x10")
149
+ keys.push({ name: "up" });
150
+ else if (c === "\t")
151
+ keys.push({ name: "down" });
152
+ else if (c >= " ")
153
+ keys.push({ name: "char", ch: c });
154
+ }
155
+ return keys;
156
+ }
157
+ /** The picker as lines: a title (with the filter), the matching rows, then the keys. */
158
+ export function renderPicker(state, s, opts) {
159
+ const shown = matching(state);
160
+ const ascii = s.icons === "ascii";
161
+ const pointer = ascii ? ">" : s.accent("❯");
162
+ const blank = " ".repeat(visibleWidth(pointer));
163
+ const title = `${s.accent("?")} ${s.bold(opts.title)}`;
164
+ const out = [state.query ? `${title} ${s.muted("filter")} ${state.query}${s.muted("_")}` : title];
165
+ const rows = Math.max(1, opts.maxRows);
166
+ const start = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), shown.length - rows));
167
+ const page = shown.slice(start, start + rows);
168
+ if (!shown.length)
169
+ out.push(` ${s.muted(`no profile matches "${state.query}"`)}`);
170
+ const cells = page.map((item, k) => {
171
+ const on = start + k === state.cursor;
172
+ const [name = "", ...rest] = item.cells;
173
+ return [`${on ? pointer : blank} ${name}`, ...rest.map((c) => (on ? c : s.muted(c)))];
174
+ });
175
+ // The agent column goes first on a narrow terminal, then the account; the mark stays.
176
+ out.push(...s.table(cells, { indent: 1, columns: [{}, { drop: 2 }, { drop: 1 }, {}] }));
177
+ const hidden = shown.length - page.length;
178
+ if (hidden > 0)
179
+ out.push(` ${s.muted(`${hidden} more`)}`);
180
+ const hint = ascii
181
+ ? "up/down or j/k move, type to filter, enter choose, esc cancel"
182
+ : "↑↓ or j/k move · type to filter · enter choose · esc cancel";
183
+ out.push(` ${s.muted(hint)}`);
184
+ return out;
185
+ }
186
+ const SHOW_CURSOR = "\x1b[?25h";
187
+ const HIDE_CURSOR = "\x1b[?25l";
188
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
189
+ /**
190
+ * The real terminal: raw stdin, drawing on stderr. A signal while the picker is open restores
191
+ * the terminal (raw mode off, cursor shown) and then ends the process as the signal would.
192
+ */
193
+ export function realTerminal(input = process.stdin, output = process.stderr, proc = process) {
194
+ return {
195
+ columns: () => output.columns || 80,
196
+ rows: () => output.rows || 24,
197
+ write: (text) => {
198
+ output.write(text);
199
+ },
200
+ start(onData, onResize) {
201
+ const wasRaw = Boolean(input.isRaw);
202
+ let restored = false;
203
+ const restore = () => {
204
+ if (restored)
205
+ return;
206
+ restored = true;
207
+ input.off("data", onData);
208
+ if (onResize)
209
+ output.off("resize", onResize);
210
+ for (const sig of SIGNALS)
211
+ proc.off(sig, onSignal);
212
+ proc.off("exit", restore);
213
+ try {
214
+ input.setRawMode(wasRaw);
215
+ }
216
+ catch {
217
+ /* the terminal is gone */
218
+ }
219
+ input.pause();
220
+ output.write(SHOW_CURSOR);
221
+ };
222
+ const onSignal = (sig) => {
223
+ restore();
224
+ proc.kill(proc.pid, sig);
225
+ };
226
+ for (const sig of SIGNALS)
227
+ proc.on(sig, onSignal);
228
+ proc.on("exit", restore);
229
+ try {
230
+ input.setRawMode(true);
231
+ input.setEncoding("utf8");
232
+ input.on("data", onData);
233
+ if (onResize)
234
+ output.on("resize", onResize);
235
+ input.resume();
236
+ }
237
+ catch (err) {
238
+ restore();
239
+ throw err;
240
+ }
241
+ return restore;
242
+ },
243
+ };
244
+ }
245
+ /** Physical rows `lines` take on a terminal `columns` wide (long lines wrap). */
246
+ function physicalRows(lines, columns) {
247
+ return lines.reduce((n, l) => n + Math.max(1, Math.ceil(visibleWidth(l) / Math.max(1, columns))), 0);
248
+ }
249
+ /**
250
+ * Run the picker on `term`. Resolves with the chosen value, or undefined when cancelled. The
251
+ * picker's lines are erased at the end, and the terminal is restored on every path.
252
+ */
253
+ export function runPicker(term, s, items, opts) {
254
+ return new Promise((resolve, reject) => {
255
+ let state = initialState(items, opts.initial);
256
+ let drawn = 0;
257
+ let done = false;
258
+ let stop;
259
+ const erase = () => {
260
+ if (drawn > 0)
261
+ term.write(`\r${drawn > 1 ? `\x1b[${drawn - 1}A` : ""}\x1b[J`);
262
+ drawn = 0;
263
+ };
264
+ const draw = () => {
265
+ const maxRows = Math.max(3, Math.min(opts.maxRows, term.rows() - 4));
266
+ const lines = renderPicker(state, opts.styleAt ? opts.styleAt(term.columns()) : s, { ...opts, maxRows });
267
+ erase();
268
+ term.write(lines.join("\n"));
269
+ drawn = physicalRows(lines, term.columns());
270
+ };
271
+ const finish = (err, value) => {
272
+ if (done)
273
+ return;
274
+ done = true;
275
+ try {
276
+ erase();
277
+ if (value !== undefined && opts.chosen)
278
+ term.write(`${opts.chosen(value)}\n`);
279
+ }
280
+ catch {
281
+ /* restoring matters more than the last line */
282
+ }
283
+ try {
284
+ term.write(SHOW_CURSOR);
285
+ }
286
+ catch {
287
+ /* ditto */
288
+ }
289
+ try {
290
+ stop?.();
291
+ }
292
+ catch {
293
+ /* ditto */
294
+ }
295
+ if (err)
296
+ reject(err);
297
+ else
298
+ resolve(value);
299
+ };
300
+ const onData = (chunk) => {
301
+ if (done)
302
+ return;
303
+ try {
304
+ for (const key of parseKeys(chunk)) {
305
+ const r = reduce(state, key);
306
+ state = r.state;
307
+ if (r.outcome)
308
+ return finish(undefined, r.outcome.kind === "pick" ? r.outcome.value : undefined);
309
+ }
310
+ draw();
311
+ }
312
+ catch (err) {
313
+ finish(err);
314
+ }
315
+ };
316
+ const redraw = () => {
317
+ if (done)
318
+ return;
319
+ try {
320
+ draw();
321
+ }
322
+ catch (err) {
323
+ finish(err);
324
+ }
325
+ };
326
+ try {
327
+ term.write(HIDE_CURSOR);
328
+ stop = term.start(onData, redraw);
329
+ draw();
330
+ }
331
+ catch (err) {
332
+ finish(err);
333
+ return;
334
+ }
335
+ opts.update?.then((next) => {
336
+ if (done)
337
+ return;
338
+ state = withItems(state, next);
339
+ redraw();
340
+ }, () => {
341
+ /* keep the first items */
342
+ });
343
+ });
344
+ }
345
+ /** "alice@example.com", "not logged in", or the launcher of an agent without account details. */
346
+ async function accountText(name, agent, env) {
347
+ if (!launcherPath(name, env, agent))
348
+ return { text: "not set up", warn: true };
349
+ // turno reads no account for these agents (Codex, Copilot, Cursor).
350
+ if (!adapter(agent).accountDetails)
351
+ return { text: "-", warn: false };
352
+ const { authStatus } = await import("./commands/usage.js");
353
+ const s = await authStatus(name, env);
354
+ if (!s)
355
+ return { text: "account unknown", warn: true };
356
+ return s.loggedIn ? { text: s.email || "logged in", warn: false } : { text: "not logged in", warn: true };
357
+ }
358
+ /**
359
+ * The profile a command needs, chosen by a person. Without anyone to answer it fails with exit
360
+ * 2 and the valid values; a cancel fails with exit 130 and nothing changed.
361
+ */
362
+ export async function pickProfile(io, opts) {
363
+ const config = loadConfig(io.env);
364
+ const names = listProfiles(config, io.env, opts.agent);
365
+ if (!names.length)
366
+ return fail(`no profiles yet${opts.agent && opts.agent !== DEFAULT_AGENT ? ` for ${adapter(opts.agent).label}` : ""}; create one with turno profile add <name>`);
367
+ if (!io.ask)
368
+ return needsAnswer(opts.command, `a profile: ${[...names, ...(opts.extra ?? [])].join(", ")}`);
369
+ const dir = opts.dir ?? process.cwd();
370
+ const roots = candidateRoots(dir);
371
+ const agents = [...new Set(names.map((n) => agentOf(n, config)))];
372
+ const here = new Map();
373
+ for (const agent of agents) {
374
+ const chosen = resolveProfile(dir, config, io.env, roots, agent).chosen;
375
+ if (chosen)
376
+ here.set(chosen, true);
377
+ }
378
+ const folderPick = names.find((n) => here.has(n) && agentOf(n, config) === DEFAULT_AGENT) ?? names.find((n) => here.has(n));
379
+ // What `turno auto` would open here (Claude Code, as `turno run auto` does).
380
+ const auto = opts.auto ? resolveProfile(dir, config, io.env, roots, DEFAULT_AGENT) : undefined;
381
+ const autoTo = auto?.chosen && names.includes(auto.chosen) ? auto.chosen : undefined;
382
+ const initial = opts.initial && names.includes(opts.initial) ? opts.initial : autoTo ? "auto" : folderPick;
383
+ const term = io.terminal ?? (process.stdin.isTTY && process.stderr.isTTY ? realTerminal() : undefined);
384
+ const styleAt = (columns) => style({ env: { ...io.env, COLUMNS: String(columns) }, isTty: true });
385
+ const s = term ? styleAt(term.columns()) : style({ env: io.env, isTty: Boolean(process.stderr.isTTY) });
386
+ const pill = (n) => s.profile(n, profileColor(config.profiles, n));
387
+ const now = Date.now() / 1000;
388
+ const mark = (n) => {
389
+ const parts = [];
390
+ if (here.has(n))
391
+ parts.push(s.lead("on", "this folder"));
392
+ if (opts.marks?.[n])
393
+ parts.push(opts.marks[n]);
394
+ const until = exhaustedUntil(n, io.env);
395
+ if (until !== undefined && until > now)
396
+ parts.push(s.warn("exhausted"));
397
+ return parts.join(s.muted(" · "));
398
+ };
399
+ const item = (n, account) => {
400
+ const agent = adapter(agentOf(n, config));
401
+ const acc = account ? (account.warn ? s.warn(account.text) : account.text) : s.muted("...");
402
+ return { value: n, cells: [pill(n), agent.label, acc, mark(n)], search: `${agent.label} ${account?.text ?? ""}` };
403
+ };
404
+ const autoName = (st) => `${st.bold("auto")} ${st.muted("(")}${autoTo}${st.muted(")")}`;
405
+ const first = autoTo
406
+ ? [
407
+ {
408
+ value: "auto",
409
+ cells: [
410
+ autoName(s),
411
+ adapter(DEFAULT_AGENT).label,
412
+ s.muted(auto.reason),
413
+ auto.note ? s.warn(`${auto.assigned} ${auto.note}`) : "",
414
+ ],
415
+ search: `auto ${autoTo}`,
416
+ },
417
+ ]
418
+ : [];
419
+ const withAccounts = Promise.all(names.map(async (n) => item(n, await accountText(n, agentOf(n, config), io.env)))).then((items) => [...first, ...items]);
420
+ let value;
421
+ if (term) {
422
+ value = await runPicker(term, s, [...first, ...names.map((n) => item(n))], {
423
+ title: opts.title,
424
+ maxRows: 10,
425
+ ...(initial ? { initial } : {}),
426
+ update: withAccounts,
427
+ styleAt,
428
+ chosen: (v) => `${s.icon("ok")} ${opts.title} ${v === "auto" && autoTo ? autoName(s) : pill(v)}`,
429
+ });
430
+ }
431
+ else {
432
+ value = await askByNumber(io, s, await withAccounts, opts.title, initial);
433
+ }
434
+ if (value === undefined)
435
+ throw new CliError("cancelled; nothing changed", Exit.cancelled);
436
+ return value;
437
+ }
438
+ /**
439
+ * The picker as a numbered question, for a person who can answer but not on a raw terminal
440
+ * (an `ask` without a TTY on stdin): a number, a name, or Enter for the marked one.
441
+ */
442
+ async function askByNumber(io, s, items, title, initial) {
443
+ io.err(`${s.accent("?")} ${s.bold(title)}`);
444
+ const rows = items.map((it, i) => [s.muted(String(i + 1)), ...it.cells]);
445
+ for (const line of s.table(rows, { columns: [{ align: "right" }] }))
446
+ io.err(line);
447
+ const def = initial ? items.findIndex((i) => i.value === initial) + 1 : 0;
448
+ const answer = (await io.ask(`Number or name${def ? ` [${def}]` : ""}: `)).trim();
449
+ if (!answer)
450
+ return def ? items[def - 1].value : undefined;
451
+ const n = Number(answer);
452
+ if (Number.isInteger(n) && n >= 1 && n <= items.length)
453
+ return items[n - 1].value;
454
+ const named = items.find((i) => i.value === answer);
455
+ if (named)
456
+ return named.value;
457
+ return fail(`no profile '${answer}'; pass a profile: ${items.map((i) => i.value).join(", ")}`);
458
+ }
459
+ //# sourceMappingURL=picker.js.map
@@ -3,13 +3,49 @@
3
3
  * the MCP SDK. Order and section decide `turno help`.
4
4
  */
5
5
  export const SECTIONS = [
6
+ { title: "Get started", commands: ["init", "demo"] },
6
7
  { title: "Start an agent", commands: ["run", "auto"] },
7
8
  { title: "Accounts", commands: ["profile", "limit", "session", "open"] },
8
- { title: "MCP servers and outside services", commands: ["mcp", "identity", "secret", "browser"] },
9
+ { title: "MCP servers and outside services", commands: ["mcp", "identity", "secret"] },
9
10
  { title: "Look", commands: ["ui"] },
10
- { title: "Maintenance", commands: ["status", "doctor", "config", "undo", "upgrade", "version", "completion", "migrate"] },
11
+ {
12
+ title: "Maintenance",
13
+ commands: ["status", "doctor", "config", "undo", "upgrade", "uninstall", "version", "completion"],
14
+ },
15
+ { title: "Developer tools", commands: ["browser"] },
11
16
  ];
17
+ /**
18
+ * One line per visible command for `turno help`, so the help renders from this table without
19
+ * loading any command module. Each must equal the command's own `summary` (a test checks it).
20
+ */
21
+ export const HELP_SUMMARY = {
22
+ init: "set turno up in one step: find agents, profiles, folders and MCP servers, show the diff, write it (one undo)",
23
+ demo: "try turno in a throwaway HOME: two profiles, a gateway and the status line (removed on exit)",
24
+ run: "open a profile with its agent (turno <profile> is the short form), or auto",
25
+ auto: "open the agent with the account assigned to this folder (turno-auto)",
26
+ profile: "accounts (profiles) for each agent: list, add, repair, remove, and which folders use each",
27
+ limit: "usage limits of each account, and the exhausted marks that move projects to the fallback",
28
+ session: "live Claude Code sessions, and moving one to another account",
29
+ open: "open a claude.ai link with an account (default: the session's)",
30
+ mcp: "MCP servers behind the lazy gateway, and the gateway daemon itself",
31
+ identity: "who acts on outside services: service accounts (linear:work) and browser identities (browser:school)",
32
+ secret: "store MCP secrets in the Keychain (macOS) or the Secret Service (Linux)",
33
+ ui: "the status line, its font and icons in every terminal",
34
+ status: "one screen with everything: this folder, profiles and usage, sessions, mcpd and the look",
35
+ doctor: "check everything (system, config, profiles, MCP, look, mcpd) and fix what is safe to fix",
36
+ config: "read and change config.toml without losing its comments; check every config file",
37
+ undo: "list recent changes turno made to your files, and put any of them back",
38
+ upgrade: "update turno to the newest release (or check for one)",
39
+ uninstall: "remove the service, launchers, status line and MCP entries turno set up (profile folders stay)",
40
+ version: "the turno version, how it was installed, and whether a newer one is known",
41
+ completion: "shell completion for commands, profiles, identities and config keys",
42
+ browser: "developer tool: compare browser engines (needs turno-browser)",
43
+ };
44
+ /** `turno help <topic>` (cli/topics.ts), listed here so `turno help` loads nothing. */
45
+ export const HELP_TOPICS = ["environment", "exit-codes", "json"];
12
46
  export const COMMANDS = {
47
+ init: () => import("./commands/init.js"),
48
+ demo: () => import("./commands/demo.js"),
13
49
  run: () => import("./commands/run.js"),
14
50
  auto: () => import("./commands/auto.js"),
15
51
  profile: () => import("./commands/profile.js"),
@@ -26,8 +62,10 @@ export const COMMANDS = {
26
62
  config: () => import("./commands/config.js"),
27
63
  undo: () => import("./commands/undo.js"),
28
64
  upgrade: () => import("./commands/upgrade.js"),
65
+ uninstall: () => import("./commands/uninstall.js"),
29
66
  version: () => import("./commands/version.js"),
30
67
  completion: () => import("./commands/completion.js"),
68
+ // Kept for people coming from the bash tool; not in the help.
31
69
  migrate: () => import("./commands/migrate.js"),
32
70
  // Called by Claude Code, hooks, launchers and the LaunchAgent; not in the help.
33
71
  statusline: () => import("./commands/statusline.js"),
@@ -39,9 +77,9 @@ export const COMMANDS = {
39
77
  };
40
78
  /**
41
79
  * Earlier names: the 0.1 commands and the Spanish words of the bash script. They keep
42
- * working so hooks, Orca, skills and muscle memory do not break; the help shows the new ones.
80
+ * working so hooks, editors, skills and muscle memory do not break; the help shows the new ones.
43
81
  */
44
- export const ALIASES = {
82
+ const ALIASES = {
45
83
  which: ["profile", "which"],
46
84
  setup: ["profile", "repair"],
47
85
  sessions: ["session", "list"],
@@ -60,12 +98,25 @@ export const ALIASES = {
60
98
  abrir: ["open"],
61
99
  "sync-mcp": ["mcp", "sync"],
62
100
  };
63
- export const ALIAS_FLAGS = {
101
+ const ALIAS_FLAGS = {
64
102
  uso: { "--vigilar": "--watch" },
65
103
  agotada: { hasta: "until" },
66
104
  };
67
105
  /** Commands that run on every prompt or launch: no update notice, no extra work. */
68
- export const QUIET = new Set(["run", "auto", "open", "statusline", "hook", "resolve", "mcpd", "__complete", "__update-check", "completion", "upgrade", "version"]);
106
+ export const QUIET = new Set([
107
+ "run",
108
+ "auto",
109
+ "open",
110
+ "statusline",
111
+ "hook",
112
+ "resolve",
113
+ "mcpd",
114
+ "__complete",
115
+ "__update-check",
116
+ "completion",
117
+ "upgrade",
118
+ "version",
119
+ ]);
69
120
  /** Expand an alias: the command name and the arguments it stands for. */
70
121
  export function expand(first, rest) {
71
122
  const alias = ALIASES[first];
@@ -74,4 +125,8 @@ export function expand(first, rest) {
74
125
  const flags = ALIAS_FLAGS[first] ?? {};
75
126
  return [alias[0], [...alias.slice(1), ...rest.map((a) => flags[a] ?? a)]];
76
127
  }
128
+ /** Every visible command name, for suggestions after a typo. */
129
+ export function visibleCommands() {
130
+ return SECTIONS.flatMap((s) => s.commands);
131
+ }
77
132
  //# sourceMappingURL=registry.js.map
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Safe mode: `turno run <profile> --no-gateway`, `turno auto --no-gateway` or TURNO_SAFE=1.
3
+ * The agent opens with the profile's account, as its launcher would set it up, but without the
4
+ * gateway: no mcpd entries, no gateway token, no session headers, and (Claude Code) no status
5
+ * line. When a problem goes away in safe mode, it comes from turno's gateway or status line;
6
+ * when it stays, it does not. How each agent leaves the entries out is in docs/agents.md.
7
+ */
8
+ import { existsSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { adapter, agentProfileDir } from "../agents/index.js";
11
+ import { ensurePrivateDir, paths, tildify } from "../core/paths.js";
12
+ import { Exit } from "./exit.js";
13
+ import { CliError } from "./io.js";
14
+ import { execLauncher } from "./launch.js";
15
+ import { findOnPath, launcherBrowser } from "./launchers.js";
16
+ /** The flag that asks for safe mode, taken out of the agent's arguments. */
17
+ const SAFE_FLAG = "--no-gateway";
18
+ /** `--no-gateway` out of the arguments (only turno's, before a `--`), and whether it was there. */
19
+ export function takeSafeFlag(args) {
20
+ const end = args.indexOf("--");
21
+ const head = end < 0 ? [...args] : args.slice(0, end);
22
+ const tail = end < 0 ? [] : args.slice(end);
23
+ const kept = head.filter((a) => a !== SAFE_FLAG);
24
+ return { args: [...kept, ...tail], safe: kept.length !== head.length };
25
+ }
26
+ /** Variables a launcher sets for the gateway, which safe mode leaves out. */
27
+ const GATEWAY_VARS = ["TURNO_MCPD_TOKEN", "TURNO_SESSION_PID", "TURNO_SESSION_CWD_B64"];
28
+ /**
29
+ * The safe-mode arguments of an agent for the MCP file it reads (a profile's or the hub's): the
30
+ * adapter's `safeMode` (src/agents), with a private scratch file under the state folder.
31
+ */
32
+ export function safePlan(agent, file, cwd, env, key) {
33
+ const dir = ensurePrivateDir(join(paths(env).state, "safe"), env);
34
+ return adapter(agent).safeMode({ file, cwd, env, scratch: join(dir, `${key}.mcp.json`) });
35
+ }
36
+ /**
37
+ * The environment a launcher gives `profile`, without the gateway variables, and with
38
+ * TURNO_SAFE=1 so a turno the agent runs stays in safe mode. Without a profile: the plain agent.
39
+ */
40
+ export function safeEnv(agent, profile, env, platform = process.platform) {
41
+ const a = adapter(agent);
42
+ const out = { ...env, TURNO_SAFE: "1" };
43
+ for (const v of GATEWAY_VARS)
44
+ delete out[v];
45
+ if (!profile)
46
+ return out;
47
+ out[a.homeEnv] = agentProfileDir(profile, agent, env);
48
+ out.TURNO_PROFILE = profile;
49
+ if (!a.classicLauncher)
50
+ out.TURNO_AGENT = agent;
51
+ Object.assign(out, a.launcherEnv);
52
+ const browser = launcherBrowser(env, platform);
53
+ if (browser)
54
+ out.BROWSER = browser;
55
+ return out;
56
+ }
57
+ /**
58
+ * Open `profile` (or the plain agent) in safe mode: the agent's own command with the profile's
59
+ * environment, never the launcher, which would export the gateway token. The run record is
60
+ * written as the launcher writes it, so turno sessions still knows the account.
61
+ */
62
+ export async function launchSafe(agent, profile, args, io, cwd = process.cwd()) {
63
+ const a = adapter(agent);
64
+ const bin = findOnPath(a.command, io.env);
65
+ if (!bin)
66
+ throw new CliError(`${a.command} is not installed (${a.install})`, Exit.notInstalled);
67
+ if (profile && !existsSync(agentProfileDir(profile, agent, io.env))) {
68
+ throw new CliError(`profile ${profile} has no folder (${tildify(agentProfileDir(profile, agent, io.env), io.env)}). Run: turno profile repair ${profile}`);
69
+ }
70
+ const configFile = profile ? a.mcp.file(agentProfileDir(profile, agent, io.env), io.env) : a.mcp.hubFile(io.env);
71
+ const plan = safePlan(agent, configFile, cwd, io.env, profile ?? `plain-${agent}`);
72
+ io.err(`turno: safe mode, ${profile ? `profile ${profile}` : `plain ${a.command}`} without the gateway (${SAFE_FLAG} or TURNO_SAFE=1)`);
73
+ for (const n of plan.notes)
74
+ io.err(` ${n}`);
75
+ // execve keeps this PID, as the launcher's exec does; a child process would have another.
76
+ if (profile && typeof process.execve === "function") {
77
+ try {
78
+ const run = ensurePrivateDir(paths(io.env).runDir, io.env);
79
+ writeFileSync(join(run, String(process.pid)), `${profile}\n`);
80
+ }
81
+ catch {
82
+ /* turno sessions shows it as unknown */
83
+ }
84
+ }
85
+ return execLauncher(bin, [...plan.args, ...args], safeEnv(agent, profile, io.env));
86
+ }
87
+ //# sourceMappingURL=safe.js.map