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
@@ -1,11 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync, statSync } from "node:fs";
2
+ import { chmodSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { paths } from "../core/paths.js";
4
+ import { PRIVATE_FILE_MODE, ensurePrivateDir, paths, profileDir } from "../core/paths.js";
5
5
  export const DEFAULT_MAX_TURNS = 15;
6
6
  export const DEFAULT_TIMEOUT_MS = 5 * 60_000;
7
7
  /** The bridge itself: never reachable from a delegated run, so delegation cannot recurse. */
8
- export const BRIDGE_TOOLS = "mcp__accounts__*";
8
+ const BRIDGE_TOOLS = "mcp__accounts__*";
9
9
  /** Path of a profile's launcher (`claude-<profile>` in the turno bin dir). */
10
10
  export function launcherPath(profile, env = process.env) {
11
11
  return join(paths(env).bin, `claude-${profile}`);
@@ -19,12 +19,12 @@ export function launcherExists(profile, env = process.env) {
19
19
  }
20
20
  }
21
21
  /** The prompt the owning profile receives. */
22
- export function delegationPrompt(account, task, write) {
22
+ function delegationPrompt(account, task, write, tools = account.tools) {
23
23
  const what = account.description ? `${account.id} (${account.description})` : account.id;
24
24
  return [
25
25
  "You are running headless on behalf of another Claude Code session, through the turno accounts bridge.",
26
26
  `Account: ${what}, service ${account.service}.`,
27
- `Use only these tools to reach it: ${account.tools.join(", ")}.`,
27
+ `Use only these tools to reach it: ${tools.join(", ")}. Any other tool is refused.`,
28
28
  write
29
29
  ? "Write actions (creating, sending, posting, editing or deleting) are allowed for this task: the user confirmed it. Do only what the task asks."
30
30
  : "Write actions are NOT allowed: only read. If the task needs a write (creating, sending, posting, editing or deleting), do not do it; describe exactly what you would do instead.",
@@ -36,26 +36,143 @@ export function delegationPrompt(account, task, write) {
36
36
  ].join("\n");
37
37
  }
38
38
  /**
39
- * The enforced command line (ADR 0004, decision 3): headless, `dontAsk` so a global
40
- * `bypassPermissions` default cannot leak in, no built-in tools, only the account's tools
41
- * allowed, and the bridge itself disallowed.
39
+ * Environment variables the delegated run keeps (plus every `LC_*`). Everything else in
40
+ * mcpd's environment is dropped: another profile's `CLAUDE_CONFIG_DIR`, API keys, the session
41
+ * variables of whoever started mcpd.
42
42
  */
43
- export function buildDelegation(req, env = process.env) {
44
- const home = paths(env).home;
45
- const cwd = req.cwd && isDir(req.cwd) ? req.cwd : home;
46
- const childEnv = { ...env };
47
- delete childEnv.TURNO_SESSION_PID;
43
+ const ENV_ALLOW = [
44
+ "HOME",
45
+ "PATH",
46
+ "USER",
47
+ "LOGNAME",
48
+ "SHELL",
49
+ "LANG",
50
+ "TZ",
51
+ "TMPDIR",
52
+ "TERM",
53
+ "HTTP_PROXY",
54
+ "HTTPS_PROXY",
55
+ "NO_PROXY",
56
+ "ALL_PROXY",
57
+ "http_proxy",
58
+ "https_proxy",
59
+ "no_proxy",
60
+ "all_proxy",
61
+ "NODE_EXTRA_CA_CERTS",
62
+ "SSL_CERT_FILE",
63
+ "SSL_CERT_DIR",
64
+ ];
65
+ /** The minimal environment of a delegated run, from mcpd's own. */
66
+ function childEnv(env) {
67
+ const out = {};
68
+ for (const [k, v] of Object.entries(env)) {
69
+ if (v === undefined)
70
+ continue;
71
+ if (ENV_ALLOW.includes(k) || k.startsWith("LC_"))
72
+ out[k] = v;
73
+ }
74
+ return out;
75
+ }
76
+ /** The MCP server a tool pattern names (`mcp__linear__*` is `linear`); undefined for other patterns. */
77
+ export function mcpServerOf(pattern) {
78
+ if (!pattern.startsWith("mcp__"))
79
+ return undefined;
80
+ const rest = pattern.slice(5);
81
+ const end = rest.indexOf("__");
82
+ const server = end === -1 ? rest : rest.slice(0, end);
83
+ return server || undefined;
84
+ }
85
+ /** Claude Code's form of a server name inside tool names. */
86
+ function toolName(server) {
87
+ return server.replace(/[^a-zA-Z0-9_-]/g, "_");
88
+ }
89
+ const GATEWAY_URL = /^http:\/\/127\.0\.0\.1:\d+\/mcp\//;
90
+ /**
91
+ * The MCP config of a delegated run: the owning profile's own entries for the servers its
92
+ * tool patterns name, when each one is a turno gateway entry. Anything else (claude.ai
93
+ * connectors, which --strict-mcp-config does not load; a server missing from the profile; a
94
+ * server that does not go through the gateway, whose entry may hold its own secrets) keeps
95
+ * the profile's MCP config, and the allowed tools are the only limit.
96
+ */
97
+ export function isolatedMcp(profile, tools, env = process.env) {
98
+ const wanted = [...new Set(tools.map(mcpServerOf).filter((s) => s !== undefined))];
99
+ const connector = wanted.find((s) => s.startsWith("claude_ai_"));
100
+ if (connector)
101
+ return {
102
+ strict: false,
103
+ servers: {},
104
+ why: `${connector} is a claude.ai connector, which --strict-mcp-config would not load`,
105
+ };
106
+ const wild = wanted.find((s) => s.includes("*"));
107
+ if (wild)
108
+ return { strict: false, servers: {}, why: `the pattern server "${wild}" is not one server` };
109
+ let configured = {};
110
+ try {
111
+ const cfg = JSON.parse(readFileSync(join(profileDir(profile, env), ".claude.json"), "utf8"));
112
+ if (cfg.mcpServers && typeof cfg.mcpServers === "object" && !Array.isArray(cfg.mcpServers))
113
+ configured = cfg.mcpServers;
114
+ }
115
+ catch {
116
+ /* no config: every wanted server is missing */
117
+ }
118
+ const servers = {};
119
+ for (const w of wanted) {
120
+ const name = Object.keys(configured).find((k) => toolName(k) === w);
121
+ if (name === undefined)
122
+ return { strict: false, servers: {}, why: `server "${w}" is not in the MCP config of profile ${profile}` };
123
+ const entry = configured[name];
124
+ if (!entry || typeof entry.url !== "string" || !GATEWAY_URL.test(entry.url)) {
125
+ return { strict: false, servers: {}, why: `server "${w}" does not go through the turno gateway` };
126
+ }
127
+ servers[name] = entry;
128
+ }
129
+ return { strict: true, servers };
130
+ }
131
+ /** Remove what is inside `dir`, keeping the folder itself (a concurrent run may be in it). */
132
+ function emptyDir(dir) {
133
+ for (const name of readdirSync(dir))
134
+ rmSync(join(dir, name), { recursive: true, force: true });
135
+ }
136
+ /**
137
+ * Prepare the run of `profile`: an empty working folder under turno's state (one per profile,
138
+ * so Claude Code keeps one project for the bridge) and, when the account's servers allow it, an
139
+ * MCP config with only those servers, in a per-run folder removed by `cleanup`.
140
+ */
141
+ export function prepareRun(profile, tools, env = process.env) {
142
+ const root = ensurePrivateDir(join(paths(env).state, "delegate"), env);
143
+ const cwd = ensurePrivateDir(join(root, profile), env);
144
+ emptyDir(cwd);
145
+ const mcp = isolatedMcp(profile, tools, env);
146
+ if (!mcp.strict)
147
+ return { cwd, mcp, cleanup: () => { } };
148
+ const dir = mkdtempSync(join(root, ".run-"));
149
+ const mcpConfig = join(dir, "mcp.json");
150
+ writeFileSync(mcpConfig, `${JSON.stringify({ mcpServers: mcp.servers }, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
151
+ chmodSync(mcpConfig, PRIVATE_FILE_MODE);
152
+ return { cwd, mcpConfig, mcp, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
153
+ }
154
+ /**
155
+ * The enforced command line: headless, `dontAsk` so a global
156
+ * `bypassPermissions` default cannot leak in, no settings files (their allow rules, hooks and
157
+ * plugins would widen the run), no built-in tools, only the decided tools allowed, the bridge
158
+ * itself disallowed, and only the account's servers when the folder has an MCP config.
159
+ */
160
+ export function buildDelegation(req, run, env = process.env) {
161
+ const tools = req.tools ?? req.account.tools;
48
162
  return {
49
163
  command: launcherPath(req.account.profile, env),
50
164
  args: [
51
165
  "-p",
52
- delegationPrompt(req.account, req.task, req.write),
166
+ delegationPrompt(req.account, req.task, req.write, tools),
53
167
  "--permission-mode",
54
168
  "dontAsk",
169
+ "--setting-sources",
170
+ "",
171
+ ...(run.mcpConfig ? ["--mcp-config", run.mcpConfig, "--strict-mcp-config"] : []),
55
172
  "--tools",
56
173
  "",
57
174
  "--allowedTools",
58
- ...req.account.tools,
175
+ ...tools,
59
176
  "--disallowedTools",
60
177
  BRIDGE_TOOLS,
61
178
  "--output-format",
@@ -63,21 +180,17 @@ export function buildDelegation(req, env = process.env) {
63
180
  "--max-turns",
64
181
  String(req.maxTurns ?? DEFAULT_MAX_TURNS),
65
182
  ],
66
- cwd,
67
- env: childEnv,
183
+ cwd: run.cwd,
184
+ env: childEnv(env),
68
185
  timeoutMs: req.timeoutMs ?? DEFAULT_TIMEOUT_MS,
69
186
  };
70
187
  }
71
- function isDir(p) {
72
- try {
73
- return existsSync(p) && statSync(p).isDirectory();
74
- }
75
- catch {
76
- return false;
188
+ /** Default runner: own process group, killed as a whole on timeout or abort. */
189
+ const spawnRunner = (spec, signal) => new Promise((resolve) => {
190
+ if (signal?.aborted) {
191
+ resolve({ code: null, stdout: "", stderr: "", timedOut: false, cancelled: true });
192
+ return;
77
193
  }
78
- }
79
- /** Default runner: own process group, killed as a whole on timeout. */
80
- export const spawnRunner = (spec) => new Promise((resolve) => {
81
194
  const child = spawn(spec.command, spec.args, {
82
195
  cwd: spec.cwd,
83
196
  env: spec.env,
@@ -87,6 +200,7 @@ export const spawnRunner = (spec) => new Promise((resolve) => {
87
200
  let stdout = "";
88
201
  let stderr = "";
89
202
  let timedOut = false;
203
+ let cancelled = false;
90
204
  let done = false;
91
205
  const killGroup = (signal) => {
92
206
  if (child.pid === undefined)
@@ -99,12 +213,22 @@ export const spawnRunner = (spec) => new Promise((resolve) => {
99
213
  }
100
214
  };
101
215
  let hardKill;
102
- const timer = setTimeout(() => {
103
- timedOut = true;
216
+ const stop = () => {
104
217
  killGroup("SIGTERM");
105
218
  hardKill = setTimeout(() => killGroup("SIGKILL"), 5000);
106
219
  hardKill.unref();
220
+ };
221
+ const timer = setTimeout(() => {
222
+ timedOut = true;
223
+ stop();
107
224
  }, spec.timeoutMs);
225
+ const onAbort = () => {
226
+ if (done)
227
+ return;
228
+ cancelled = true;
229
+ stop();
230
+ };
231
+ signal?.addEventListener("abort", onAbort, { once: true });
108
232
  child.stdout.setEncoding("utf8").on("data", (d) => (stdout += d));
109
233
  child.stderr.setEncoding("utf8").on("data", (d) => {
110
234
  if (stderr.length < 64 * 1024)
@@ -115,8 +239,9 @@ export const spawnRunner = (spec) => new Promise((resolve) => {
115
239
  return;
116
240
  done = true;
117
241
  clearTimeout(timer);
118
- // After a timeout the hard kill stays armed (unref'd) for grandchildren still alive.
119
- resolve({ code, stdout, stderr, timedOut });
242
+ signal?.removeEventListener("abort", onAbort);
243
+ // After a timeout or abort the hard kill stays armed (unref'd) for grandchildren still alive.
244
+ resolve({ code, stdout, stderr, timedOut, ...(cancelled ? { cancelled } : {}) });
120
245
  };
121
246
  child.on("error", (err) => {
122
247
  stderr += `${err.message}\n`;
@@ -124,6 +249,15 @@ export const spawnRunner = (spec) => new Promise((resolve) => {
124
249
  });
125
250
  child.on("close", (code) => finish(code));
126
251
  });
252
+ /** Tool names from the result's `permission_denials` (calls Claude Code refused). */
253
+ function deniedTools(json) {
254
+ if (!Array.isArray(json?.permission_denials))
255
+ return [];
256
+ const names = json.permission_denials
257
+ .map((d) => (d && typeof d === "object" ? d.tool_name : undefined))
258
+ .filter((n) => typeof n === "string");
259
+ return [...new Set(names)];
260
+ }
127
261
  /** The JSON object printed by `--output-format json` (the last line that parses). */
128
262
  export function parseClaudeJson(stdout) {
129
263
  const whole = stdout.trim();
@@ -158,19 +292,49 @@ function tail(text, n = 400) {
158
292
  export async function delegate(req, opts = {}) {
159
293
  const env = opts.env ?? process.env;
160
294
  const now = opts.now ?? Date.now;
161
- const spec = buildDelegation(req, env);
295
+ const run = prepareRun(req.account.profile, req.tools ?? req.account.tools, env);
296
+ const spec = buildDelegation(req, run, env);
162
297
  const started = now();
163
- const out = await (opts.runner ?? spawnRunner)(spec);
298
+ let out;
299
+ try {
300
+ out = await (opts.runner ?? spawnRunner)(spec, opts.signal);
301
+ }
302
+ finally {
303
+ run.cleanup();
304
+ }
164
305
  const durationMs = now() - started;
165
306
  const json = parseClaudeJson(out.stdout);
166
307
  const costUsd = typeof json?.total_cost_usd === "number" ? json.total_cost_usd : null;
167
308
  const numTurns = typeof json?.num_turns === "number" ? json.num_turns : null;
309
+ const base = {
310
+ costUsd,
311
+ numTurns,
312
+ durationMs,
313
+ denied: deniedTools(json),
314
+ mcp: run.mcp.strict ? "strict" : "profile",
315
+ };
316
+ if (out.cancelled || (opts.signal?.aborted && !json)) {
317
+ return {
318
+ ok: false,
319
+ cancelled: true,
320
+ text: `Delegation to ${req.account.profile} was cancelled; its process was stopped.`,
321
+ ...base,
322
+ };
323
+ }
168
324
  if (out.timedOut) {
169
- return { ok: false, text: `Delegation to ${req.account.profile} timed out after ${Math.round(spec.timeoutMs / 1000)}s.`, costUsd, numTurns, durationMs };
325
+ return {
326
+ ok: false,
327
+ text: `Delegation to ${req.account.profile} timed out after ${Math.round(spec.timeoutMs / 1000)}s.`,
328
+ ...base,
329
+ };
170
330
  }
171
331
  if (!json) {
172
332
  const why = tail(out.stderr) || tail(out.stdout) || "no output";
173
- return { ok: false, text: `Delegation to ${req.account.profile} failed (exit ${out.code ?? "?"}): ${why}`, costUsd, numTurns, durationMs };
333
+ return {
334
+ ok: false,
335
+ text: `Delegation to ${req.account.profile} failed (exit ${out.code ?? "?"}): ${why}`,
336
+ ...base,
337
+ };
174
338
  }
175
339
  const result = typeof json.result === "string" ? json.result : "";
176
340
  const isError = json.is_error === true || out.code !== 0;
@@ -180,6 +344,6 @@ export async function delegate(req, opts = {}) {
180
344
  ? `Delegation to ${req.account.profile} ended with an error${typeof json.subtype === "string" ? ` (${json.subtype})` : ""}${out.stderr.trim() ? `: ${tail(out.stderr)}` : "."}`
181
345
  : "(the delegated run returned no text)";
182
346
  }
183
- return { ok: !isError, text, costUsd, numTurns, durationMs };
347
+ return { ok: !isError, text, ...base };
184
348
  }
185
349
  //# sourceMappingURL=delegate.js.map
@@ -0,0 +1,79 @@
1
+ /**
2
+ * What a call to the accounts bridge may do: whether the user must confirm it, and
3
+ * which tools the delegated run gets. The decision depends on the account, never on the
4
+ * caller's word alone: `write=false` only narrows the tools when the account lists read tools.
5
+ */
6
+ export const CONFIRM_POLICIES = ["always", "writes", "never"];
7
+ export function isConfirmPolicy(v) {
8
+ return typeof v === "string" && CONFIRM_POLICIES.includes(v);
9
+ }
10
+ /**
11
+ * Mail and messaging services: reading them hands another account's private conversations to
12
+ * the calling session, so every call is confirmed unless the account says otherwise.
13
+ */
14
+ const MESSAGING = new Set([
15
+ "chat",
16
+ "discord",
17
+ "email",
18
+ "exchange",
19
+ "gchat",
20
+ "google-chat",
21
+ "imessage",
22
+ "matrix",
23
+ "mattermost",
24
+ "messages",
25
+ "messenger",
26
+ "outlook",
27
+ "signal",
28
+ "slack",
29
+ "sms",
30
+ "teams",
31
+ "telegram",
32
+ "whatsapp",
33
+ "zulip",
34
+ ]);
35
+ function isMessagingService(service) {
36
+ return MESSAGING.has(service) || service.includes("mail");
37
+ }
38
+ /** The default policy of a service: `always` for mail and messaging, `writes` elsewhere. */
39
+ export function defaultConfirm(service) {
40
+ return isMessagingService(service) ? "always" : "writes";
41
+ }
42
+ /** Whether the tool pattern `pattern` (with an optional trailing `*`) covers `tool`. */
43
+ export function patternCovers(pattern, tool) {
44
+ if (pattern === tool)
45
+ return true;
46
+ return pattern.endsWith("*") && tool.startsWith(pattern.slice(0, -1));
47
+ }
48
+ export function effectivePolicy(account) {
49
+ return account.confirm ?? defaultConfirm(account.service);
50
+ }
51
+ /**
52
+ * Decide a call. A read gets only the read tools when the account lists them; without them a
53
+ * read cannot be enforced, so it is treated like a write (all tools, confirmed unless the
54
+ * policy is `never`).
55
+ */
56
+ export function decide(account, write) {
57
+ const policy = effectivePolicy(account);
58
+ const readTools = account.readTools ?? [];
59
+ if (!write && readTools.length > 0) {
60
+ return {
61
+ policy,
62
+ confirm: policy === "always",
63
+ toolset: "read",
64
+ tools: [...readTools],
65
+ reason: policy === "always" ? `read with the read tools; confirm = "always"` : "read with the read tools only",
66
+ };
67
+ }
68
+ const reason = write
69
+ ? "write: every tool of the account"
70
+ : "read, but the account lists no read_tools, so it gets every tool";
71
+ return {
72
+ policy,
73
+ confirm: policy !== "never",
74
+ toolset: "all",
75
+ tools: [...account.tools],
76
+ reason: policy === "never" ? `${reason}; confirm = "never"` : reason,
77
+ };
78
+ }
79
+ //# sourceMappingURL=policy.js.map
@@ -1,8 +1,10 @@
1
- import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { dirname, resolve, sep } from "node:path";
3
3
  import { parse, stringify } from "smol-toml";
4
4
  import { ConfigError, isValidProfileName } from "../core/config.js";
5
- import { expandHome, paths, tildify } from "../core/paths.js";
5
+ import { PRIVATE_FILE_MODE, ensurePrivateDir, expandHome, paths, tildify } from "../core/paths.js";
6
+ import { CONFIRM_POLICIES, isConfirmPolicy, patternCovers } from "./policy.js";
7
+ import { realOr } from "../core/fsutil.js";
6
8
  const ACCOUNT_ID = /^([a-z0-9][a-z0-9_-]*):([A-Za-z0-9][A-Za-z0-9_.@-]*)$/;
7
9
  const SERVICE = /^[a-z0-9][a-z0-9_-]*$/;
8
10
  /** Split and validate an account id (`service:label`); undefined when malformed. */
@@ -27,6 +29,16 @@ function optStr(v, file, key) {
27
29
  throw new ConfigError(file, `${key} must be a string`);
28
30
  return v;
29
31
  }
32
+ function toolList(v, file, key) {
33
+ if (!Array.isArray(v) || v.length === 0)
34
+ throw new ConfigError(file, `${key} must be a non-empty array of tool patterns`);
35
+ for (const t of v) {
36
+ if (typeof t !== "string" || !t.trim() || /\s/.test(t)) {
37
+ throw new ConfigError(file, `${key}: invalid tool pattern ${JSON.stringify(t)}`);
38
+ }
39
+ }
40
+ return [...v];
41
+ }
30
42
  /** Validate one account definition; shared by the parser and `turno accounts add`. */
31
43
  export function makeAccount(id, fields, file = "accounts.toml") {
32
44
  const key = `account."${id}"`;
@@ -41,20 +53,29 @@ export function makeAccount(id, fields, file = "accounts.toml") {
41
53
  throw new ConfigError(file, `${key} needs profile`);
42
54
  if (!isValidProfileName(fields.profile))
43
55
  throw new ConfigError(file, `${key}.profile: invalid profile name "${fields.profile}"`);
44
- const tools = fields.tools;
45
- if (!Array.isArray(tools) || tools.length === 0)
46
- throw new ConfigError(file, `${key}.tools must be a non-empty array of tool patterns`);
47
- for (const t of tools) {
48
- if (typeof t !== "string" || !t.trim() || /\s/.test(t)) {
49
- throw new ConfigError(file, `${key}.tools: invalid tool pattern ${JSON.stringify(t)}`);
56
+ const tools = toolList(fields.tools, file, `${key}.tools`);
57
+ let readTools;
58
+ if (fields.readTools !== undefined) {
59
+ readTools = toolList(fields.readTools, file, `${key}.read_tools`);
60
+ for (const r of readTools) {
61
+ if (!tools.some((t) => patternCovers(t, r))) {
62
+ throw new ConfigError(file, `${key}.read_tools: "${r}" is not covered by the account's tools (${tools.join(", ")})`);
63
+ }
50
64
  }
51
65
  }
66
+ if (fields.confirm !== undefined && !isConfirmPolicy(fields.confirm)) {
67
+ throw new ConfigError(file, `${key}.confirm must be ${CONFIRM_POLICIES.map((c) => `"${c}"`)
68
+ .join(", ")
69
+ .replace(/, ([^,]*)$/, " or $1")}`);
70
+ }
52
71
  return {
53
72
  id,
54
73
  service,
55
74
  label: parsed.label,
56
75
  profile: fields.profile,
57
- tools: [...tools],
76
+ tools,
77
+ ...(readTools ? { readTools } : {}),
78
+ ...(fields.confirm !== undefined ? { confirm: fields.confirm } : {}),
58
79
  ...(fields.description ? { description: fields.description } : {}),
59
80
  };
60
81
  }
@@ -76,6 +97,8 @@ export function parseRegistry(text, file = "accounts.toml", env = process.env) {
76
97
  ...(service !== undefined ? { service } : {}),
77
98
  ...(profile !== undefined ? { profile } : {}),
78
99
  tools: v.tools,
100
+ ...(v.read_tools !== undefined ? { readTools: v.read_tools } : {}),
101
+ ...(v.confirm !== undefined ? { confirm: v.confirm } : {}),
79
102
  ...(description !== undefined ? { description } : {}),
80
103
  }, file);
81
104
  }
