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,236 @@
1
+ /**
2
+ * Syntax highlighting for what turno shows in a terminal: TOML (config.toml, mcp.toml and their
3
+ * diffs) and JSON (`--json` output, agent config snippets). Both work line by line on the text as
4
+ * it is, never reformat it, and only add ANSI color codes: removing them gives back the input.
5
+ * Callers decide whether to color (see `colors` in io.ts).
6
+ */
7
+ const RESET = "\x1b[0m";
8
+ /** SGR codes. Magenta reads well on dark and light backgrounds, unlike bright yellow or blue. */
9
+ const STYLE = {
10
+ header: "1",
11
+ key: "36",
12
+ string: "32",
13
+ literal: "35",
14
+ comment: "2",
15
+ secret: "33",
16
+ };
17
+ function render(tokens) {
18
+ let out = "";
19
+ for (const t of tokens) {
20
+ if (!t.text)
21
+ continue;
22
+ out += t.kind === "plain" ? t.text : `\x1b[${STYLE[t.kind]}m${t.text}${RESET}`;
23
+ }
24
+ return out;
25
+ }
26
+ /** The trailing comment `turno mcp import` adds to a preview line whose value it masked. */
27
+ const SECRET_MARK = /^#\s*secret, hidden\s*$/;
28
+ // TOML ----------------------------------------------------------------------------------------
29
+ const BARE = "[A-Za-z0-9_-]+";
30
+ const BASIC = '"(?:[^"\\\\]|\\\\.)*"';
31
+ const LITERAL = "'[^']*'";
32
+ const SIMPLE = `(?:${BARE}|${BASIC}|${LITERAL})`;
33
+ const KEY_PATH = `${SIMPLE}(?:[ \\t]*\\.[ \\t]*${SIMPLE})*`;
34
+ /** A key (dotted or quoted) followed by `=`, at the start of what is left of the line. */
35
+ const KEY = new RegExp(`^${KEY_PATH}(?=[ \\t]*=)`);
36
+ /** `[table]` or `[[array.of.tables]]`, possibly indented, with only a comment after it. */
37
+ const HEADER = new RegExp(`^([ \\t]*)(\\[\\[?[ \\t]*${KEY_PATH}[ \\t]*\\]\\]?)(?=[ \\t]*(?:#.*)?$)`);
38
+ /** Numbers, booleans, dates and times, inf and nan: anything bare in a value position. */
39
+ const WORD = /^[A-Za-z0-9_+\-.:]+/;
40
+ export function tomlState() {
41
+ return { stack: [] };
42
+ }
43
+ /** Where a multi-line string that starts at `from` ends (index after the delimiter), or -1. */
44
+ function closeMultiline(line, from, delim) {
45
+ let i = from;
46
+ while (i < line.length) {
47
+ if (delim === '"""' && line[i] === "\\") {
48
+ i += 2;
49
+ continue;
50
+ }
51
+ if (line.startsWith(delim, i)) {
52
+ // A closing delimiter may carry up to two more quotes that belong to the string.
53
+ let end = i + 3;
54
+ while (end < line.length && end - i < 5 && line[end] === delim[0])
55
+ end++;
56
+ return end;
57
+ }
58
+ i++;
59
+ }
60
+ return -1;
61
+ }
62
+ /** Where a single-line string that starts at `from` (on its quote) ends, or the line end. */
63
+ function closeString(line, from) {
64
+ const quote = line[from];
65
+ let i = from + 1;
66
+ while (i < line.length) {
67
+ if (quote === '"' && line[i] === "\\") {
68
+ i += 2;
69
+ continue;
70
+ }
71
+ if (line[i] === quote)
72
+ return i + 1;
73
+ i++;
74
+ }
75
+ return line.length;
76
+ }
77
+ function tomlTokens(line, state) {
78
+ const tokens = [];
79
+ const push = (text, kind) => tokens.push({ text, kind });
80
+ let i = 0;
81
+ if (state.multiline) {
82
+ const end = closeMultiline(line, 0, state.multiline);
83
+ if (end < 0) {
84
+ push(line, "string");
85
+ return tokens;
86
+ }
87
+ push(line.slice(0, end), "string");
88
+ state.multiline = undefined;
89
+ i = end;
90
+ }
91
+ else if (!state.stack.length) {
92
+ const h = HEADER.exec(line);
93
+ if (h) {
94
+ push(h[1], "plain");
95
+ push(h[2], "header");
96
+ i = h[0].length;
97
+ }
98
+ }
99
+ // A key can start the line (outside arrays) and follow `{` or `,` inside an inline table.
100
+ let expectKey = i === 0 && !state.stack.length && !tokens.length;
101
+ while (i < line.length) {
102
+ const rest = line.slice(i);
103
+ const ch = line[i];
104
+ if (ch === " " || ch === "\t") {
105
+ const ws = /^[ \t]+/.exec(rest)[0];
106
+ push(ws, "plain");
107
+ i += ws.length;
108
+ continue;
109
+ }
110
+ if (expectKey) {
111
+ expectKey = false;
112
+ const k = KEY.exec(rest);
113
+ if (k) {
114
+ push(k[0], "key");
115
+ i += k[0].length;
116
+ continue;
117
+ }
118
+ }
119
+ if (ch === "#") {
120
+ push(rest, "comment");
121
+ break;
122
+ }
123
+ if (rest.startsWith('"""') || rest.startsWith("'''")) {
124
+ const delim = rest.slice(0, 3);
125
+ const end = closeMultiline(line, i + 3, delim);
126
+ if (end < 0) {
127
+ push(rest, "string");
128
+ state.multiline = delim;
129
+ break;
130
+ }
131
+ push(line.slice(i, end), "string");
132
+ i = end;
133
+ continue;
134
+ }
135
+ if (ch === '"' || ch === "'") {
136
+ const end = closeString(line, i);
137
+ push(line.slice(i, end), "string");
138
+ i = end;
139
+ continue;
140
+ }
141
+ if (ch === "[" || ch === "{") {
142
+ state.stack.push(ch);
143
+ push(ch, "plain");
144
+ expectKey = ch === "{";
145
+ i++;
146
+ continue;
147
+ }
148
+ if (ch === "]" || ch === "}") {
149
+ if (state.stack.at(-1) === (ch === "]" ? "[" : "{"))
150
+ state.stack.pop();
151
+ push(ch, "plain");
152
+ i++;
153
+ continue;
154
+ }
155
+ if (ch === ",") {
156
+ expectKey = state.stack.at(-1) === "{";
157
+ push(ch, "plain");
158
+ i++;
159
+ continue;
160
+ }
161
+ const w = WORD.exec(rest);
162
+ if (w) {
163
+ push(w[0], /^(?:true|false|[+-]?(?:inf|nan)|[+-]?[0-9][A-Za-z0-9_+\-.:]*)$/.test(w[0]) ? "literal" : "plain");
164
+ i += w[0].length;
165
+ continue;
166
+ }
167
+ push(ch, "plain");
168
+ i++;
169
+ }
170
+ return markSecrets(tokens);
171
+ }
172
+ /** On a line marked `# secret, hidden`, the masked value (and the mark) stand out. */
173
+ function markSecrets(tokens) {
174
+ const last = tokens.at(-1);
175
+ if (last?.kind !== "comment" || !SECRET_MARK.test(last.text))
176
+ return tokens;
177
+ const strings = tokens.filter((t) => t.kind === "string");
178
+ const masked = strings.filter((t) => t.text.includes("****"));
179
+ for (const t of masked.length ? masked : strings)
180
+ t.kind = "secret";
181
+ last.kind = "secret";
182
+ return tokens;
183
+ }
184
+ /** One TOML line, colored; `state` carries open arrays and strings to the next line. */
185
+ export function highlightTomlLine(line, state) {
186
+ return render(tomlTokens(line, state));
187
+ }
188
+ /** A TOML text, colored line by line. */
189
+ export function highlightToml(text) {
190
+ const state = tomlState();
191
+ return text
192
+ .split("\n")
193
+ .map((l) => highlightTomlLine(l, state))
194
+ .join("\n");
195
+ }
196
+ // JSON ----------------------------------------------------------------------------------------
197
+ const JSON_LITERAL = /^(?:-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null)/;
198
+ /** A JSON text, colored: keys, strings, and numbers with true, false and null. */
199
+ export function highlightJson(text) {
200
+ const tokens = [];
201
+ let i = 0;
202
+ let plain = "";
203
+ const flush = () => {
204
+ if (plain)
205
+ tokens.push({ text: plain, kind: "plain" });
206
+ plain = "";
207
+ };
208
+ while (i < text.length) {
209
+ const ch = text[i];
210
+ if (ch === '"') {
211
+ let end = i + 1;
212
+ while (end < text.length && text[end] !== '"' && text[end] !== "\n")
213
+ end += text[end] === "\\" ? 2 : 1;
214
+ if (text[end] === '"')
215
+ end++;
216
+ const after = /^\s*/.exec(text.slice(end))[0];
217
+ flush();
218
+ tokens.push({ text: text.slice(i, end), kind: text[end + after.length] === ":" ? "key" : "string" });
219
+ i = end;
220
+ continue;
221
+ }
222
+ const prev = text[i - 1];
223
+ const lit = prev === undefined || !/[A-Za-z0-9_.]/.test(prev) ? JSON_LITERAL.exec(text.slice(i)) : null;
224
+ if (lit) {
225
+ flush();
226
+ tokens.push({ text: lit[0], kind: "literal" });
227
+ i += lit[0].length;
228
+ continue;
229
+ }
230
+ plain += ch;
231
+ i++;
232
+ }
233
+ flush();
234
+ return render(tokens);
235
+ }
236
+ //# sourceMappingURL=highlight.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The next step after a command that writes: one `Next: ...` line, so a person knows what to run
3
+ * after `profile add`, `mcp import --write` and the like. `hints = false` in config.toml turns
4
+ * them off; they are never printed under --json, where stdout is data.
5
+ */
6
+ import { loadConfig } from "../core/config.js";
7
+ /** Whether hints are on: config.toml's `hints`, true when the file is missing or does not parse. */
8
+ function hintsOn(env) {
9
+ try {
10
+ return loadConfig(env).hints;
11
+ }
12
+ catch {
13
+ return true;
14
+ }
15
+ }
16
+ /**
17
+ * Print `Next: <steps joined by "; ">`. `stream: "err"` keeps stdout clean for commands whose
18
+ * stdout is a file (`turno mcp export > file.toml`).
19
+ */
20
+ export function nextStep(io, steps, opts = {}) {
21
+ const list = (typeof steps === "string" ? [steps] : steps).filter(Boolean);
22
+ if (!list.length || opts.json || !hintsOn(io.env))
23
+ return;
24
+ const line = `Next: ${list.join("; ")}`;
25
+ if (opts.stream === "err")
26
+ io.err(line);
27
+ else
28
+ io.out(line);
29
+ }
30
+ //# sourceMappingURL=hints.js.map
package/dist/cli/io.js CHANGED
@@ -1,22 +1,207 @@
1
1
  /** Small helpers shared by command modules. Keep this file free of heavy imports. */
