turno-cli 0.2.0 → 0.4.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 (116) hide show
  1. package/CHANGELOG.md +266 -0
  2. package/README.md +134 -42
  3. package/dist/accounts/audit.js +27 -15
  4. package/dist/accounts/builtin.js +35 -7
  5. package/dist/accounts/delegate.js +30 -7
  6. package/dist/accounts/policy.js +4 -2
  7. package/dist/accounts/registry.js +3 -1
  8. package/dist/agents/adapter.js +22 -0
  9. package/dist/agents/claude.js +54 -3
  10. package/dist/agents/codex.js +94 -6
  11. package/dist/agents/copilot.js +19 -2
  12. package/dist/agents/cursor.js +19 -2
  13. package/dist/agents/index.js +1 -1
  14. package/dist/agents/snippets.js +37 -10
  15. package/dist/cli/args.js +32 -15
  16. package/dist/cli/commands/accounts.js +29 -7
  17. package/dist/cli/commands/auto.js +50 -12
  18. package/dist/cli/commands/browser-do-session.js +170 -0
  19. package/dist/cli/commands/browser-do.js +740 -0
  20. package/dist/cli/commands/browser-flows.js +300 -0
  21. package/dist/cli/commands/browser-identity.js +952 -0
  22. package/dist/cli/commands/browser-live.js +118 -0
  23. package/dist/cli/commands/browser-session.js +102 -0
  24. package/dist/cli/commands/browser-vault.js +193 -0
  25. package/dist/cli/commands/browser.js +303 -62
  26. package/dist/cli/commands/complete.js +13 -3
  27. package/dist/cli/commands/completion.js +4 -0
  28. package/dist/cli/commands/config.js +90 -13
  29. package/dist/cli/commands/demo.js +36 -7
  30. package/dist/cli/commands/doctor.js +170 -36
  31. package/dist/cli/commands/identity.js +101 -12
  32. package/dist/cli/commands/init.js +42 -10
  33. package/dist/cli/commands/limit.js +65 -9
  34. package/dist/cli/commands/mcp-call.js +240 -0
  35. package/dist/cli/commands/mcp-oauth.js +33 -6
  36. package/dist/cli/commands/mcp-observe.js +128 -23
  37. package/dist/cli/commands/mcp-share.js +201 -0
  38. package/dist/cli/commands/mcp.js +203 -42
  39. package/dist/cli/commands/mcpd.js +76 -12
  40. package/dist/cli/commands/open.js +26 -3
  41. package/dist/cli/commands/profile.js +212 -30
  42. package/dist/cli/commands/resolve.js +8 -1
  43. package/dist/cli/commands/run.js +24 -4
  44. package/dist/cli/commands/secret.js +23 -38
  45. package/dist/cli/commands/session.js +16 -5
  46. package/dist/cli/commands/sessions.js +7 -1
  47. package/dist/cli/commands/setup.js +83 -11
  48. package/dist/cli/commands/status.js +67 -15
  49. package/dist/cli/commands/statusline.js +7 -2
  50. package/dist/cli/commands/ui.js +17 -5
  51. package/dist/cli/commands/undo.js +39 -7
  52. package/dist/cli/commands/uninstall.js +24 -5
  53. package/dist/cli/commands/upgrade.js +113 -76
  54. package/dist/cli/commands/usage.js +11 -10
  55. package/dist/cli/commands/version.js +20 -8
  56. package/dist/cli/commands/which.js +5 -3
  57. package/dist/cli/diagnostics.js +184 -0
  58. package/dist/cli/exit.js +65 -0
  59. package/dist/cli/group.js +20 -8
  60. package/dist/cli/help.js +6 -1
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +24 -8
  63. package/dist/cli/launch.js +31 -2
  64. package/dist/cli/launchers.js +25 -10
  65. package/dist/cli/main.js +52 -18
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +17 -5
  69. package/dist/cli/registry.js +20 -2
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +31 -9
  73. package/dist/cli/style.js +35 -5
  74. package/dist/cli/topics.js +155 -0
  75. package/dist/core/config.js +39 -3
  76. package/dist/core/fsutil.js +2 -10
  77. package/dist/core/journal.js +19 -11
  78. package/dist/core/manifest.js +28 -1
  79. package/dist/core/paths.js +6 -112
  80. package/dist/core/profiles.js +28 -8
  81. package/dist/core/resolve.js +13 -3
  82. package/dist/core/secrets.js +4 -154
  83. package/dist/core/state-file.js +107 -0
  84. package/dist/core/update.js +14 -11
  85. package/dist/core/version.js +57 -10
  86. package/dist/demo/server.js +10 -2
  87. package/dist/mcpd/cache.js +6 -7
  88. package/dist/mcpd/calllog.js +10 -9
  89. package/dist/mcpd/client-names.js +8 -13
  90. package/dist/mcpd/connectors.js +42 -3
  91. package/dist/mcpd/daemon.js +29 -8
  92. package/dist/mcpd/folder-sets.js +5 -2
  93. package/dist/mcpd/gateway.js +57 -29
  94. package/dist/mcpd/health.js +70 -26
  95. package/dist/mcpd/importer.js +106 -9
  96. package/dist/mcpd/instances.js +70 -32
  97. package/dist/mcpd/jsonrpc.js +3 -1
  98. package/dist/mcpd/middleware.js +156 -0
  99. package/dist/mcpd/modern.js +57 -19
  100. package/dist/mcpd/oauth.js +71 -17
  101. package/dist/mcpd/peerpid.js +63 -17
  102. package/dist/mcpd/pressure.js +4 -1
  103. package/dist/mcpd/rss.js +34 -19
  104. package/dist/mcpd/service.js +28 -4
  105. package/dist/mcpd/share.js +217 -0
  106. package/dist/mcpd/state.js +16 -16
  107. package/dist/mcpd/sync.js +22 -12
  108. package/dist/mcpd/systemd.js +4 -1
  109. package/dist/mcpd/tokens.js +4 -8
  110. package/dist/mcpd/upstream.js +12 -5
  111. package/dist/statusline/cost.js +17 -4
  112. package/dist/statusline/input.js +15 -3
  113. package/dist/ui/fonts.js +1 -1
  114. package/dist/ui/settings.js +6 -1
  115. package/npm-shrinkwrap.json +12 -3
  116. package/package.json +7 -6