@@ -127,6 +150,8 @@ export function formatRegistry(reg, env = process.env) {
127
150
  service: a.service,
128
151
  profile: a.profile,
129
152
  tools: a.tools,
153
+ ...(a.readTools ? { read_tools: a.readTools } : {}),
154
+ ...(a.confirm ? { confirm: a.confirm } : {}),
130
155
  ...(a.description ? { description: a.description } : {}),
131
156
  };
132
157
  }
@@ -145,9 +170,10 @@ export function saveRegistry(reg, env = process.env, journal) {
145
170
  journal.write(file, formatRegistry(reg, env));
146
171
  return file;
147
172
  }
148
- mkdirSync(dirname(file), { recursive: true });
173
+ ensurePrivateDir(dirname(file), env);
149
174
  const tmp = `${file}.${process.pid}.tmp`;
150
- writeFileSync(tmp, formatRegistry(reg, env));
175
+ writeFileSync(tmp, formatRegistry(reg, env), { mode: PRIVATE_FILE_MODE });
176
+ chmodSync(tmp, PRIVATE_FILE_MODE);
151
177
  renameSync(tmp, file);
152
178
  return file;
153
179
  }
@@ -155,14 +181,6 @@ function normalize(p) {
155
181
  const r = resolve(p);
156
182
  return r.length > 1 && r.endsWith(sep) ? r.slice(0, -1) : r;
157
183
  }
