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
@@ -3,32 +3,50 @@ import { existsSync } from "node:fs";
3
3
  import { parse } from "smol-toml";
4
4
  import { loadRegistry } from "../../accounts/registry.js";
5
5
  import { editConfig, migrationPending, readConfigText } from "../../core/config-edit.js";
6
- import { loadConfig } from "../../core/config.js";
6
+ import { IDLE_UNDER_PRESSURE_PROBLEM, loadConfig, parseIdleUnderPressure, requestBodyProblem, } from "../../core/config.js";
7
+ import { DEFAULT_AGENT, adapter, isAgentId } from "../../agents/index.js";
8
+ import { agentOf, configProblems, listProfiles } from "../../core/profiles.js";
7
9
  import { Journal } from "../../core/journal.js";
8
10
  import { loadManifest } from "../../core/manifest.js";
9
11
  import { paths, tildify } from "../../core/paths.js";
10
12
  import { removeValue, setValue } from "../../core/toml-edit.js";
11
- import { DRY_RUN, JSON_FLAG, bool, parseFlags, printJson } from "../args.js";
13
+ import { DRY_RUN, JSON_FLAG, bool, flagsOf, parseFlags } from "../args.js";
14
+ import { emit, emitConfigValue, jsonOutput } from "../output.js";
12
15
  import { group } from "../group.js";
13
- import { fail, paint } from "../io.js";
16
+ import { highlightToml } from "../highlight.js";
17
+ import { CliError, colors, columns, fail, paint } from "../io.js";
18
+ import { parseColor } from "./profile.js";
19
+ /**
20
+ * `turno config path --json`: one entry per file, each {path, exists}; with --all,
21
+ * `all` lists every path turno uses, each {name, path, exists, about}.
22
+ */
23
+ const PATH_JSON = jsonOutput(["config", "mcp", "accounts", "state", "backups", "all"]);
24
+ const PATH_FLAGS = { all: { type: "boolean" }, ...JSON_FLAG };
14
25
  /** Keys `config set` may change; tables of their own have their own commands. */
15
26
  const KEYS = {
16
- system: "profile the plain claude command (~/.claude) is logged into",
17
- default: "profile for folders without a rule",
18
- fallback: "profile used while the assigned one is exhausted",
27
+ system: 'profile the plain claude command (~/.claude) is logged into; "" for none (then turno auto needs a rule)',
28
+ default: "Claude Code profile for folders without a rule",
29
+ fallback: "Claude Code profile used while the assigned one is exhausted (opt-in)",
30
+ "agents.<agent>.default": "the same for codex, copilot or cursor",
31
+ "agents.<agent>.fallback": "the same for codex, copilot or cursor (opt-in)",
19
32
  icons: "auto, nerd or unicode",
20
33
  nerd_terminals: "terminals whose font draws Nerd icons",
21
34
  update_check: "true or false: look for new turno releases once a day",
35
+ hints: "true or false: print the next step after a command that writes",
22
36
  "open.chrome_dir": "folder of the isolated Chrome profiles",
23
37
  "mcpd.port": "port of the MCP gateway",
38
+ "mcpd.call_log": "true or false: keep the log of tool calls (turno mcp log)",
39
+ "mcpd.max_request_body": 'largest request mcpd accepts, like "64MiB" (default 32MiB)',
40
+ "mcpd.idle_under_pressure": 'idle limit of MCP servers while memory is low, like "5m" (default), or false',
24
41
  "profiles.<name>.color": "status line pill color",
25
42
  "profiles.<name>.browser": "chrome or default",
26
43
  };
27
44
  /** Split a dotted key into its table and key. */
28
45
  export function splitKey(key) {
29
- const allowed = Object.keys(KEYS).some((k) => new RegExp(`^${k.replace(/\./g, "\\.").replace("<name>", "[a-z0-9][a-z0-9_-]*")}$`).test(key));
46
+ const pattern = (k) => new RegExp(`^${k.replace(/\./g, "\\.").replace("<name>", "[a-z0-9][a-z0-9_-]*").replace("<agent>", "(codex|copilot|cursor)")}$`);
47
+ const allowed = Object.keys(KEYS).some((k) => pattern(k).test(key));
30
48
  if (!allowed)
31
- fail(`unknown key '${key}'. Keys: ${Object.keys(KEYS).join(", ")}`);
49
+ fail(`unknown key '${key}' (turno config --help lists them)`);
32
50
  const i = key.lastIndexOf(".");
33
51
  return i < 0 ? { table: undefined, key } : { table: key.slice(0, i), key: key.slice(i + 1) };
34
52
  }