2
+ import { Exit } from "./exit.js";
3
+ /** A wrong command line: main prints `turno: <message>` and exits 2 (Exit.usage). */
2
4
  export class UsageError extends Error {
3
5
  constructor(message) {
4
6
  super(message);
5
7
  this.name = "UsageError";
6
8
  }
7
9
  }
10
+ /** A plain error with its exit code (see exit.ts): main prints `turno: <message>` and returns `code`. */
11
+ export class CliError extends Error {
12
+ code;
13
+ constructor(message, code = Exit.failure) {
14
+ super(message);
15
+ this.code = code;
16
+ this.name = "CliError";
17
+ }
18
+ }
19
+ async function askStdin(question) {
20
+ const { createInterface } = await import("node:readline/promises");
21
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
22
+ try {
23
+ return await rl.question(question);
24
+ }
25
+ finally {
26
+ rl.close();
27
+ }
28
+ }
8
29
  export function defaultIo() {
9
30
  return {
10
31
  out: (line = "") => process.stdout.write(`${line}\n`),
11
32
  err: (line = "") => process.stderr.write(`${line}\n`),
12
33
  env: process.env,
13
34
  isTty: Boolean(process.stdout.isTTY),
35
+ ...(process.stdin.isTTY && process.stderr.isTTY && !noInputReason(process.env) ? { ask: askStdin } : {}),
14
36
  };
15
37
  }
