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,281 @@
1
+ /**
2
+ * The look of turno's own screens: semantic colors, status icons, section headers, key/value
3
+ * rows, tables sized to the terminal, usage bars, a spinner and timings. Every command draws with
4
+ * this so the CLI reads as one tool. Without colors (a pipe, NO_COLOR) the same layout comes out
5
+ * as plain text with ASCII icons, stable for scripts and tests.
6
+ *
7
+ * Keep this file free of heavy imports: `turno --help`, `turno status` and the status line load it.
8
+ */
9
+ import { NAMED_COLORS, PILL_DEFAULTS } from "../statusline/render.js";
10
+ import { colors } from "./io.js";
11
+ const cp = (n) => String.fromCodePoint(n);
12
+ export const ICONS = {
13
+ nerd: {
14
+ ok: cp(0xf00c),
15
+ warn: cp(0xf071),
16
+ err: cp(0xf00d),
17
+ info: cp(0xf05a),
18
+ add: "+",
19
+ remove: "-",
20
+ on: cp(0xf111),
21
+ off: cp(0xf10c),
22
+ arrow: cp(0xf061),
23
+ next: cp(0xf0a9),
24
+ skip: cp(0xf05e),
25
+ },
26
+ unicode: { ok: "✓", warn: "!", err: "✗", info: "•", add: "+", remove: "-", on: "●", off: "○", arrow: "→", next: "➜", skip: "–" },
27
+ ascii: { ok: "ok", warn: "!", err: "x", info: "-", add: "+", remove: "-", on: "", off: "", arrow: "->", next: "", skip: "-" },
28
+ };
29
+ /** SGR codes of the semantic colors: the terminal's own palette, so dark and light themes both work. */
30
+ const CODES = { ok: "32", warn: "33", err: "31", accent: "36", muted: "2", faint: "90", bold: "1" };
31
+ /**
32
+ * The 256-color code of a profile: its `color` in config.toml, or one of the defaults by its
33
+ * place in the config. The one rule for every profile pill: the status line (`pillColor` in
34
+ * statusline.ts) calls this too, and the color tables are the status line's (render.ts).
35
+ */
36
+ export function profileColor(profiles, name) {
37
+ const c = profiles[name]?.color;
38
+ if (typeof c === "number")
39
+ return c;
40
+ if (typeof c === "string") {
41
+ if (/^\d+$/.test(c))
42
+ return Number(c);
43
+ const named = NAMED_COLORS[c.toLowerCase()];
44
+ if (named !== undefined)
45
+ return named;
46
+ }
47
+ const names = Object.keys(profiles);
48
+ const idx = names.includes(name) ? names.indexOf(name) : [...name].reduce((a, ch) => a + ch.charCodeAt(0), 0);
49
+ return PILL_DEFAULTS[idx % PILL_DEFAULTS.length];
50
+ }
51
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching ANSI escapes is the point
52
+ const ANSI = /\x1b\[[0-9;]*m/g;
53
+ /** Text without its ANSI color codes. */
54
+ export function stripAnsi(text) {
55
+ return text.replace(ANSI, "");
56
+ }
57
+ /** Columns a string takes on screen (ANSI codes take none). */
58
+ export function visibleWidth(text) {
59
+ return [...stripAnsi(text)].length;
60
+ }
61
+ /** Pad to `width` visible columns. */
62
+ export function padEnd(text, width) {
63
+ return text + " ".repeat(Math.max(0, width - visibleWidth(text)));
64
+ }
65
+ function padStart(text, width) {
66
+ return " ".repeat(Math.max(0, width - visibleWidth(text))) + text;
67
+ }
68
+ /**
69
+ * Columns of the terminal: COLUMNS, then the real terminal, then 80 (a pipe, a test). Never
70
+ * below 40, so layouts keep a sane minimum.
71
+ */
72
+ export function termWidth(io) {
73
+ const env = Number(io.env.COLUMNS);
74
+ if (Number.isInteger(env) && env > 0)
75
+ return Math.max(40, env);
76
+ const real = io.isTty ? process.stdout.columns : undefined;
77
+ return real && real > 0 ? Math.max(40, real) : 80;
78
+ }
79
+ /** "420ms", "1.2s", "1m05s". */
80
+ export function duration(ms) {
81
+ if (ms < 1000)
82
+ return `${Math.max(0, Math.round(ms))}ms`;
83
+ if (ms < 60_000)
84
+ return `${(ms / 1000).toFixed(1)}s`;
85
+ const s = Math.round(ms / 1000);
86
+ return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
87
+ }
88
+ /** Level of a usage percentage: below 60 fine, below 85 a warning, then a problem. */
89
+ export function level(pct) {
90
+ return pct < 60 ? "ok" : pct < 85 ? "warn" : "err";
91
+ }
92
+ /** Cut a word that may hold ANSI codes into pieces of at most `width` visible columns. */
93
+ function chop(word, width) {
94
+ const pieces = [];
95
+ let piece = "";
96
+ let w = 0;
97
+ // ANSI codes take no columns and stay with the character after them.
98
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching ANSI escapes is the point
99
+ for (const m of word.matchAll(/\x1b\[[0-9;]*m|[^\x1b]/gu)) {
100
+ const t = m[0];
101
+ if (t.startsWith("\x1b")) {
102
+ piece += t;
103
+ continue;
104
+ }
105
+ if (w === width) {
106
+ pieces.push(piece);
107
+ piece = "";
108
+ w = 0;
109
+ }
110
+ piece += t;
111
+ w++;
112
+ }
113
+ if (piece)
114
+ pieces.push(piece);
115
+ return pieces;
116
+ }
117
+ /**
118
+ * Break text that may hold ANSI codes into lines of at most `width` visible columns, at spaces.
119
+ * A word longer than the width (a long path) is cut at the width. Colors carry over: a terminal
120
+ * keeps the active SGR across a line break.
121
+ */
122
+ export function wrapAnsi(text, width) {
123
+ if (visibleWidth(text) <= width)
124
+ return [text];
125
+ const words = text.split(" ").flatMap((word) => (visibleWidth(word) > width ? chop(word, width) : [word]));
126
+ const [first = "", ...rest] = words;
127
+ const lines = [];
128
+ let line = first;
129
+ let w = visibleWidth(first);
130
+ for (const word of rest) {
131
+ const ww = visibleWidth(word);
132
+ // Break before a word that does not fit; spaces inside a line (alignment) stay as they are.
133
+ if (w > 0 && ww > 0 && w + 1 + ww > width) {
134
+ lines.push(line);
135
+ line = word;
136
+ w = ww;
137
+ }
138
+ else {
139
+ line += ` ${word}`;
140
+ w += 1 + ww;
141
+ }
142
+ }
143
+ lines.push(line);
144
+ return lines;
145
+ }
146
+ /** Columns a wrapping last table column keeps before other columns are dropped for it. */
147
+ const LAST_MIN = 24;
148
+ export function style(io, opts = {}) {
149
+ const color = colors(io);
150
+ const icons = !color ? "ascii" : opts.nerd ? "nerd" : "unicode";
151
+ const width = termWidth(io);
152
+ const sgr = (code) => (s) => (color && s ? `\x1b[${code}m${s}\x1b[0m` : s);
153
+ const ok = sgr(CODES.ok);
154
+ const warn = sgr(CODES.warn);
155
+ const err = sgr(CODES.err);
156
+ const accent = sgr(CODES.accent);
157
+ const muted = sgr(CODES.muted);
158
+ const faint = sgr(CODES.faint);
159
+ const bold = sgr(CODES.bold);
160
+ const ICON_COLOR = {
161
+ ok,
162
+ warn,
163
+ err,
164
+ info: accent,
165
+ add: ok,
166
+ remove: err,
167
+ on: ok,
168
+ off: faint,
169
+ arrow: faint,
170
+ next: accent,
171
+ skip: faint,
172
+ };
173
+ const icon = (name) => (ICON_COLOR[name] ?? ((s) => s))(ICONS[icons][name]);
174
+ const iconWidth = Math.max(...["ok", "warn", "err", "skip", "info"].map((n) => visibleWidth(ICONS[icons][n])));
175
+ const wrapLine = (prefix, text) => {
176
+ if (!color)
177
+ return `${prefix}${text}`;
178
+ const hang = visibleWidth(prefix);
179
+ const body = wrapAnsi(text, Math.max(20, width - hang));
180
+ return [`${prefix}${body[0]}`, ...body.slice(1).map((l) => `${" ".repeat(hang)}${l}`)].join("\n");
181
+ };
182
+ const tableRows = (rows, o = {}) => {
183
+ const indent = o.indent ?? 2;
184
+ const gap = o.gap ?? 2;
185
+ const cols = o.columns ?? [];
186
+ const n = Math.max(0, ...rows.map((r) => r.length));
187
+ let keep = Array.from({ length: n }, (_, i) => i);
188
+ const widthOf = (i) => Math.max(0, ...rows.map((r) => visibleWidth(r[i] ?? "")));
189
+ // The last column wraps under itself, so it only needs LAST_MIN columns to fit.
190
+ const total = (ks) => indent + ks.reduce((a, i, k) => a + (k === ks.length - 1 ? Math.min(widthOf(i), LAST_MIN) : widthOf(i)), 0) + gap * Math.max(0, ks.length - 1);
191
+ // Only a terminal drops columns: a pipe keeps everything for whoever reads it.
192
+ while (color && total(keep) > width) {
193
+ const droppable = keep.filter((i) => cols[i]?.drop !== undefined).sort((a, b) => cols[b].drop - cols[a].drop);
194
+ if (!droppable.length)
195
+ break;
196
+ keep = keep.filter((i) => i !== droppable[0]);
197
+ }
198
+ const widths = new Map(keep.map((i) => [i, widthOf(i)]));
199
+ return rows.map((r) => {
200
+ const cells = keep.map((i, k) => {
201
+ const cell = r[i] ?? "";
202
+ const w = widths.get(i);
203
+ if (cols[i]?.align === "right")
204
+ return padStart(cell, w);
205
+ return k === keep.length - 1 ? cell : padEnd(cell, w);
206
+ });
207
+ const head = " ".repeat(indent) + cells.slice(0, -1).map((c) => `${c}${" ".repeat(gap)}`).join("");
208
+ return wrapLine(head, cells.at(-1) ?? "")
209
+ .split("\n")
210
+ .map((l) => l.trimEnd());
211
+ });
212
+ };
213
+ const table = (rows, o) => tableRows(rows, o).flat();
214
+ return {
215
+ color,
216
+ icons,
217
+ width,
218
+ bold,
219
+ muted,
220
+ accent,
221
+ ok,
222
+ warn,
223
+ err,
224
+ icon,
225
+ lead: (name, text) => (ICONS[icons][name] ? `${icon(name)} ${text}` : text),
226
+ profile: (name, c) => (color && c !== undefined ? `\x1b[48;5;${c};1;38;5;255m ${name} \x1b[0m` : color ? bold(name) : name),
227
+ header: (title) => {
228
+ if (!color)
229
+ return title;
230
+ const rule = Math.max(0, Math.min(width, 80) - visibleWidth(title) - 1);
231
+ return `${bold(title)} ${faint("─".repeat(rule))}`;
232
+ },
233
+ kv: (key, value, keyWidth, indent = 2) => wrapLine(`${" ".repeat(indent)}${muted(padEnd(key, keyWidth))} `, value).trimEnd(),
234
+ table,
235
+ tableRows,
236
+ wrap: wrapLine,
237
+ note: (state, text, indent = 2) => wrapLine(`${" ".repeat(indent)}${padEnd(icon(state), iconWidth)} `, text),
238
+ bar: (pct, cells = 10) => {
239
+ const p = Math.min(Math.max(pct, 0), 100);
240
+ const filled = Math.round((p * cells) / 100);
241
+ const paint = { ok, warn, err }[level(p)];
242
+ // A heavy rule on a terminal (colored, the rest faint); blocks in plain text, where only shape tells.
243
+ const [on, off] = color ? ["━", "━"] : ["█", "░"];
244
+ return `${paint(on.repeat(filled))}${faint(off.repeat(cells - filled))} ${paint(`${p.toFixed(0)}%`.padStart(4))}`;
245
+ },
246
+ check: (state, text) => `${padEnd(icon(state), iconWidth)} ${text}`,
247
+ };
248
+ }
249
+ const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
250
+ /**
251
+ * A spinner with the elapsed time on stderr, for steps that wait (the gateway starting). Only on
252
+ * a terminal with colors: anywhere else it draws nothing, and the caller prints the result line.
253
+ */
254
+ export function spinner(io, text, opts = {}) {
255
+ const now = opts.now ?? Date.now;
256
+ const start = now();
257
+ const tty = opts.tty ?? Boolean(process.stderr.isTTY);
258
+ const write = opts.write ?? ((s) => process.stderr.write(s));
259
+ if (!tty || !colors(io))
260
+ return { update: () => { }, stop: () => now() - start };
261
+ let current = text;
262
+ let frame = 0;
263
+ const draw = () => {
264
+ const secs = ((now() - start) / 1000).toFixed(1);
265
+ write(`\r\x1b[K\x1b[36m${FRAMES[frame++ % FRAMES.length]}\x1b[0m ${current} \x1b[2m${secs}s\x1b[0m`);
266
+ };
267
+ draw();
268
+ const timer = setInterval(draw, 80);
269
+ timer.unref?.();
270
+ return {
271
+ update: (t) => {
272
+ current = t;
273
+ },
274
+ stop: () => {
275
+ clearInterval(timer);
276
+ write("\r\x1b[K");
277
+ return now() - start;
278
+ },
279
+ };
280
+ }
281
+ //# sourceMappingURL=style.js.map
@@ -1,7 +1,90 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { parse } from "smol-toml";
3
- import { AGENT_IDS, isAgentId } from "../agents/index.js";
4
- import { expandHome, paths } from "./paths.js";
3
+ import { AGENT_IDS, DEFAULT_AGENT, adapter, isAgentId } from "../agents/index.js";
4
+ import { distance } from "../cli/io.js";
5
+ import { expandHome, paths, tildify } from "./paths.js";
6
+ /** Every key config.toml may hold, by table ("" is the top level; `*` stands for any name). */
7
+ const KNOWN_KEYS = {
8
+ "": ["system", "default", "fallback", "icons", "nerd_terminals", "update_check", "profiles", "agents", "projects", "open", "mcpd"],
9
+ "profiles.*": ["agent", "browser", "color"],
10
+ "agents.*": ["default", "fallback"],
11
+ "projects[]": ["path", "profile", "mcp", "mcp_deny"],
12
+ open: ["chrome_dir"],
13
+ mcpd: ["port", "call_log", "max_request_body", "idle_under_pressure"],
14
+ };
15
+ const SIZE_UNITS = { "": 1, b: 1, k: 1024, kb: 1000, kib: 1024, m: 1024 ** 2, mb: 1000 ** 2, mib: 1024 ** 2, g: 1024 ** 3, gb: 1000 ** 3, gib: 1024 ** 3 };
16
+ /** Bounds of `mcpd.max_request_body`: below 1 MiB ordinary tool calls fail, above 1 GiB a client can exhaust memory. */
17
+ const MIN_REQUEST_BODY = 1024 ** 2;
18
+ const MAX_REQUEST_BODY = 1024 ** 3;
19
+ /**
20
+ * A size in bytes: a whole number of bytes, or a string such as "64MiB", "512 KiB" or "1GB".
21
+ * Undefined when it is neither.
22
+ */
23
+ export function parseSize(v) {
24
+ if (typeof v === "number")
25
+ return Number.isInteger(v) && v >= 0 ? v : undefined;
26
+ if (typeof v !== "string")
27
+ return undefined;
28
+ const m = /^\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*$/i.exec(v);
29
+ const unit = m ? SIZE_UNITS[m[2].toLowerCase()] : undefined;
30
+ return m && unit ? Math.round(Number(m[1]) * unit) : undefined;
31
+ }
32
+ /** Check `mcpd.max_request_body`; the message when it is out of bounds or not a size. */
33
+ export function requestBodyProblem(v) {
34
+ const n = parseSize(v);
35
+ if (n === undefined || n < MIN_REQUEST_BODY || n > MAX_REQUEST_BODY)
36
+ return 'mcpd.max_request_body must be a size between 1MiB and 1GiB, in bytes or like "64MiB"';
37
+ return undefined;
38
+ }
39
+ /** Default of `mcpd.idle_under_pressure`, in seconds. */
40
+ const DEFAULT_IDLE_UNDER_PRESSURE = 300;
41
+ /**
42
+ * `mcpd.idle_under_pressure` in seconds: a duration ("5m", "90s", "1h" or seconds) between 30
43
+ * seconds and 24 hours, `false` (0, off) or `true` (the default). Undefined when invalid.
44
+ */
45
+ export function parseIdleUnderPressure(v) {
46
+ if (v === false)
47
+ return 0;
48
+ if (v === true)
49
+ return DEFAULT_IDLE_UNDER_PRESSURE;
50
+ let secs;
51
+ if (typeof v === "number")
52
+ secs = v;
53
+ else if (typeof v === "string") {
54
+ const m = /^(\d+(?:\.\d+)?)\s*(s|m|h)?$/.exec(v.trim());
55
+ if (m)
56
+ secs = Number(m[1]) * (m[2] === "h" ? 3600 : m[2] === "m" ? 60 : 1);
57
+ }
58
+ return secs !== undefined && Number.isFinite(secs) && secs >= 30 && secs <= 24 * 3600 ? secs : undefined;
59
+ }
60
+ export const IDLE_UNDER_PRESSURE_PROBLEM = 'mcpd.idle_under_pressure must be a duration between 30s and 24h, like "5m", or false';
61
+ /** The known key closest to `key`, when it is a likely typo (or `colour` for `color`). */
62
+ export function suggestKey(key, known) {
63
+ let best;
64
+ for (const k of known) {
65
+ const d = distance(key, k);
66
+ if (d <= Math.max(1, Math.min(3, Math.floor(k.length / 3))) && (!best || d < best.d))
67
+ best = { k, d };
68
+ }
69
+ return best?.k;
70
+ }
71
+ function unknownKeys(table, known, prefix, warnings) {
72
+ for (const key of Object.keys(table)) {
73
+ if (known.includes(key))
74
+ continue;
75
+ const near = suggestKey(key, known);
76
+ warnings.push(`unknown key ${prefix}${key}${near ? ` (did you mean ${prefix}${near}?)` : ""}; turno ignores it`);
77
+ }
78
+ }
79
+ /** A friendlier text for TOML syntax errors that smol-toml words in parser terms. */
80
+ function tomlMessage(message) {
81
+ const head = message.split("\n", 1)[0].replace(/^Invalid TOML document: /, "");
82
+ const pos = /\n(\d+):/.exec(message);
83
+ if (/control characters are not allowed in strings|unterminated string/i.test(head)) {
84
+ return `line ${pos?.[1] ?? "?"}: a string is not closed (a " is missing at the end of the value)`;
85
+ }
86
+ return message;
87
+ }
5
88
  export class ConfigError extends Error {
6
89
  constructor(file, message) {
7
90
  super(`${file}: ${message}`);
@@ -19,14 +102,32 @@ function str(v, file, key) {
19
102
  throw new ConfigError(file, `${key} must be a string`);
20
103
  return v;
21
104
  }
22
- export function parseConfig(text, file = "config.toml", env = process.env) {
105
+ /** A list of MCP server names (`[[projects]] mcp`), or undefined when unset. */
106
+ function names(v, file, key) {
107
+ if (v === undefined)
108
+ return undefined;
109
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string" || !x))
110
+ throw new ConfigError(file, `${key} must be an array of server names, like ["issues", "docs"]`);
111
+ return v;
112
+ }
113
+ function table(v, file, key) {
114
+ if (v === undefined)
115
+ return {};
116
+ if (typeof v !== "object" || v === null || Array.isArray(v))
117
+ throw new ConfigError(file, `[${key}] must be a table`);
118
+ return v;
119
+ }
120
+ export function parseConfig(text, path = "config.toml", env = process.env) {
121
+ const file = tildify(path, env);
23
122
  let raw;
24
123
  try {
25
124
  raw = parse(text);
26
125
  }
27
126
  catch (err) {
28
- throw new ConfigError(file, err.message);
127
+ throw new ConfigError(file, tomlMessage(err.message));
29
128
  }
129
+ const warnings = [];
130
+ unknownKeys(raw, KNOWN_KEYS[""], "", warnings);
30
131
  const p = paths(env);
31
132
  const cfg = {
32
133
  icons: "auto",
@@ -36,7 +137,8 @@ export function parseConfig(text, file = "config.toml", env = process.env) {
36
137
  agents: {},
37
138
  projects: [],
38
139
  open: { chromeDir: p.chromeProfilesDir },
39
- mcpd: { port: 47821 },
140
+ mcpd: { port: 47821, callLog: true, idleUnderPressure: DEFAULT_IDLE_UNDER_PRESSURE },
141
+ warnings,
40
142
  };
41
143
  cfg.system = str(raw.system, file, "system");
42
144
  cfg.default = str(raw.default, file, "default");
@@ -60,13 +162,12 @@ export function parseConfig(text, file = "config.toml", env = process.env) {
60
162
  throw new ConfigError(file, "update_check must be true or false");
61
163
  cfg.updateCheck = raw.update_check;
62
164
  }
63
- const profiles = raw.profiles ?? {};
64
- if (typeof profiles !== "object" || Array.isArray(profiles))
65
- throw new ConfigError(file, "[profiles] must be a table");
165
+ const profiles = table(raw.profiles, file, "profiles");
66
166
  for (const [name, value] of Object.entries(profiles)) {
67
167
  if (!isValidProfileName(name))
68
168
  throw new ConfigError(file, `invalid profile name "${name}"`);
69
- const v = (value ?? {});
169
+ const v = table(value, file, `profiles.${name}`);
170
+ unknownKeys(v, KNOWN_KEYS["profiles.*"], `profiles.${name}.`, warnings);
70
171
  const browser = str(v.browser, file, `profiles.${name}.browser`) ?? "chrome";
71
172
  if (browser !== "chrome" && browser !== "default") {
72
173
  throw new ConfigError(file, `profiles.${name}.browser must be chrome or default`);
@@ -75,19 +176,18 @@ export function parseConfig(text, file = "config.toml", env = process.env) {
75
176
  if (color !== undefined && typeof color !== "string" && typeof color !== "number") {
76
177
  throw new ConfigError(file, `profiles.${name}.color must be a name or a number`);
77
178
  }
78
- const agent = v.agent ?? "claude";
179
+ const agent = v.agent ?? DEFAULT_AGENT;
79
180
  if (!isAgentId(agent))
80
181
  throw new ConfigError(file, `profiles.${name}.agent must be one of ${AGENT_IDS.join(", ")}`);
81
182
  cfg.profiles[name] = { agent, browser, ...(color !== undefined ? { color } : {}) };
82
183
  }
83
- const agents = raw.agents ?? {};
84
- if (typeof agents !== "object" || Array.isArray(agents))
85
- throw new ConfigError(file, "[agents] must be a table");
184
+ const agents = table(raw.agents, file, "agents");
86
185
  for (const [id, value] of Object.entries(agents)) {
87
- if (!isAgentId(id) || id === "claude") {
88
- throw new ConfigError(file, `[agents.${id}]: use one of ${AGENT_IDS.filter((a) => a !== "claude").join(", ")} (Claude Code uses the top-level default and fallback)`);
186
+ if (!isAgentId(id) || id === DEFAULT_AGENT) {
187
+ throw new ConfigError(file, `[agents.${id}]: use one of ${AGENT_IDS.filter((a) => a !== DEFAULT_AGENT).join(", ")} (${adapter(DEFAULT_AGENT).label} uses the top-level default and fallback)`);
89
188
  }
90
- const v = (value ?? {});
189
+ const v = table(value, file, `agents.${id}`);
190
+ unknownKeys(v, KNOWN_KEYS["agents.*"], `agents.${id}.`, warnings);
91
191
  const roles = {};
92
192
  const d = str(v.default, file, `agents.${id}.default`);
93
193
  const f = str(v.fallback, file, `agents.${id}.fallback`);
@@ -101,28 +201,50 @@ export function parseConfig(text, file = "config.toml", env = process.env) {
101
201
  if (!Array.isArray(projects))
102
202
  throw new ConfigError(file, "projects must be an array of tables ([[projects]])");
103
203
  for (const [i, item] of projects.entries()) {
104
- const v = item;
204
+ const v = table(item, file, `projects[${i}]`);
205
+ unknownKeys(v, KNOWN_KEYS["projects[]"], `projects[${i}].`, warnings);
105
206
  const path = str(v.path, file, `projects[${i}].path`);
106
207
  const profile = str(v.profile, file, `projects[${i}].profile`);
107
- if (!path || !profile)
108
- throw new ConfigError(file, `projects[${i}] needs path and profile`);
109
- cfg.projects.push({ path: expandHome(path, env), profile });
208
+ const mcp = names(v.mcp, file, `projects[${i}].mcp`);
209
+ const mcpDeny = names(v.mcp_deny, file, `projects[${i}].mcp_deny`);
210
+ if (!path || (!profile && !mcp && !mcpDeny))
211
+ throw new ConfigError(file, `projects[${i}] needs path and profile, mcp or mcp_deny`);
212
+ cfg.projects.push({ path: expandHome(path, env), ...(profile ? { profile } : {}), ...(mcp ? { mcp } : {}), ...(mcpDeny ? { mcpDeny } : {}) });
110
213
  }
111
- const open = (raw.open ?? {});
214
+ const open = table(raw.open, file, "open");
215
+ unknownKeys(open, KNOWN_KEYS.open, "open.", warnings);
112
216
  const chromeDir = str(open.chrome_dir, file, "open.chrome_dir");
113
217
  if (chromeDir)
114
218
  cfg.open.chromeDir = expandHome(chromeDir, env);
115
- const mcpd = (raw.mcpd ?? {});
219
+ const mcpd = table(raw.mcpd, file, "mcpd");
220
+ unknownKeys(mcpd, KNOWN_KEYS.mcpd, "mcpd.", warnings);
116
221
  if (mcpd.port !== undefined) {
117
222
  if (typeof mcpd.port !== "number" || !Number.isInteger(mcpd.port) || mcpd.port < 1024 || mcpd.port > 65535) {
118
223
  throw new ConfigError(file, "mcpd.port must be an integer between 1024 and 65535");
119
224
  }
120
225
  cfg.mcpd.port = mcpd.port;
121
226
  }
227
+ if (mcpd.call_log !== undefined) {
228
+ if (typeof mcpd.call_log !== "boolean")
229
+ throw new ConfigError(file, "mcpd.call_log must be true or false");
230
+ cfg.mcpd.callLog = mcpd.call_log;
231
+ }
232
+ if (mcpd.max_request_body !== undefined) {
233
+ const problem = requestBodyProblem(mcpd.max_request_body);
234
+ if (problem)
235
+ throw new ConfigError(file, problem);
236
+ cfg.mcpd.maxRequestBody = parseSize(mcpd.max_request_body);
237
+ }
238
+ if (mcpd.idle_under_pressure !== undefined) {
239
+ const secs = parseIdleUnderPressure(mcpd.idle_under_pressure);
240
+ if (secs === undefined)
241
+ throw new ConfigError(file, IDLE_UNDER_PRESSURE_PROBLEM);
242
+ cfg.mcpd.idleUnderPressure = secs;
243
+ }
122
244
  return cfg;
123
245
  }
124
246
  /** Load ~/.config/turno/config.toml; a missing file means all defaults. */
125
- export function loadConfig(env = process.env) {
247
+ export function loadConfig(env) {
126
248
  const file = paths(env).configFile;
127
249
  let text = "";
128
250
  try {
@@ -1,8 +1,8 @@
1
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { readFileSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { paths } from "./paths.js";
3
+ import { paths, writePrivateFile } from "./paths.js";
4
4
  /** Epoch seconds until which a profile is marked exhausted, or undefined (expired marks are removed). */
5
- export function exhaustedUntil(profile, env = process.env, now = Date.now() / 1000) {
5
+ export function exhaustedUntil(profile, env, now = Date.now() / 1000) {
6
6
  const file = join(paths(env).exhaustedDir, profile);
7
7
  let until;
8
8
  try {
@@ -19,12 +19,10 @@ export function exhaustedUntil(profile, env = process.env, now = Date.now() / 10
19
19
  }
20
20
  return until;
21
21
  }
22
- export function markExhausted(profile, until, env = process.env) {
23
- const dir = paths(env).exhaustedDir;
24
- mkdirSync(dir, { recursive: true });
25
- writeFileSync(join(dir, profile), `${Math.floor(until)}\n`);
22
+ export function markExhausted(profile, until, env) {
23
+ writePrivateFile(join(paths(env).exhaustedDir, profile), `${Math.floor(until)}\n`, env);
26
24
  }
27
- export function clearExhausted(profile, env = process.env) {
25
+ export function clearExhausted(profile, env) {
28
26
  rmSync(join(paths(env).exhaustedDir, profile), { force: true });
29
27
  }
30
28
  //# sourceMappingURL=exhausted.js.map
@@ -0,0 +1,47 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { CliError } from "../cli/io.js";
3
+ /** Small file and process helpers shared across modules. Keep this file free of heavy imports. */
4
+ /** The real path of `p`, or `p` itself when it cannot be resolved (it does not exist, no access). */
5
+ export function realOr(p) {
6
+ try {
7
+ return realpathSync(p);
8
+ }
9
+ catch {
10
+ return p;
11
+ }
12
+ }
13
+ /** The parsed JSON of a file, or undefined when it is missing, unreadable or not JSON. */
14
+ export function readJsonFile(file) {
15
+ try {
16
+ return JSON.parse(readFileSync(file, "utf8"));
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ /** A JSON object: not null, not an array. */
23
+ export function isObject(v) {
24
+ return typeof v === "object" && v !== null && !Array.isArray(v);
25
+ }
26
+ /**
27
+ * The object in a JSON config another program writes (Claude Code's .claude.json and
28
+ * settings.json, Cursor's mcp.json): valid JSON of any other shape is an error naming the file,
29
+ * not a TypeError later.
30
+ */
31
+ export function parseJsonObject(text, file) {
32
+ const v = JSON.parse(text);
33
+ if (!isObject(v))
34
+ throw new CliError(`${file} does not hold a JSON object; fix or remove it`);
35
+ return v;
36
+ }
37
+ /** Whether a process is alive. EPERM means it exists but belongs to someone else. */
38
+ export function pidAlive(pid) {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch (err) {
44
+ return err.code === "EPERM";
45
+ }
46
+ }
47
+ //# sourceMappingURL=fsutil.js.map