@@ -52,15 +70,42 @@ export function parseValue(raw) {
52
70
  return raw;
53
71
  }
54
72
  function lookup(doc, key) {
55
- return key.split(".").reduce((v, k) => (v && typeof v === "object" ? v[k] : undefined), doc);
73
+ return key
74
+ .split(".")
75
+ .reduce((v, k) => (v && typeof v === "object" ? v[k] : undefined), doc);
56
76
  }
57
77
  async function path(args, io) {
58
- const p = parseFlags(args, JSON_FLAG, 0);
78
+ const p = parseFlags(args, PATH_FLAGS, 0);
59
79
  const env = io.env;
60
80
  const pp = paths(env);
61
- const files = { config: pp.configFile, mcp: pp.mcpFile, accounts: pp.accountsFile, state: pp.state, backups: pp.backupsDir };
81
+ const files = {
82
+ config: pp.configFile,
83
+ mcp: pp.mcpFile,
84
+ accounts: pp.accountsFile,
85
+ state: pp.state,
86
+ backups: pp.backupsDir,
87
+ };
88
+ const all = bool(p, "all") ? (await import("../diagnostics.js")).allPaths(env) : undefined;
62
89
  if (bool(p, "json")) {
63
- printJson(io.out, Object.fromEntries(Object.entries(files).map(([k, v]) => [k, { path: tildify(v, env), exists: existsSync(v) }])));
90
+ emit(io, p, PATH_JSON, {
91
+ ...Object.fromEntries(Object.entries(files).map(([k, v]) => [k, { path: tildify(v, env), exists: existsSync(v) }])),
92
+ ...(all
93
+ ? {
94
+ all: all.map((e) => ({
95
+ name: e.name,
96
+ path: tildify(e.path, env),
97
+ exists: existsSync(e.path),
98
+ about: e.about,
99
+ })),
100
+ }
101
+ : {}),
102
+ });
103
+ return 0;
104
+ }
105
+ if (all) {
106
+ const w = Math.max(...all.map((e) => e.name.length));
107
+ for (const e of all)
108
+ io.out(`${e.name.padEnd(w)} ${tildify(e.path, env)}${existsSync(e.path) ? "" : paint(io, " (not there yet)", "2")} ${paint(io, e.about, "2")}`);
64
109
  return 0;
65
110
  }
66
111
  for (const [k, v] of Object.entries(files))
@@ -69,6 +114,9 @@ async function path(args, io) {
69
114
  }
70
115
  async function get(args, io) {
71
116
  const p = parseFlags(args, JSON_FLAG, 1);
117
+ // A config value has config.toml's shape, not a schema of fields.
118
+ if (p.json)
119
+ fail("config get --json takes no fields: it prints the value as config.toml holds it");
72
120
  const key = p.positionals[0];
73
121
  const text = readConfigText(io.env);
74
122
  loadConfig(io.env); // report a broken file before reading from it
@@ -77,25 +125,101 @@ async function get(args, io) {
77
125
  if (v === undefined) {
78
126
  if (!key)
79
127
  return 0;
128
+ if (bool(p, "json"))
129
+ throw new CliError(`${key} is not set`);
80
130
  io.err(`${key} is not set`);
81
131
  return 1;
82
132
  }
83
133
  if (bool(p, "json") || typeof v === "object")
84
- printJson(io.out, v);
134
+ emitConfigValue(io, v);
85
135
  else
86
136
  io.out(String(v));
87
137
  return 0;
88
138
  }
139
+ /**
140
+ * Check a value before it is written, with the messages `profile add` uses: profile names
141
+ * must exist (and run the right agent), colors and enums must be valid. Returns the value to write.
142
+ */
143
+ export function checkValue(key, raw, env) {
144
+ const value = parseValue(raw);
145
+ const profile = (name, agent) => {
146
+ if (typeof name !== "string" || !name)
147
+ fail(`${key} must be a profile name`);
148
+ const config = loadConfig(env);
149
+ if (!listProfiles(config, env).includes(name))
150
+ fail(`no profile '${name}' (turno profile list)`);
151
+ const has = agentOf(name, config);
152
+ if (has !== agent)
153
+ fail(`${name} is a ${adapter(has).label} profile, but ${key} is for ${adapter(agent).label}`);
154
+ return name;
155
+ };
156
+ const roles = /^(?:agents\.([a-z]+)\.)?(system|default|fallback)$/.exec(key);
157
+ if (roles) {
158
+ if (key === "system" && (value === "" || raw === '""'))
159
+ return "";
160
+ const agent = roles[1] ?? DEFAULT_AGENT;
161
+ if (!isAgentId(agent))
162
+ fail(`unknown agent '${agent}'`);
163
+ return profile(value, agent);
164
+ }
165
+ const prof = /^profiles\.([^.]+)\.(color|browser)$/.exec(key);
166
+ if (prof) {
167
+ if (!listProfiles(loadConfig(env), env).includes(prof[1]))
168
+ fail(`no profile '${prof[1]}' (turno profile list)`);
169
+ if (prof[2] === "color")
170
+ return parseColor(raw, key);
171
+ if (raw !== "chrome" && raw !== "default")
172
+ fail(`${key} must be chrome or default`);
173
+ return raw;
174
+ }
175
+ switch (key) {
176
+ case "icons":
177
+ if (raw !== "auto" && raw !== "nerd" && raw !== "unicode")
178
+ fail("icons must be auto, nerd or unicode");
179
+ return raw;
180
+ case "update_check":
181
+ case "hints":
182
+ if (typeof value !== "boolean")
183
+ fail(`${key} must be true or false`);
184
+ return value;
185
+ case "mcpd.port":
186
+ if (typeof value !== "number" || value < 1024 || value > 65535)
187
+ fail("mcpd.port must be an integer between 1024 and 65535");
188
+ return value;
189
+ case "mcpd.max_request_body": {
190
+ const problem = requestBodyProblem(value);
191
+ if (problem)
192
+ fail(problem);
193
+ return value;
194
+ }
195
+ case "mcpd.idle_under_pressure":
196
+ if (parseIdleUnderPressure(value) === undefined)
197
+ fail(IDLE_UNDER_PRESSURE_PROBLEM);
198
+ return value;
199
+ case "nerd_terminals":
200
+ if (!Array.isArray(value))
201
+ fail('nerd_terminals must be a list, like ["warp", "vscode"]');
202
+ return value;
203
+ case "open.chrome_dir":
204
+ return raw;
205
+ }
206
+ return value;
207
+ }
208
+ const SET_SPEC = { ...DRY_RUN };
89
209
  async function set(args, io) {
90
- const p = parseFlags(args, DRY_RUN, 2);
210
+ const p = parseFlags(args, SET_SPEC, 2);
91
211
  const [key, raw] = p.positionals;
92
212
  if (!key || raw === undefined)
93
213
  return fail("usage: turno config set <key> <value>");
94
214
  const k = splitKey(key);
215
+ const value = checkValue(key, raw, io.env);
95
216
  const dry = bool(p, "dry-run");
96
217
  const journal = new Journal(io.env, `config set ${key}`, dry);
97
- const { changed } = editConfig(io.env, journal, (t) => setValue(t, k.table, k.key, parseValue(raw)));
98
- io.out(`${key} = ${JSON.stringify(parseValue(raw))}${changed ? "" : " (unchanged)"}${dry ? " (dry run)" : ""}`);
218
+ const { changed } = editConfig(io.env, journal, (t) => setValue(t, k.table, k.key, value));
219
+ const line = `${key} = ${JSON.stringify(value)}`;
220
+ io.out(`${colors(io) ? highlightToml(line) : line}${changed ? "" : " (unchanged)"}${dry ? " (dry run)" : ""}`);
221
+ if (/(^|\.)fallback$/.test(key))
222
+ io.out('fallback is opt-in: read "Vendor terms" in the README before relying on it.');
99
223
  if (journal.hint())
100
224
  io.out(journal.hint());
101
225
  return 0;
@@ -146,23 +270,61 @@ async function check(args, io) {
146
270
  io.out(`${paint(io, "FAIL", "31")} ${err.message}`);
147
271
  }
148
272
  };
149
- one(pp.configFile, () => loadConfig(io.env));
273
+ const problems = [];
274
+ one(pp.configFile, () => problems.push(...configProblems(loadConfig(io.env), io.env)));
275
+ for (const w of problems)
276
+ io.out(`${paint(io, "warn", "33")} ${w}`);
150
277
  one(pp.mcpFile, () => loadManifest(io.env));
151
278
  one(pp.accountsFile, () => loadRegistry(io.env));
152
279
  return failed ? 1 : 0;
153
280
  }
154
281
  export const command = group("config", "read and change config.toml without losing its comments; check every config file", {
155
- path: { summary: "where each config and state file lives", synopsis: "[--json]", flags: ["--json"], run: path },
156
- get: { summary: "print a value (the whole file as JSON without a key)", synopsis: "[key] [--json]", args: ["key"], flags: ["--json"], run: get },
157
- set: { summary: "set a value; the file must still parse", synopsis: "<key> <value> [--dry-run]", args: ["key", "any"], flags: ["--dry-run"], run: set },
158
- unset: { summary: "remove a value", synopsis: "<key> [--dry-run]", args: ["key"], flags: ["--dry-run"], run: unset },
282
+ path: {
283
+ summary: "where each config and state file lives (--all: every path turno uses)",
284
+ synopsis: "[--all] [--json]",
285
+ flags: flagsOf(PATH_FLAGS),
286
+ json: PATH_JSON,
287
+ details: "--all adds the logs, tokens, caches, service file, launchers, each agent's\nfolder and each profile's folder and launcher, with what turno keeps there.\nThe paths only, never what is in them.",
288
+ run: path,
289
+ },
290
+ get: {
291
+ summary: "print a value (the whole file as JSON without a key)",
292
+ synopsis: "[key] [--json]",
293
+ args: ["key"],
294
+ flags: ["--json"],
295
+ run: get,
296
+ },
297
+ set: {
298
+ summary: "set a value, checked like profile add checks it",
299
+ synopsis: "<key> <value> [--dry-run]",
300
+ args: ["key", "any"],
301
+ flags: flagsOf(SET_SPEC),
302
+ run: set,
303
+ },
304
+ unset: {
305
+ summary: "remove a value",
306
+ synopsis: "<key> [--dry-run]",
307
+ args: ["key"],
308
+ flags: ["--dry-run"],
309
+ run: unset,
310
+ },
159
311
  edit: { summary: "open config.toml in $VISUAL or $EDITOR, then check it", run: edit },
160
312
  check: { summary: "parse config.toml, mcp.toml and accounts.toml", run: check },
161
313
  }, {
162
314
  fallback: "path",
163
- footer: `Keys:\n${Object.entries(KEYS)
164
- .map(([k, d]) => ` ${k.padEnd(26)} ${d}`)
165
- .join("\n")}\n\nProjects use turno profile assign; MCP servers live in mcp.toml (turno mcp).`,
315
+ footer: `Keys:\n${columns(Object.entries(KEYS), 2, 26)}\n\nProjects use turno profile assign; MCP servers live in mcp.toml (turno mcp).
316
+ A [[projects]] rule with mcp = [...] limits the servers of that folder.`,
317
+ examples: [
318
+ "turno config path --json",
319
+ "turno config path --all",
320
+ "turno config get default",
321
+ "turno config get mcpd --json",
322
+ "turno config set default work",
323
+ "turno config set icons unicode --dry-run",
324
+ "turno config unset fallback",
325
+ "turno config edit",
326
+ "turno config check",
327
+ ],
166
328
  });
167
329
  export const CONFIG_KEYS = Object.keys(KEYS);
168
330
  //# sourceMappingURL=config.js.map
@@ -0,0 +1,321 @@
1
+ import { spawn } from "node:child_process";
2
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { Journal } from "../../core/journal.js";
7
+ import { paths } from "../../core/paths.js";
8
+ import { literal, setValue } from "../../core/toml-edit.js";
9
+ import { bool, parseFlags } from "../args.js";
10
+ import { profileColor, stripAnsi, style } from "../style.js";
11
+ import { findOnPath } from "../launchers.js";
12
+ import { setupProfiles } from "./setup.js";
13
+ import { pidAlive } from "../../core/fsutil.js";
14
+ /**
15
+ * `turno demo`: turno in a throwaway HOME under the OS temp folder, with two Claude
16
+ * Code profiles, a folder rule, two MCP servers behind an mcpd on a free port, and the status
17
+ * line. It never reads or writes the person's own HOME, never signs in, needs no global install
18
+ * (it works from npx's cache), and always stops mcpd and removes the folder when it ends.
19
+ */
20
+ const PREFIX = "turno-demo-";
21
+ /** A file in every demo HOME with the PID of the demo that owns it. */
22
+ const OWNER = ".turno-demo";
23
+ /** Variables a demo session keeps from the caller: terminal and locale, never config or tokens. */
24
+ const KEEP = [
25
+ "PATH",
26
+ "TERM",
27
+ "COLORTERM",
28
+ "TERM_PROGRAM",
29
+ "LANG",
30
+ "LC_ALL",
31
+ "LC_CTYPE",
32
+ "TMPDIR",
33
+ "USER",
34
+ "LOGNAME",
35
+ "SHELL",
36
+ "COLUMNS",
37
+ "NO_COLOR",
38
+ ];
39
+ /** The env of everything that runs inside the demo: the demo HOME, its launchers first on PATH. */
40
+ export function demoEnv(base, home) {
41
+ const env = {};
42
+ for (const k of KEEP)
43
+ if (base[k] !== undefined)
44
+ env[k] = base[k];
45
+ env.HOME = home;
46
+ env.PATH = `${join(home, ".local", "bin")}:${base.PATH ?? "/usr/bin:/bin"}`;
47
+ env.TURNO_NO_UPDATE_CHECK = "1";
48
+ return env;
49
+ }
50
+ const PROFILES = [
51
+ { name: "work", color: "violet", folder: "code/acme" },
52
+ { name: "personal", color: "green", folder: "code/personal-site" },
53
+ ];
54
+ const SERVERS = ["docs", "issues"];
55
+ /** Remove demo HOMEs left by a demo that was killed (SIGKILL, power loss): their owner is gone. */
56
+ function removeStale(tmp) {
57
+ let names = [];
58
+ try {
59
+ names = readdirSync(tmp);
60
+ }
61
+ catch {
62
+ return;
63
+ }
64
+ for (const n of names) {
65
+ if (!n.startsWith(PREFIX))
66
+ continue;
67
+ const dir = join(tmp, n);
68
+ let pid = 0;
69
+ try {
70
+ pid = Number.parseInt(readFileSync(join(dir, OWNER), "utf8"), 10);
71
+ }
72
+ catch {
73
+ continue; // not made by turno demo: never touched
74
+ }
75
+ if (pid > 0 && !pidAlive(pid))
76
+ rmSync(dir, { recursive: true, force: true });
77
+ }
78
+ }
79
+ /** An Io that keeps the output of the steps the demo runs for itself. */
80
+ function quietIo(env) {
81
+ const text = [];
82
+ return { env, isTty: false, text, out: (l = "") => text.push(l), err: (l = "") => text.push(l) };
83
+ }
84
+ /** A single-quoted POSIX shell word. */
85
+ const sq = (s) => `'${s.replace(/'/g, "'\\''")}'`;
86
+ function write(file, text, mode = 0o600) {
87
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
88
+ writeFileSync(file, text, { mode });
89
+ chmodSync(file, mode);
90
+ }
91
+ function manifestText(server) {
92
+ const lines = ["# turno demo: two MCP servers behind the gateway. Each starts on first use and stops when idle.", ""];
93
+ for (const name of SERVERS) {
94
+ lines.push(`[server.${name}]`, `command = ${literal(server.command)}`, `args = ${literal([...server.args, name])}`, 'scope = "shared"', "");
95
+ }
96
+ // The same server, another account: the work profile gets its own process.
97
+ lines.push("[server.issues.variant.work]", 'env = { DEMO_ACCOUNT = "work" }', "");
98
+ return lines.join("\n");
99
+ }
100
+ function configText() {
101
+ const lines = [
102
+ "# turno demo: ~/code/acme opens with the work profile, every other folder with personal.",
103
+ 'default = "personal"',
104
+ 'icons = "unicode"',
105
+ "",
106
+ ];
107
+ for (const p of PROFILES)
108
+ lines.push(`[profiles.${p.name}]`, `color = "${p.color}"`, "");
109
+ lines.push("[[projects]]", 'path = "~/code/acme"', 'profile = "work"', "");
110
+ return lines.join("\n");
111
+ }
112
+ function samplePayload(home, folder, now) {
113
+ return {
114
+ session_id: "turno-demo",
115
+ model: { display_name: "Opus" },
116
+ workspace: { current_dir: join(home, folder), project_dir: join(home, folder) },
117
+ cost: { total_cost_usd: 0.42, total_lines_added: 120, total_lines_removed: 18 },
118
+ context_window: { used_percentage: 23, total_input_tokens: 46_000, context_window_size: 200_000 },
119
+ rate_limits: {
120
+ five_hour: { used_percentage: 38, resets_at: Math.trunc(now) + 2 * 3600 },
121
+ seven_day: { used_percentage: 12, resets_at: Math.trunc(now) + 4 * 86400 },
122
+ },
123
+ };
124
+ }
125
+ /** Build the demo HOME and start its gateway. The caller must call stop(). */
126
+ export async function startDemo(io, opts = {}) {
127
+ const tmp = realpathSync(opts.tmp ?? tmpdir());
128
+ removeStale(tmp);
129
+ const home = mkdtempSync(join(tmp, PREFIX));
130
+ writeFileSync(join(home, OWNER), `${process.pid}\n`);
131
+ let daemon;
132
+ let stopped = false;
133
+ // Last resort if the process ends without stop() (an uncaught error): the files still go.
134
+ const onExit = () => rmSync(home, { recursive: true, force: true });
135
+ process.on("exit", onExit);
136
+ const stop = async () => {
137
+ if (stopped)
138
+ return;
139
+ stopped = true;
140
+ try {
141
+ await daemon?.stop();
142
+ }
143
+ finally {
144
+ rmSync(home, { recursive: true, force: true });
145
+ process.off("exit", onExit);
146
+ }
147
+ };
148
+ try {
149
+ const env = demoEnv(io.env, home);
150
+ const p = paths(env);
151
+ const here = dirname(fileURLToPath(import.meta.url));
152
+ const entry = opts.entry ?? join(here, "..", "main.js");
153
+ const server = opts.server ?? { command: process.execPath, args: [join(here, "..", "..", "demo", "server.js")] };
154
+ const shim = join(p.bin, "turno");
155
+ write(shim, `#!/bin/sh\n# turno demo: the turno that started this demo\nexec ${sq(process.execPath)} ${sq(entry)} "$@"\n`, 0o755);
156
+ write(join(home, ".zshrc"), "# turno demo\nPROMPT='%F{magenta}turno demo%f %~ %# '\n");
157
+ write(join(home, ".bashrc"), "# turno demo\nPS1='turno demo \\w \\$ '\n");
158
+ // The hub settings.json is linked into every profile, so both draw turno's status line.
159
+ write(join(p.hub, "settings.json"), `${JSON.stringify({ statusLine: { type: "command", command: `${JSON.stringify(shim)} statusline`, padding: 0 } }, null, 2)}\n`);
160
+ for (const f of PROFILES)
161
+ mkdirSync(join(home, f.folder), { recursive: true });
162
+ write(p.mcpFile, manifestText(server));
163
+ write(p.configFile, configText());
164
+ const quiet = quietIo(env);
165
+ setupProfiles(PROFILES.map((f) => f.name), quiet, { turno: sq(shim), journal: new Journal(env, "demo setup") });
166
+ const { startDaemon } = await import("../../mcpd/daemon.js");
167
+ daemon = await startDaemon({ env, port: 0 });
168
+ const port = daemon.port;
169
+ write(p.configFile, setValue(configText(), "mcpd", "port", port));
170
+ const { command: mcp } = await import("./mcp.js");
171
+ if ((await mcp.run(["sync"], quiet)) !== 0)
172
+ throw new Error(`mcp sync failed in the demo:\n${quiet.text.join("\n")}`);
173
+ // The status line without its background workers: a known plan, a gateway known to answer.
174
+ const now = Date.now() / 1000;
175
+ write(join(p.planDir, "work"), "max");
176
+ write(join(p.planDir, "personal"), "pro");
177
+ write(join(p.state, "cache", "mcpd-health.json"), JSON.stringify({ ok: true, port, checked_at: Math.trunc(now) + 10 * 365 * 86400 }));
178
+ write(join(home, "statusline.json"), `${JSON.stringify(samplePayload(home, PROFILES[0].folder, now), null, 2)}\n`);
179
+ const { collect } = await import("./statusline.js");
180
+ const { render } = await import("../../statusline/render.js");
181
+ const statusLines = PROFILES.map((f) => render(collect(samplePayload(home, f.folder, now), { ...env, CLAUDE_CONFIG_DIR: join(home, `.claude-${f.name}`) }, now, [])).replace(/\n$/, ""));
182
+ return { home, env, port, statusLines, stop };
183
+ }
184
+ catch (err) {
185
+ await stop();
186
+ throw err;
187
+ }
188
+ }
189
+ function intro(io, d) {
190
+ const s = style(io);
191
+ io.out(s.wrap(`${s.bold(s.accent("turno demo"))} `, s.muted(`a throwaway HOME at ${d.home}`)));
192
+ io.out("");
193
+ io.out(s.header("Set up"));
194
+ const colors = Object.fromEntries(PROFILES.map((p) => [p.name, { color: p.color }]));
195
+ const [work, personal] = PROFILES.map((p) => s.profile(p.name, profileColor(colors, p.name)));
196
+ io.out(s.kv("profiles", `${work} for ~/code/acme, ${personal} for every other folder ${s.muted("(Claude Code)")}`, 8));
197
+ io.out(s.kv("gateway", `${s.lead("on", "mcpd")} on 127.0.0.1:${d.port} ${s.muted("with docs and issues, synced into both profiles")}`, 8));
198
+ io.out(s.kv("status", s.muted("the line Claude Code draws for each profile:"), 8));
199
+ io.out("");
200
+ for (const l of d.statusLines)
201
+ io.out(s.color ? l : stripAnsi(l));
202
+ io.out("");
203
+ io.out(s.header("Try"));
204
+ const rows = [
205
+ ["turno status", "the one-screen summary"],
206
+ ["turno profile which ~/code/acme", "which account a folder opens with, and why"],
207
+ ["turno mcp list", "the servers behind the gateway"],
208
+ ["cat ~/.claude-work/.claude.json", "the gateway entries turno mcp sync wrote"],
209
+ ["CLAUDE_CONFIG_DIR=~/.claude-work turno statusline < ~/statusline.json", "draw the work status line yourself"],
210
+ ["turno undo --list", "every change turno made, each one undoable"],
211
+ ];
212
+ if (findOnPath("claude", d.env))
213
+ rows.push([
214
+ "cd ~/code/acme && turno auto mcp list",
215
+ "Claude Code connects to both servers through mcpd (no sign-in)",
216
+ ]);
217
+ // Commands up to 40 columns share one column; a longer one puts its note on the next line.
218
+ const w = Math.max(...rows.map(([c]) => c.length).filter((n) => n <= 40));
219
+ for (const [c, why] of rows) {
220
+ if (c.length > w)
221
+ io.out(` ${s.bold(c)}\n${s.wrap(` ${" ".repeat(w)} `, s.muted(why))}`);
222
+ else
223
+ io.out(s.wrap(` ${s.bold(c.padEnd(w))} `, s.muted(why)));
224
+ }
225
+ io.out("");
226
+ io.out(s.muted("Nothing here reads or changes your own HOME, and nothing signs in."));
227
+ }
228
+ const USAGE = `Usage: turno demo [--keep] [-- <command> [args...]]
229
+
230
+ Try turno without touching your setup. The demo builds a throwaway HOME under the temp folder
231
+ with two Claude Code profiles (work, personal), a folder rule, two MCP servers behind an mcpd on
232
+ a free port, and the status line. It never signs in.
233
+
234
+ In a terminal it opens a shell in that HOME; exit the shell to end the demo. With a command after
235
+ --, it runs that command in the demo instead. With --keep it waits for Ctrl-C instead, so you can
236
+ use the demo from another terminal. Without a terminal (a pipe, --no-input, an agent) and without
237
+ --keep it prints what it set up and ends. Either way it stops mcpd and removes the folder when it
238
+ ends. Works from npx: npx turno-cli demo
239
+
240
+ Examples:
241
+ $ turno demo
242
+ $ turno demo -- turno status`;
243
+ const KEEP_FLAG = { keep: { type: "boolean" } };
244
+ /** Run the demo: a shell, a command, or a wait for Ctrl-C. Returns the exit code. */
245
+ export async function runDemo(args, io, opts = {}) {
246
+ const end = args.indexOf("--");
247
+ const keep = bool(parseFlags(end < 0 ? args : args.slice(0, end), KEEP_FLAG, 0), "keep");
248
+ const cmd = end < 0 ? [] : args.slice(end + 1);
249
+ const d = await startDemo(io, opts);
250
+ let child;
251
+ let wake;
252
+ // Ctrl-C reaches a child in the foreground from the terminal; the demo waits for it to end.
253
+ // SIGTERM and SIGHUP (the terminal closed) end the child, then the demo cleans up.
254
+ const onSignal = (sig) => {
255
+ if (!child)
256
+ return wake?.();
257
+ if (sig === "SIGINT")
258
+ return;
259
+ child.kill(cmd.length ? sig : "SIGHUP");
260
+ setTimeout(() => child?.kill("SIGKILL"), 3000).unref();
261
+ };
262
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
263
+ for (const s of signals)
264
+ process.on(s, onSignal);
265
+ const onAbort = () => wake?.();
266
+ opts.signal?.addEventListener("abort", onAbort);
267
+ try {
268
+ if (cmd.length) {
269
+ io.err(`turno demo: running ${cmd.join(" ")} in a throwaway HOME at ${d.home} (mcpd on 127.0.0.1:${d.port})`);
270
+ return await runChild(cmd[0], cmd.slice(1), d, (c) => (child = c));
271
+ }
272
+ intro(io, d);
273
+ io.out("");
274
+ if (io.ask && !keep) {
275
+ io.out("Opening a shell in the demo HOME. Type exit to end the demo; it then stops mcpd and removes everything.");
276
+ const shell = d.env.SHELL || "/bin/sh";
277
+ return await runChild(shell, ["-i"], d, (c) => (child = c));
278
+ }
279
+ if (!keep) {
280
+ // Nobody can open the shell or press Ctrl-C here: show what the demo holds and end it.
281
+ io.out(style(io).wrap("", style(io).muted("No terminal here (a pipe, --no-input or an agent), so the demo ends now. Run a command in it with turno demo -- turno status, or pass --keep to keep it until Ctrl-C.")));
282
+ return 0;
283
+ }
284
+ io.out(`From another terminal: export HOME=${d.home} PATH=${d.home}/.local/bin:$PATH`);
285
+ io.out("Press Ctrl-C to stop the demo and remove it.");
286
+ await new Promise((resolve) => {
287
+ wake = resolve;
288
+ if (opts.signal?.aborted)
289
+ resolve();
290
+ });
291
+ return 0;
292
+ }
293
+ finally {
294
+ for (const s of signals)
295
+ process.off(s, onSignal);
296
+ opts.signal?.removeEventListener("abort", onAbort);
297
+ await d.stop();
298
+ io.err(`turno demo: stopped mcpd and removed ${d.home}`);
299
+ }
300
+ }
301
+ function runChild(file, args, d, track) {
302
+ return new Promise((resolve) => {
303
+ const c = spawn(file, args, { stdio: "inherit", env: d.env, cwd: d.home });
304
+ track(c);
305
+ c.once("error", (err) => {
306
+ process.stderr.write(`turno demo: cannot run ${file}: ${err.message}\n`);
307
+ resolve(127);
308
+ });
309
+ c.once("exit", (code, signal) => resolve(code ?? (signal ? 128 + (signalNumber(signal) ?? 1) : 1)));
310
+ });
311
+ }
312
+ function signalNumber(signal) {
313
+ return { SIGHUP: 1, SIGINT: 2, SIGKILL: 9, SIGTERM: 15 }[signal];
314
+ }
315
+ export const command = {
316
+ summary: "try turno in a throwaway HOME: two profiles, a gateway and the status line (removed on exit)",
317
+ usage: USAGE,
318
+ flags: ["--keep"],
319
+ run: (args, io) => runDemo(args, io),
320
+ };
321
+ //# sourceMappingURL=demo.js.map