158
- function real(p) {
159
- try {
160
- return realpathSync(p);
161
- }
162
- catch {
163
- return p;
164
- }
165
- }
166
184
  function within(dir, root) {
167
185
  return dir === root || root === sep || dir.startsWith(root + sep);
168
186
  }
@@ -171,10 +189,10 @@ function within(dir, root) {
171
189
  * matching path wins. Both the folder and the rule paths are also compared through symlinks.
172
190
  */
173
191
  export function preferredFor(reg, cwd) {
174
- const dirs = [...new Set([normalize(cwd), normalize(real(cwd))])];
192
+ const dirs = [...new Set([normalize(cwd), normalize(realOr(cwd))])];
175
193
  const best = {};
176
194
  for (const rule of reg.prefer) {
177
- const roots = [...new Set([rule.path, normalize(real(rule.path))])];
195
+ const roots = [...new Set([rule.path, normalize(realOr(rule.path))])];
178
196
  const match = roots.filter((r) => dirs.some((d) => within(d, r))).map((r) => r.length);
179
197
  if (!match.length)
180
198
  continue;
@@ -0,0 +1,29 @@
1
+ export const JSON_MCP_SERVERS = { format: "json", key: "mcpServers" };
2
+ export const TOML_MCP_SERVERS = { format: "toml", key: "mcp_servers" };
3
+ /** The gateway URL of one server, the same for every agent. */
4
+ export function gatewayUrl(name, port) {
5
+ return `http://127.0.0.1:${port}/mcp/${encodeURIComponent(name)}`;
6
+ }
7
+ /** Whether an MCP entry points at mcpd: written by `turno mcp sync`, or by hand from `turno mcp config`. */
8
+ export function isGatewayEntry(e) {
9
+ if (typeof e !== "object" || e === null || Array.isArray(e))
10
+ return false;
11
+ const o = e;
12
+ const table = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
13
+ const headers = { ...table(o.headers), ...table(o.http_headers), ...table(o.env_http_headers) };
14
+ if (Object.keys(headers).some((h) => h.toLowerCase() === "x-turno-profile" || h.toLowerCase() === "x-turno-pid"))
15
+ return true;
16
+ if (o.bearer_token_env_var === "TURNO_MCPD_TOKEN")
17
+ return true;
18
+ return typeof o.url === "string" && /^http:\/\/127\.0\.0\.1:\d+\/mcp\/[^/]+\/?$/.test(o.url);
19
+ }
20
+ /** The names of the gateway entries in one server map, sorted. */
21
+ export function gatewayNames(map) {
22
+ if (typeof map !== "object" || map === null || Array.isArray(map))
23
+ return [];
24
+ return Object.entries(map)
25
+ .filter(([, e]) => isGatewayEntry(e))
26
+ .map(([n]) => n)
27
+ .sort();
28
+ }
29
+ //# sourceMappingURL=adapter.js.map