38
+ /**
39
+ * The variables each coding agent sets for the commands it runs, by agent id: inside them nobody
40
+ * reads a question, so turno never asks one. Kept here rather than in
41
+ * the adapters because every run loads io.ts and it stays free of heavy imports; a test keeps the
42
+ * ids in step with src/agents.
43
+ */
44
+ export const AGENT_SESSION_ENV = {
45
+ claude: ["CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION"],
46
+ codex: ["CODEX_THREAD_ID", "CODEX_SANDBOX"],
47
+ copilot: ["COPILOT_CLI", "COPILOT_AGENT_SESSION_ID"],
48
+ cursor: ["CURSOR_AGENT"],
49
+ };
50
+ const on = (v) => v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
51
+ /**
52
+ * The variable that keeps turno from asking anything here (TURNO_NO_INPUT, or an agent's), or
53
+ * undefined when a person may answer on a terminal. TURNO_NO_INPUT=1 (or --no-input) turns
54
+ * questions off; TURNO_NO_INPUT=0 allows them inside an agent session, for a person in an
55
+ * editor terminal that sets an agent variable.
56
+ */
57
+ export function noInputReason(env) {
58
+ const own = env.TURNO_NO_INPUT;
59
+ if (own !== undefined && own !== "")
60
+ return on(own) ? "TURNO_NO_INPUT" : undefined;
61
+ return Object.values(AGENT_SESSION_ENV)
62
+ .flat()
63
+ .find((name) => on(env[name]));
64
+ }
65
+ /** The same Io without a way to ask. */
66
+ export function withoutAsk(io) {
67
+ const { ask: _ask, ...rest } = io;
68
+ return rest;
69
+ }
70
+ /**
71
+ * A question nobody can answer here (no terminal, --no-input, an agent session): exit 2 and
72
+ * name the flag that answers it, the same way for every command.
73
+ */
74
+ export function needsAnswer(what, flag = "--yes") {
75
+ throw new UsageError(`${what} needs an answer; pass ${flag} (or run it in a terminal)`);
76
+ }
77
+ /** Ask a yes/no question; false without a person to answer. */
78
+ export async function confirm(io, question) {
79
+ if (!io.ask)
80
+ return false;
81
+ const answer = (await io.ask(`${question} [y/N] `)).trim().toLowerCase();
82
+ return answer === "y" || answer === "yes";
83
+ }
84
+ const COLOR_MODES = ["auto", "always", "never"];
85
+ export function isColorMode(v) {
86
+ return v !== undefined && COLOR_MODES.includes(v);
87
+ }
88
+ /**
89
+ * Whether output gets ANSI colors. The first rule that applies wins:
90
+ *
91
+ * 1. `--color always|never` on the command line;
92
+ * 2. TURNO_COLOR=always|never (any other value counts as auto; --color auto sets it aside);
93
+ * 3. NO_COLOR set and not empty: off (https://no-color.org, which lets a flag or a tool's own
94
+ * setting override it);
95
+ * 4. FORCE_COLOR: 0 or false turns colors off, anything else turns them on, also in a pipe;
96
+ * 5. CLICOLOR_FORCE set and not 0: on, also in a pipe (https://bixense.com/clicolors);
97
+ * 6. CLICOLOR=0, or TERM=dumb: off;
98
+ * 7. auto: on when output is a terminal.
99
+ *
100
+ * `--json` output is never colored outside a terminal, whatever this says (output.ts).
101
+ */
102
+ export function colors(io) {
103
+ // An explicit --color auto also sets TURNO_COLOR aside.
104
+ const own = io.color ?? io.env.TURNO_COLOR;
105
+ if (own === "always")
106
+ return true;
107
+ if (own === "never")
108
+ return false;
109
+ const env = io.env;
110
+ if (env.NO_COLOR)
111
+ return false;
112
+ const force = env.FORCE_COLOR;
113
+ if (force !== undefined && force !== "")
114
+ return force !== "0" && force !== "false";
115
+ if (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")
116
+ return true;
117
+ if (env.CLICOLOR === "0" || env.TERM === "dumb")
118
+ return false;
119
+ return io.isTty;
120
+ }
16
121
  export function paint(io, text, code) {
17
- return io.isTty && !io.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : text;
122
+ return colors(io) ? `\x1b[${code}m${text}\x1b[0m` : text;
18
123
  }
19
124
  export function fail(message) {
20
125
  throw new UsageError(message);
21
126
  }
127
+ /** "1 project", "2 projects". */
128
+ export function plural(n, word, many = `${word}s`) {
129
+ return `${n} ${n === 1 ? word : many}`;
130
+ }
131
+ /** Help text width. */
132
+ const WIDTH = 80;
133
+ /** Break `text` into lines of at most `width` columns at spaces (a longer word stays whole). */
134
+ export function wrap(text, width) {
135
+ const lines = [];
136
+ let line = "";
137
+ for (const word of text.split(/\s+/).filter(Boolean)) {
138
+ if (line && line.length + 1 + word.length > width) {
139
+ lines.push(line);
140
+ line = word;
141
+ }
142
+ else
143
+ line = line ? `${line} ${word}` : word;
144
+ }
145
+ if (line)
146
+ lines.push(line);
147
+ return lines.length ? lines : [""];
148
+ }
149
+ /**
150
+ * Two-column rows (` left summary`) within WIDTH columns: summaries wrap under their
151
+ * column, and a left side too wide for the column goes on its own line.
152
+ */
153
+ export function columns(rows, indent = 2, maxLeft = 32, left) {
154
+ const fit = rows.map(([l]) => l.length).filter((n) => n <= maxLeft);
155
+ const w = left ?? Math.max(0, ...fit);
156
+ const pad = " ".repeat(indent);
157
+ const out = [];
158
+ for (const [left, summary] of rows) {
159
+ const col = indent + w + 2;
160
+ const body = wrap(summary, Math.max(20, WIDTH - col));
161
+ if (left.length > w) {
162
+ const [first, ...more] = wrap(left, WIDTH - indent - 4);
163
+ out.push(`${pad}${first}`);
164
+ for (const l of more)
165
+ out.push(`${pad} ${l}`);
166
+ for (const l of body)
167
+ out.push(`${" ".repeat(col)}${l}`);
168
+ continue;
169
+ }
170
+ out.push(`${pad}${left.padEnd(w)} ${body[0]}`);
171
+ for (const l of body.slice(1))
172
+ out.push(`${" ".repeat(col)}${l}`);
173
+ }
174
+ return out.join("\n");
175
+ }
176
+ /**
177
+ * The `Examples:` block that ends a command's help: one `$ command` per line, with an optional
178
+ * ` # why` after it.
179
+ */
180
+ export function examplesBlock(examples) {
181
+ return ["Examples:", ...examples.map((e) => ` $ ${e}`)].join("\n");
182
+ }
183
+ /** Edit distance with adjacent transpositions (so "stauts" is 1 away from "status"). */
184
+ export function distance(a, b) {
185
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
186
+ for (let i = 1; i <= a.length; i++) {
187
+ for (let j = 1; j <= b.length; j++) {
188
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
189
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
190
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
191
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
192
+ }
193
+ }
194
+ return d[a.length][b.length];
195
+ }
196
+ /** The closest of `candidates` to `word` (at most 2 edits, 1 for words of 3 letters or less). */
197
+ export function closest(word, candidates) {
198
+ const max = word.length <= 3 ? 1 : 2;
199
+ let best;
200
+ for (const c of candidates) {
201
+ const d = distance(word.toLowerCase(), c);
202
+ if (d <= max && (!best || d < best.d))
203
+ best = { c, d };
204
+ }
205
+ return best?.c;
206
+ }
22
207
  //# sourceMappingURL=io.js.map
@@ -1,35 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
- import { accessSync, constants as fsConstants, statSync } from "node:fs";
3
2
  import { constants } from "node:os";
4
- import { delimiter, join } from "node:path";
5
- import { isValidProfileName } from "../core/config.js";
6
- import { paths } from "../core/paths.js";
7
- import { UsageError } from "./io.js";
8
- import { launcherName, profileAgent } from "./launchers.js";
9
- function executable(file) {
10
- try {
11
- if (!statSync(file).isFile())
12
- return false;
13
- accessSync(file, fsConstants.X_OK);
14
- return true;
15
- }
16
- catch {
17
- return false;
18
- }
19
- }
20
- /** Absolute path of a command found on PATH (or the command itself when it has a slash). */
21
- export function findOnPath(cmd, env = process.env) {
22
- if (cmd.includes("/"))
23
- return executable(cmd) ? cmd : undefined;
24
- for (const dir of (env.PATH ?? "").split(delimiter)) {
25
- if (!dir)
26
- continue;
27
- const file = join(dir, cmd);
28
- if (executable(file))
29
- return file;
30
- }
31
- return undefined;
32
- }
3
+ import { join } from "node:path";
4
+ import { isValidProfileName, loadConfig } from "../core/config.js";
5
+ import { paths, tildify } from "../core/paths.js";
6
+ import { listProfiles } from "../core/profiles.js";
7
+ import { CliError, UsageError } from "./io.js";
8
+ import { executable, launcherName, profileAgent } from "./launchers.js";
9
+ export { findOnPath } from "./launchers.js";
33
10
  /** Path of a profile's launcher (claude-<name>, codex-<name>, ...) when it exists and is executable. */
34
11
  export function launcherPath(name, env = process.env, agent = profileAgent(name, env)) {
35
12
  if (!isValidProfileName(name))
@@ -37,6 +14,14 @@ export function launcherPath(name, env = process.env, agent = profileAgent(name,
37
14
  const file = join(paths(env).bin, launcherName(name, agent));
38
15
  return executable(file) ? file : undefined;
39
16
  }
17
+ /** `--no-gateway` before any `--`, or TURNO_SAFE on: safe mode (cli/safe.ts holds the rest). */
18
+ export function wantsSafe(args, env) {
19
+ const end = args.indexOf("--");
20
+ if ((end < 0 ? args : args.slice(0, end)).includes("--no-gateway"))
21
+ return true;
22
+ const v = env.TURNO_SAFE;
23
+ return v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
24
+ }
40
25
  /** Terminal signals already reach the child (same process group); these are passed on. */
41
26
  const FORWARDED = ["SIGTERM", "SIGHUP"];
42
27
  const IGNORED = ["SIGINT", "SIGQUIT"];
@@ -80,17 +65,45 @@ export async function execLauncher(file, args, env = process.env) {
80
65
  });
81
66
  });