@@ -0,0 +1,217 @@
1
+ /**
2
+ * `turno mcp export` and `turno mcp import <file>`: mcp.toml without secret values, and merging
3
+ * such a file (or another agent's MCP config) into mcp.toml. An exported file names each secret
4
+ * by its `keychain:` or `env:` reference; literal secrets become `keychain:turno/<server>/<key>`
5
+ * references that the importing machine fills with `turno secret set`.
6
+ */
7
+ import { parse, stringify } from "smol-toml";
8
+ import { parseManifest } from "../core/manifest.js";
9
+ import { argSecrets, isSecretValue, serviceKey, urlSecrets } from "./importer.js";
10
+ const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /**
12
+ * mcp.toml text without secret values. With `profile`, only the servers that profile gets and
13
+ * only its own variant. Comments are not kept (the file is generated).
14
+ */
15
+ export function exportManifest(text, opts = {}) {
16
+ const manifest = parseManifest(text); // refuse to export a file mcpd would refuse
17
+ const raw = parse(text);
18
+ const table = isTable(raw.server) ? raw.server : {};
19
+ const keychain = new Set();
20
+ const envVars = new Set();
21
+ const moved = [];
22
+ const redacted = [];
23
+ const out = {};
24
+ const refOf = (v) => {
25
+ if (v.startsWith("keychain:"))
26
+ keychain.add(v.slice("keychain:".length));
27
+ else if (v.startsWith("env:"))
28
+ envVars.add(v.slice(4).replace(/:-.*$/, ""));
29
+ };
30
+ /** env and headers: references stay, literal secrets become references. */
31
+ const values = (server, scope, map) => {
32
+ if (!isTable(map))
33
+ return undefined;
34
+ const next = {};
35
+ for (const [k, v] of Object.entries(map)) {
36
+ if (typeof v !== "string") {
37
+ next[k] = v;
38
+ continue;
39
+ }
40
+ if (v.startsWith("keychain:") || v.startsWith("env:")) {
41
+ refOf(v);
42
+ next[k] = v;
43
+ }
44
+ else if (!v.includes("${") && isSecretValue(k, v)) {
45
+ const service = `turno/${scope}/${serviceKey(k)}`;
46
+ keychain.add(service);
47
+ moved.push(`${server}.${k}`);
48
+ next[k] = `keychain:${service}`;
49
+ }
50
+ else
51
+ next[k] = v;
52
+ }
53
+ return next;
54
+ };
55
+ const scrub = (server, scope, t) => {
56
+ const next = { ...t };
57
+ for (const key of ["env", "headers"]) {
58
+ const v = values(server, scope, t[key]);
59
+ if (v)
60
+ next[key] = v;
61
+ }
62
+ if (Array.isArray(t.args)) {
63
+ const args = t.args.map(String);
64
+ const found = argSecrets(args);
65
+ if (found.length) {
66
+ next.args = args.map((a) => found.reduce((s, f) => s.split(f).join("<secret>"), a));
67
+ redacted.push(`${server}.args`);
68
+ }
69
+ }
70
+ if (typeof t.url === "string") {
71
+ const found = urlSecrets(t.url);
72
+ if (found.length) {
73
+ let url = t.url;
74
+ for (const f of found)
75
+ url = url.split(f).join("<secret>").split(encodeURIComponent(f)).join("<secret>");
76
+ next.url = url;
77
+ redacted.push(`${server}.url`);
78
+ }
79
+ }
80
+ if (isTable(t.oauth) && typeof t.oauth.client_secret === "string")
81
+ refOf(t.oauth.client_secret);
82
+ return next;
83
+ };
84
+ for (const [name, value] of Object.entries(table)) {
85
+ if (!isTable(value))
86
+ continue;
87
+ const def = manifest.servers[name];
88
+ if (opts.profile && !def.profiles.includes("*") && !def.profiles.includes(opts.profile))
89
+ continue;
90
+ const server = scrub(name, name, value);
91
+ if (isTable(value.variant)) {
92
+ const variants = {};
93
+ for (const [prof, v] of Object.entries(value.variant)) {
94
+ if (opts.profile && prof !== opts.profile)
95
+ continue;
96
+ if (isTable(v))
97
+ variants[prof] = scrub(`${name}.variant.${prof}`, `${name}/${prof}`, v);
98
+ }
99
+ if (Object.keys(variants).length)
100
+ server.variant = variants;
101
+ else
102
+ delete server.variant;
103
+ }
104
+ out[name] = server;
105
+ }
106
+ const names = Object.keys(out);
107
+ const head = [
108
+ `# turno MCP servers, from \`${opts.command ?? "turno mcp export"}\`. No secret values: each secret is`,
109
+ "# a keychain: or env: reference. Import it with: turno mcp import <this file> --write",
110
+ ];
111
+ if (keychain.size) {
112
+ head.push("#", "# Store these secrets on the machine that imports it (the value on stdin):");
113
+ for (const s of [...keychain].sort())
114
+ head.push(`# turno secret set ${s}`);
115
+ }
116
+ if (envVars.size)
117
+ head.push("#", `# Variables mcpd reads from its environment: ${[...envVars].sort().join(", ")}`);
118
+ if (redacted.length)
119
+ head.push("#", `# Secrets replaced by <secret> (args and URLs cannot hold a reference): ${redacted.join(", ")}`);
120
+ const body = names.length ? `${stringify({ server: out })}\n` : "";
121
+ const result = `${head.join("\n")}\n\n${body}`;
122
+ parseManifest(result, "export"); // never print something import would refuse
123
+ return {
124
+ text: result,
125
+ servers: names,
126
+ keychain: [...keychain].sort(),
127
+ envVars: [...envVars].sort(),
128
+ moved,
129
+ redacted,
130
+ };
131
+ }
132
+ /** The parts of a TOML table header: `server."a.b".env` is server, a.b, env. */
133
+ function headerPath(inner) {
134
+ const parts = [];
135
+ const re = /\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*(?:\.|$)/y;
136
+ re.lastIndex = 0;
137
+ while (re.lastIndex < inner.length) {
138
+ const m = re.exec(inner);
139
+ if (!m)
140
+ break;
141
+ parts.push(m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : (m[2] ?? m[3]));
142
+ }
143
+ return parts;
144
+ }
145
+ const HEADER = /^\s*\[\[?\s*([^[\]#]+?)\s*\]\]?\s*(#.*)?$/;
146
+ /**
147
+ * Remove `[server.<name>]` and its sub-tables (`[server.<name>.env]`, variants, ...) from
148
+ * mcp.toml text, keeping the rest and its comments. Undefined when the server is defined some
149
+ * other way (an inline table, dotted keys under `[server]`) and the text has to be edited by hand.
150
+ */
151
+ export function removeServer(text, name) {
152
+ const lines = text.split("\n");
153
+ const keep = [];
154
+ let dropping = false;
155
+ for (const line of lines) {
156
+ const h = HEADER.exec(line);
157
+ if (h) {
158
+ const path = headerPath(h[1]);
159
+ dropping = path[0] === "server" && path[1] === name;
160
+ }
161
+ if (!dropping)
162
+ keep.push(line);
163
+ }
164
+ const next = keep.join("\n").replace(/\n{3,}/g, "\n\n");
165
+ try {
166
+ return parseManifest(next).servers[name] ? undefined : next;
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
171
+ }
172
+ /**
173
+ * Merge server tables into mcp.toml text: new names are appended, names already there are kept
174
+ * unless `force`, which replaces their tables. Throws when a server cannot be replaced in place.
175
+ */
176
+ export function mergeServers(existing, incoming, force) {
177
+ const current = existing.trim() ? parseManifest(existing).servers : {};
178
+ let text = existing;
179
+ const added = [];
180
+ const replaced = [];
181
+ const kept = [];
182
+ const append = {};
183
+ for (const [name, table] of Object.entries(incoming)) {
184
+ if (current[name]) {
185
+ if (!force) {
186
+ kept.push(name);
187
+ continue;
188
+ }
189
+ const next = removeServer(text, name);
190
+ if (next === undefined)
191
+ throw new Error(`cannot replace server ${name} in mcp.toml (it is not a [server.${name}] table); edit it by hand`);
192
+ text = next;
193
+ replaced.push(name);
194
+ }
195
+ else
196
+ added.push(name);
197
+ append[name] = table;
198
+ }
199
+ if (Object.keys(append).length) {
200
+ const trimmed = text.replace(/\s+$/, "");
201
+ text = `${trimmed}${trimmed ? "\n\n" : ""}${stringify({ server: append })}\n`;
202
+ }
203
+ parseManifest(text); // never write something mcpd cannot read back
204
+ return { text, added, replaced, kept };
205
+ }
206
+ /** The server tables of a file in mcp.toml's format (what `turno mcp export` prints). */
207
+ export function manifestServers(text, file) {
208
+ parseManifest(text, file);
209
+ const raw = parse(text);
210
+ const out = {};
211
+ if (isTable(raw.server))
212
+ for (const [n, v] of Object.entries(raw.server))
213
+ if (isTable(v))
214
+ out[n] = v;
215
+ return out;
216
+ }
217
+ //# sourceMappingURL=share.js.map
@@ -13,6 +13,7 @@ import { loadConfig, parseConfig } from "../core/config.js";
13
13
  import { pidAlive } from "../core/fsutil.js";
14
14
  import { atomicWrite } from "../core/journal.js";
15
15
  import { paths } from "../core/paths.js";
16
+ import { hasFields, readState } from "../core/state-file.js";
16
17
  /** Files mcpd keeps in the state folder besides `mcpd.token` and `mcpd.port`. */
17
18
  export function daemonFiles(env = process.env) {
18
19
  const p = paths(env);
@@ -33,7 +34,7 @@ function defaultWarn(message) {
33
34
  * folder). `read` returns it or undefined; `ensure` creates it when missing; `rotate` always
34
35
  * writes a new one. On read the file is checked with fstat: a mode wider than 600 is fixed (or
35
36
  * reported when it cannot be), and a file owned by another user is reported. The token is
36
- * never printed. Per-profile tokens derive from this one (mcpd/tokens.ts, ADR 0023).
37
+ * never printed. Per-profile tokens derive from this one (mcpd/tokens.ts).
37
38
  */
38
39
  export function masterToken(env = process.env, mode = "ensure", warn = defaultWarn) {
39
40
  const file = paths(env).mcpdToken;
@@ -91,14 +92,10 @@ export function readToken(env = process.env, warn) {
91
92
  export function rotateToken(env = process.env) {
92
93
  return masterToken(env, "rotate");
93
94
  }
95
+ const isLockInfo = (v) => hasFields(v, { pid: "number" }) && Number.isInteger(v.pid) && v.pid > 0;
96
+ /** The lock file, or undefined when there is none or it is not a lock (state-file.ts). */
94
97
  export function readLock(env = process.env) {
95
- try {
96
- const v = JSON.parse(readFileSync(daemonFiles(env).lock, "utf8"));
97
- return Number.isInteger(v.pid) && v.pid > 0 ? v : undefined;
98
- }
99
- catch {
100
- return undefined;
101
- }
98
+ return readState(daemonFiles(env).lock, isLockInfo);
102
99
  }
103
100
  /** Whether `pid` runs mcpd: alive and, when ps can tell, its command line is `... mcp daemon run` (or `mcpd run`). */
104
101
  export function isMcpdProcess(pid) {
@@ -107,7 +104,11 @@ export function isMcpdProcess(pid) {
107
104
  if (!pidAlive(pid))
108
105
  return false;
109
106
  try {
110
- const cmd = execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
107
+ const cmd = execFileSync("ps", ["-o", "command=", "-p", String(pid)], {
108
+ encoding: "utf8",
109
+ timeout: 2000,
110
+ stdio: ["ignore", "pipe", "ignore"],
111
+ });
111
112
  return /\b(mcpd|daemon) run\b/.test(cmd);
112
113
  }
113
114
  catch {
@@ -157,20 +158,19 @@ export function mcpdPort(env = process.env) {
157
158
  }
158
159
  return loadConfigSafe(env).config.mcpd.port;
159
160
  }
161
+ const isStartError = (v) => hasFields(v, { at: "string", message: "string" });
160
162
  export function readStartError(env = process.env) {
161
- try {
162
- return JSON.parse(readFileSync(daemonFiles(env).error, "utf8"));
163
- }
164
- catch {
165
- return undefined;
166
- }
163
+ return readState(daemonFiles(env).error, isStartError);
167
164
  }
168
165
  /** Whether our own mcpd answers /status on `port` with our token. */
169
166
  export async function answersAsMcpd(port, token) {
170
167
  if (!token)
171
168
  return undefined;
172
169
  try {
173
- const res = await fetch(`http://127.0.0.1:${port}/status`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(2000) });
170
+ const res = await fetch(`http://127.0.0.1:${port}/status`, {
171
+ headers: { authorization: `Bearer ${token}` },
172
+ signal: AbortSignal.timeout(2000),
173
+ });
174
174
  if (!res.ok)
175
175
  return undefined;
176
176
  const body = (await res.json());
package/dist/mcpd/sync.js CHANGED
@@ -8,9 +8,10 @@ import { servesProfile } from "../core/manifest.js";
8
8
  import { profileToken } from "./tokens.js";
9
9
  import { isObject, parseJsonObject } from "../core/fsutil.js";
10
10
  import { CliError } from "../cli/io.js";
11
+ import { isStringArray, readState, recordOf, requireState } from "../core/state-file.js";
11
12
  /**
12
- * A gateway entry in the format of each agent (ADR 0013, ADR 0032). Claude Code gets the
13
- * profile's token (ADR 0023) in the entry; the others read it, and the session PID, from the
13
+ * A gateway entry in the format of each agent. Claude Code gets the
14
+ * profile's token in the entry; the others read it, and the session PID, from the
14
15
  * launcher's environment.
15
16
  */
16
17
  export function gatewayEntryFor(agent, name, port, token, profile) {
@@ -20,7 +21,7 @@ export function gatewayEntryFor(agent, name, port, token, profile) {
20
21
  * The MCP entries a profile should have, according to the manifest. Remote servers that do not
21
22
  * go through the gateway are written as they are for agents that take them (Claude Code), and
22
23
  * skipped for the others (their formats differ; `turno mcp config` prints them). `master` is the gateway's
23
- * master token: entries carry the profile's own token derived from it (ADR 0023), never the
24
+ * master token: entries carry the profile's own token derived from it, never the
24
25
  * master itself.
25
26
  */
26
27
  export function profileServers(manifest, profile, port, master, agent = DEFAULT_AGENT) {
@@ -39,13 +40,17 @@ export function profileServers(manifest, profile, port, master, agent = DEFAULT_
39
40
  }
40
41
  return out;
41
42
  }
43
+ const isManaged = recordOf(isStringArray);
44
+ /**
45
+ * The entries turno wrote, before it removes any: a file that exists but cannot be read is a
46
+ * StateError (fix or remove it), never an empty list that would leave stale entries behind.
47
+ */
42
48
  export function readManaged(file) {
43
- try {
44
- return JSON.parse(readFileSync(file, "utf8"));
45
- }
46
- catch {
47
- return {};
48
- }
49
+ return requireState(file, isManaged) ?? {};
50
+ }
51
+ /** The same, empty when the file cannot be used: for checks that only read (doctor, the status line). */
52
+ export function peekManaged(file) {
53
+ return readState(file, isManaged) ?? {};
49
54
  }
50
55
  export function writeManaged(file, state) {
51
56
  mkdirSync(dirname(file), { recursive: true, mode: PRIVATE_DIR_MODE });
@@ -100,7 +105,7 @@ export function syncJsonServers(configFile, key, wanted, previouslyManaged, opts
100
105
  return res;
101
106
  }
102
107
  /**
103
- * Rewrite the servers of an agent config file in its store's format (ADR 0032): add or update
108
+ * Rewrite the servers of an agent config file in its store's format: add or update
104
109
  * `wanted`, remove entries turno wrote earlier that left it, keep everything else.
105
110
  */
106
111
  export function syncServers(configFile, store, wanted, previouslyManaged, opts = {}) {
@@ -122,7 +127,9 @@ function tomlValue(v) {
122
127
  if (Array.isArray(v))
123
128
  return `[${v.map(tomlValue).join(", ")}]`;
124
129
  if (v && typeof v === "object") {
125
- return `{ ${Object.entries(v).map(([k, x]) => `${tomlKey(k)} = ${tomlValue(x)}`).join(", ")} }`;
130
+ return `{ ${Object.entries(v)
131
+ .map(([k, x]) => `${tomlKey(k)} = ${tomlValue(x)}`)
132
+ .join(", ")} }`;
126
133
  }
127
134
  throw new Error(`cannot write ${String(v)} as TOML`);
128
135
  }
@@ -159,7 +166,10 @@ function syncTomlServers(configFile, key, wanted, previouslyManaged, opts) {
159
166
  const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
160
167
  // Drop the tables that go or change, from the bottom up so ranges stay valid.
161
168
  const drop = [...res.removed, ...res.updated];
162
- const ranges = [...serverTables(lines, key).entries()].filter(([n]) => drop.includes(n)).map(([, r]) => r).sort((a, b) => b[0] - a[0]);
169
+ const ranges = [...serverTables(lines, key).entries()]
170
+ .filter(([n]) => drop.includes(n))
171
+ .map(([, r]) => r)
172
+ .sort((a, b) => b[0] - a[0]);
163
173
  for (const [start, end] of ranges)
164
174
  lines.splice(start, end - start);
165
175
  for (const name of [...res.updated, ...res.added]) {
@@ -11,7 +11,10 @@ function quote(s) {
11
11
  return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
12
12
  }
13
13
  function unquote(s) {
14
- return s.replace(/\$\$/g, "$").replace(/%%/g, "%").replace(/\\(["\\])/g, "$1");
14
+ return s
15
+ .replace(/\$\$/g, "$")
16
+ .replace(/%%/g, "%")
17
+ .replace(/\\(["\\])/g, "$1");
15
18
  }
16
19
  /**
17
20
  * `systemd --user` unit that keeps `turno mcp daemon run` alive. Restart=on-failure: a clean
@@ -3,8 +3,9 @@ import { readFileSync, rmSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { atomicWrite } from "../core/journal.js";
5
5
  import { ensurePrivateDir, paths } from "../core/paths.js";
6
+ import { readState } from "../core/state-file.js";
6
7
  /**
7
- * Per-profile gateway tokens (ADR 0023). Each profile's agent config carries its own token,
8
+ * Per-profile gateway tokens. Each profile's agent config carries its own token,
8
9
  * derived from the master token so mcpd needs no list of them:
9
10
  *
10
11
  * tp1.<profile>.<base64url(HMAC-SHA256(master, "profile:" + profile))>
@@ -63,13 +64,8 @@ function syncedListFile(env) {
63
64
  return join(dirname(profileTokenFile("x", env)), "synced.json");
64
65
  }
65
66
  export function readSyncedTokenProfiles(env = process.env) {
66
- try {
67
- const v = JSON.parse(readFileSync(syncedListFile(env), "utf8"));
68
- return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
69
- }
70
- catch {
71
- return [];
72
- }
67
+ const v = readState(syncedListFile(env), (x) => Array.isArray(x));
68
+ return (v ?? []).filter((x) => typeof x === "string");
73
69
  }
74
70
  export function writeSyncedTokenProfiles(names, env = process.env) {
75
71
  const file = syncedListFile(env);
@@ -1,5 +1,5 @@
1
1
  import { LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js";
2
- import { ErrorCode, isNotification, isRequest, isResponse, rpcError } from "./jsonrpc.js";
2
+ import { ErrorCode, isNotification, isRequest, isResponse, rpcError, } from "./jsonrpc.js";
3
3
  /** Server-to-client requests and the client capability each needs. */
4
4
  const CLIENT_CAPABILITY = {
5
5
  "elicitation/create": "elicitation",
@@ -17,7 +17,7 @@ function sessionGone(err, hadSession) {
17
17
  * One running MCP server, spoken to over a raw transport. Request ids and progress tokens
18
18
  * are rewritten so several clients can share it without their messages crossing. Every
19
19
  * request it relays is settled exactly once: by the server's answer, a cancellation, a
20
- * timeout, the client going away, or the server stopping (ADR 0016).
20
+ * timeout, the client going away, or the server stopping.
21
21
  */
22
22
  export class Upstream {
23
23
  opts;
@@ -104,7 +104,12 @@ export class Upstream {
104
104
  }
105
105
  this.lastActivity = Date.now();
106
106
  return new Promise((resolve) => {
107
- const p = { resolve, method, ...(origin ? { origin } : {}), ...(originId !== undefined ? { originId } : {}) };
107
+ const p = {
108
+ resolve,
109
+ method,
110
+ ...(origin ? { origin } : {}),
111
+ ...(originId !== undefined ? { originId } : {}),
112
+ };
108
113
  if (timeoutMs) {
109
114
  p.timer = setTimeout(() => {
110
115
  this.cancelUpstream(id, "timed out");
@@ -238,7 +243,7 @@ export class Upstream {
238
243
  * The client a server-to-client message belongs to. Stdio carries no link between a server
239
244
  * request and the call that caused it, so: an explicit related request id wins; else the one
240
245
  * client with calls in flight; else the only attached client. With calls in flight from
241
- * several clients the message is refused rather than sent to a guess (ADR 0016).
246
+ * several clients the message is refused rather than sent to a guess.
242
247
  */
243
248
  route(method, params) {
244
249
  const meta = params?._meta;
@@ -310,7 +315,9 @@ export class Upstream {
310
315
  async relayRequest(m) {
311
316
  const id = m.id;
312
317
  const outcome = await this.answer(m.method, m.params);
313
- const reply = "error" in outcome ? { jsonrpc: "2.0", id, error: outcome.error } : { jsonrpc: "2.0", id, result: outcome.result };
318
+ const reply = "error" in outcome
319
+ ? { jsonrpc: "2.0", id, error: outcome.error }
320
+ : { jsonrpc: "2.0", id, result: outcome.result };
314
321
  await this.send(reply).catch(() => { });
315
322
  }
316
323
  relayNotification(m) {
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, openSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, closeSync } from "node:fs";
1
+ import { existsSync, mkdirSync, openSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, closeSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE } from "../core/paths.js";
4
4
  import { readJsonFile, realOr } from "../core/fsutil.js";
@@ -65,7 +65,7 @@ export function priceFor(model) {
65
65
  const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
66
66
  /** Tokens a usage record bills: zero for Claude Code's synthetic messages. */
67
67
  function usageTokens(u) {
68
- return num(u.input_tokens) + num(u.output_tokens) + num(u.cache_creation_input_tokens) + num(u.cache_read_input_tokens);
68
+ return (num(u.input_tokens) + num(u.output_tokens) + num(u.cache_creation_input_tokens) + num(u.cache_read_input_tokens));
69
69
  }
70
70
  /**
71
71
  * API cost in USD of one assistant usage record, or undefined when the model has no price.
@@ -84,7 +84,12 @@ export function usageCost(model, u) {
84
84
  const w5m = u.cache_creation?.ephemeral_5m_input_tokens !== undefined
85
85
  ? num(u.cache_creation.ephemeral_5m_input_tokens)
86
86
  : Math.max(0, num(u.cache_creation_input_tokens) - w1h);
87
- const usd = (num(u.input_tokens) * p[0] + num(u.output_tokens) * p[1] + w5m * p[2] + w1h * p[3] + num(u.cache_read_input_tokens) * p[4]) / 1e6;
87
+ const usd = (num(u.input_tokens) * p[0] +
88
+ num(u.output_tokens) * p[1] +
89
+ w5m * p[2] +
90
+ w1h * p[3] +
91
+ num(u.cache_read_input_tokens) * p[4]) /
92
+ 1e6;
88
93
  return usd * (u.speed === "fast" ? 2 : 1);
89
94
  }
90
95
  /** Bumped when an older state would give a wrong total (v2: unknown models are tracked). */
@@ -192,7 +197,15 @@ export function computeCost(transcript, out, now = Date.now() / 1000) {
192
197
  const mainUsd = files[main]?.usd ?? 0;
193
198
  const total = Object.values(files).reduce((a, f) => a + f.usd, 0);
194
199
  const unknown = [...new Set(Object.values(files).flatMap((f) => f.unknown ?? []))];
195
- const state = { v: STATE_VERSION, files, main: mainUsd, sub: total - mainUsd, total, unknown, updated_at: now };
200
+ const state = {
201
+ v: STATE_VERSION,
202
+ files,
203
+ main: mainUsd,
204
+ sub: total - mainUsd,
205
+ total,
206
+ unknown,
207
+ updated_at: now,
208
+ };
196
209
  try {
197
210
  writeJson(out, state);
198
211
  }
@@ -46,8 +46,16 @@ export function sanitize(raw) {
46
46
  }),
47
47
  model: sub({ display_name: str }),
48
48
  effort: sub({ level: str }),
49
- cost: sub({ total_cost_usd: num, total_lines_added: num, total_lines_removed: num }),
50
- context_window: sub({ used_percentage: num, total_input_tokens: num, context_window_size: num }),
49
+ cost: sub({
50
+ total_cost_usd: num,
51
+ total_lines_added: num,
52
+ total_lines_removed: num,
53
+ }),
54
+ context_window: sub({
55
+ used_percentage: num,
56
+ total_input_tokens: num,
57
+ context_window_size: num,
58
+ }),
51
59
  prompt_cache: sub({
52
60
  caching_observed: bool,
53
61
  warm: bool,
@@ -61,6 +69,10 @@ export function sanitize(raw) {
61
69
  export function turns(v) {
62
70
  if (!Array.isArray(v))
63
71
  return [];
64
- return v.filter((e) => Array.isArray(e) && e.length === 3 && typeof e[0] === "string" && num(e[1]) !== undefined && (e[2] === null || num(e[2]) !== undefined));
72
+ return v.filter((e) => Array.isArray(e) &&
73
+ e.length === 3 &&
74
+ typeof e[0] === "string" &&
75
+ num(e[1]) !== undefined &&
76
+ (e[2] === null || num(e[2]) !== undefined));
65
77
  }
66
78
  //# sourceMappingURL=input.js.map
package/dist/ui/fonts.js CHANGED
@@ -5,7 +5,7 @@ import { join } from "node:path";
5
5
  import { findOnPath } from "../cli/launch.js";
6
6
  const NF = "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/v3.4.0/patched-fonts/Meslo/S/";
7
7
  /**
8
- * Same values as turno-fonts. turno-cli does not depend on that package (ADR 0019), so a normal
8
+ * Same values as turno-fonts. turno-cli does not depend on that package, so a normal
9
9
  * install downloads these files and checks each one against its pinned SHA-256.
10
10
  */
11
11
  export const FALLBACK = {
@@ -41,7 +41,12 @@ export function statusLineLabel(s, env, max = 60) {
41
41
  }
42
42
  /** The entry to write: our command, keeping any other keys the user set (padding, ...). */
43
43
  function wantedStatusLine(command, existing) {
44
- return { ...(existing ?? {}), type: "command", command, refreshInterval: existing?.refreshInterval ?? REFRESH_SECONDS };
44
+ return {
45
+ ...(existing ?? {}),
46
+ type: "command",
47
+ command,
48
+ refreshInterval: existing?.refreshInterval ?? REFRESH_SECONDS,
49
+ };
45
50
  }
46
51
  export function setStatusLine(file, command, journal) {
47
52
  const settings = readSettings(file);
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "turno-cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "turno-cli",
9
- "version": "0.2.0",
9
+ "version": "0.4.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "1.32.2",
13
- "smol-toml": "1.9.1"
13
+ "smol-toml": "1.9.1",
14
+ "turno-core": "0.1.0"
14
15
  },
15
16
  "bin": {
16
17
  "turno": "dist/cli/main.js"
@@ -1012,6 +1013,14 @@
1012
1013
  "node": ">=0.6"
1013
1014
  }
1014
1015
  },
1016
+ "node_modules/turno-core": {
1017
+ "version": "0.1.0",
1018
+ "resolved": "https://registry.npmjs.org/turno-core/-/turno-core-0.1.0.tgz",
1019
+ "license": "Apache-2.0",
1020
+ "engines": {
1021
+ "node": ">=22.11"
1022
+ }
1023
+ },
1015
1024
  "node_modules/type-is": {
1016
1025
  "version": "2.1.0",
1017
1026
  "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "turno-cli",
3
- "version": "0.2.0",
4
- "description": "One MCP gateway and per-folder accounts for Claude Code, Codex, Copilot CLI and Cursor CLI.",
3
+ "version": "0.4.0",
4
+ "description": "Switch accounts in your coding agents and keep the conversation, the MCP sign-ins and the browser session.",
5
5
  "keywords": [
6
6
  "claude-code",
7
7
  "codex",
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "license": "Apache-2.0",
21
21
  "author": "William Frank Monroy Mamani (https://github.com/william-monroy)",
22
- "homepage": "https://github.com/wimo-dev/turno#readme",
22
+ "homepage": "https://turno.wimo.dev",
23
23
  "repository": {
24
24
  "type": "git",
25
25
  "url": "git+https://github.com/wimo-dev/turno.git",
@@ -46,12 +46,13 @@
46
46
  ],
47
47
  "dependencies": {
48
48
  "@modelcontextprotocol/sdk": "1.32.2",
49
- "smol-toml": "1.9.1"
49
+ "smol-toml": "1.9.1",
50
+ "turno-core": "0.1.0"
50
51
  },
51
52
  "devDependencies": {
52
53
  "@types/node": "^26.6.6",
53
- "turno-browser": "0.2.0",
54
- "turno-fonts": "0.1.1",
54
+ "turno-browser": "0.4.0",
55
+ "turno-fonts": "0.1.2",
55
56
  "typescript": "^7.0.2",
56
57
  "vitest": "^5.1.0"
57
58
  },