82
67
  }
83
- /** Exec a command looked up on PATH, as the shell's `exec cmd "$@"` would. */
84
- export async function execCommand(cmd, args, env = process.env) {
85
- const file = findOnPath(cmd, env);
86
- if (!file)
87
- throw new UsageError(`${cmd}: command not found on PATH`);
88
- return execLauncher(file, args, env);
89
- }
90
- /** `turno <profile> [args]`: exec the profile's launcher. */
91
- export async function launchProfile(name, args, io) {
68
+ /**
69
+ * `turno <profile> [args]`: exec the profile's launcher. `--no-gateway` among turno's arguments,
70
+ * or TURNO_SAFE=1, opens it in safe mode instead (cli/safe.ts).
71
+ */
72
+ export async function launchProfile(name, given, io) {
73
+ let args = given;
74
+ // Checked here without loading safe.ts, so a normal launch pays nothing for it.
75
+ if (wantsSafe(given, io.env)) {
76
+ const { launchSafe, takeSafeFlag } = await import("./safe.js");
77
+ args = takeSafeFlag(given).args;
78
+ if (!isValidProfileName(name))
79
+ throw new UsageError(`unknown command '${name}' (turno --help)`);
80
+ let config;
81
+ try {
82
+ config = loadConfig(io.env);
83
+ }
84
+ catch (err) {
85
+ throw new CliError(err.message);
86
+ }
87
+ if (!listProfiles(config, io.env).includes(name))
88
+ throw new UsageError(`no profile '${name}' (turno profile list shows them; turno profile add ${name} creates it)`);
89
+ return launchSafe(profileAgent(name, io.env), name, args, io);
90
+ }
92
91
  const file = launcherPath(name, io.env);
93
92
  if (!file) {
93
+ if (!isValidProfileName(name))
94
+ throw new UsageError(`unknown command '${name}' (turno --help)`);
95
+ let declared = false;
96
+ try {
97
+ declared = listProfiles(loadConfig(io.env), io.env).includes(name);
98
+ }
99
+ catch {
100
+ declared = false;
101
+ }
102
+ if (declared) {
103
+ const agent = profileAgent(name, io.env);
104
+ const missing = tildify(join(paths(io.env).bin, launcherName(name, agent)), io.env);
105
+ throw new CliError(`profile ${name} has no launcher (${missing} is missing). Run: turno profile repair ${name}`);
106
+ }
94
107
  throw new UsageError(`no profile '${name}' (turno profile list shows them; turno profile add ${name} creates it)`);
95
108
  }
96
109
  return execLauncher(file, args, io.env);