turno-cli 0.0.0-stage → 0.1.1

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 (83) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/README.md +335 -2
  5. package/dist/accounts/audit.js +54 -0
  6. package/dist/accounts/builtin.js +214 -0
  7. package/dist/accounts/delegate.js +185 -0
  8. package/dist/accounts/registry.js +190 -0
  9. package/dist/agents/index.js +101 -0
  10. package/dist/agents/snippets.js +64 -0
  11. package/dist/cli/args.js +47 -0
  12. package/dist/cli/commands/accounts.js +216 -0
  13. package/dist/cli/commands/auto.js +44 -0
  14. package/dist/cli/commands/available.js +18 -0
  15. package/dist/cli/commands/browser.js +175 -0
  16. package/dist/cli/commands/complete.js +112 -0
  17. package/dist/cli/commands/completion.js +57 -0
  18. package/dist/cli/commands/config.js +168 -0
  19. package/dist/cli/commands/doctor.js +324 -0
  20. package/dist/cli/commands/exhausted.js +40 -0
  21. package/dist/cli/commands/handoff.js +118 -0
  22. package/dist/cli/commands/hook.js +63 -0
  23. package/dist/cli/commands/identity.js +114 -0
  24. package/dist/cli/commands/limit.js +102 -0
  25. package/dist/cli/commands/mcp.js +350 -0
  26. package/dist/cli/commands/mcpd.js +161 -0
  27. package/dist/cli/commands/migrate.js +176 -0
  28. package/dist/cli/commands/open.js +60 -0
  29. package/dist/cli/commands/profile.js +259 -0
  30. package/dist/cli/commands/resolve.js +23 -0
  31. package/dist/cli/commands/run.js +15 -0
  32. package/dist/cli/commands/secret.js +123 -0
  33. package/dist/cli/commands/session.js +36 -0
  34. package/dist/cli/commands/sessions.js +27 -0
  35. package/dist/cli/commands/setup.js +224 -0
  36. package/dist/cli/commands/status.js +101 -0
  37. package/dist/cli/commands/statusline.js +275 -0
  38. package/dist/cli/commands/ui.js +276 -0
  39. package/dist/cli/commands/undo.js +67 -0
  40. package/dist/cli/commands/update-check.js +22 -0
  41. package/dist/cli/commands/upgrade.js +162 -0
  42. package/dist/cli/commands/usage.js +167 -0
  43. package/dist/cli/commands/version.js +27 -0
  44. package/dist/cli/commands/which.js +28 -0
  45. package/dist/cli/group.js +50 -0
  46. package/dist/cli/io.js +22 -0
  47. package/dist/cli/launch.js +98 -0
  48. package/dist/cli/launchers.js +200 -0
  49. package/dist/cli/main.js +94 -0
  50. package/dist/cli/registry.js +77 -0
  51. package/dist/core/config-edit.js +42 -0
  52. package/dist/core/config.js +137 -0
  53. package/dist/core/exhausted.js +30 -0
  54. package/dist/core/journal.js +185 -0
  55. package/dist/core/manifest.js +177 -0
  56. package/dist/core/paths.js +54 -0
  57. package/dist/core/profiles.js +61 -0
  58. package/dist/core/ratelimit.js +39 -0
  59. package/dist/core/resolve.js +78 -0
  60. package/dist/core/secrets.js +44 -0
  61. package/dist/core/sessions.js +173 -0
  62. package/dist/core/toml-edit.js +152 -0
  63. package/dist/core/update.js +102 -0
  64. package/dist/core/version.js +109 -0
  65. package/dist/mcpd/cache.js +41 -0
  66. package/dist/mcpd/connectors.js +63 -0
  67. package/dist/mcpd/daemon.js +163 -0
  68. package/dist/mcpd/gateway.js +308 -0
  69. package/dist/mcpd/importer.js +160 -0
  70. package/dist/mcpd/instances.js +303 -0
  71. package/dist/mcpd/jsonrpc.js +19 -0
  72. package/dist/mcpd/launchd.js +86 -0
  73. package/dist/mcpd/peerpid.js +25 -0
  74. package/dist/mcpd/sync.js +208 -0
  75. package/dist/mcpd/upstream.js +232 -0
  76. package/dist/statusline/cost.js +135 -0
  77. package/dist/statusline/render.js +246 -0
  78. package/dist/ui/cmap.js +57 -0
  79. package/dist/ui/fonts.js +107 -0
  80. package/dist/ui/settings.js +69 -0
  81. package/dist/ui/terminal-id.js +30 -0
  82. package/dist/ui/terminals.js +163 -0
  83. package/package.json +69 -3
@@ -0,0 +1,214 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from "@modelcontextprotocol/sdk/types.js";
4
+ import { appendAudit } from "./audit.js";
5
+ import { DEFAULT_MAX_TURNS, DEFAULT_TIMEOUT_MS, delegate, launcherExists, launcherPath } from "./delegate.js";
6
+ import { loadRegistry, preferredFor } from "./registry.js";
7
+ const TOOLS = [
8
+ {
9
+ name: "accounts_list",
10
+ description: "List the service accounts (Linear workspaces, Gmail connectors, ...) known to turno, which Claude profile owns each, " +
11
+ "whether each one is native to this session (reachable directly with its tool patterns) and the preferred account per service for this folder.",
12
+ inputSchema: { type: "object", properties: {} },
13
+ annotations: { readOnlyHint: true },
14
+ },
15
+ {
16
+ name: "accounts_delegate",
17
+ description: "Run a task against an account owned by another Claude profile: turno runs it headless in that profile with only the account's tools and returns the outcome. " +
18
+ "Set write=true for outward-facing actions (creating, sending, posting, editing, deleting); the user is then asked to confirm. " +
19
+ "For native accounts, use their tools directly instead.",
20
+ inputSchema: {
21
+ type: "object",
22
+ properties: {
23
+ account: { type: "string", description: "Account id from accounts_list, like linear:work." },
24
+ task: { type: "string", description: "What to do, self-contained: the other profile does not see this conversation." },
25
+ write: { type: "boolean", description: "True when the task changes anything outside (creates, sends, posts, edits, deletes).", default: false },
26
+ },
27
+ required: ["account", "task"],
28
+ },
29
+ },
30
+ ];
31
+ function text(t, isError = false) {
32
+ return { content: [{ type: "text", text: t }], ...(isError ? { isError: true } : {}) };
33
+ }
34
+ function money(v) {
35
+ return v === null ? "unknown cost" : `$${v.toFixed(4)}`;
36
+ }
37
+ /** The accounts bridge as a builtin mcpd server (`builtin = "accounts"` in mcp.toml). */
38
+ export function accountsBuiltin(deps = {}) {
39
+ return (rawCtx) => {
40
+ const ctx = rawCtx;
41
+ const env = deps.env ?? process.env;
42
+ const now = deps.now ?? Date.now;
43
+ const registry = deps.loadRegistry ?? (() => loadRegistry(env));
44
+ const hasLauncher = deps.launcherExists ?? ((p) => launcherExists(p, env));
45
+ const audit = deps.audit ?? ((e) => void appendAudit(e, env));
46
+ const server = new Server({ name: "turno-accounts", version: "0.1.0" }, {
47
+ capabilities: { tools: {} },
48
+ instructions: "turno accounts bridge: call accounts_list to see which service accounts exist and which are native here; " +
49
+ "use accounts_delegate to act on an account owned by another profile.",
50
+ });
51
+ const caller = { profile: ctx.profile ?? null, pid: ctx.pid ?? null };
52
+ let folder = ctx.cwd;
53
+ /** The session folder: the X-Turno-Cwd header, else the client's first root. */
54
+ async function sessionFolder() {
55
+ if (folder)
56
+ return folder;
57
+ const caps = ctx.clientCapabilities ?? server.getClientCapabilities();
58
+ if (!caps?.roots)
59
+ return undefined;
60
+ try {
61
+ const { roots } = await server.listRoots(undefined, { timeout: 10_000 });
62
+ const first = roots.find((r) => r.uri.startsWith("file://"));
63
+ if (first)
64
+ folder = fileURLToPath(first.uri);
65
+ }
66
+ catch {
67
+ /* client without roots */
68
+ }
69
+ return folder;
70
+ }
71
+ async function list() {
72
+ const reg = registry();
73
+ const cwd = await sessionFolder();
74
+ const preferred = cwd ? preferredFor(reg, cwd) : {};
75
+ const accounts = Object.values(reg.accounts)
76
+ .sort((a, b) => a.id.localeCompare(b.id))
77
+ .map((a) => ({
78
+ id: a.id,
79
+ service: a.service,
80
+ owner: a.profile,
81
+ native: ctx.profile !== undefined && a.profile === ctx.profile,
82
+ tools: a.tools,
83
+ ...(a.description ? { description: a.description } : {}),
84
+ ...(preferred[a.service] === a.id ? { preferred: true } : {}),
85
+ }));
86
+ const body = {
87
+ callerProfile: ctx.profile ?? null,
88
+ folder: cwd ?? null,
89
+ preferred,
90
+ accounts,
91
+ howTo: "Native accounts: call their tools directly. Others: accounts_delegate with the account id; set write=true for outward-facing actions.",
92
+ };
93
+ return text(JSON.stringify(body, null, 2));
94
+ }
95
+ async function confirmWrite(account, task) {
96
+ const caps = ctx.clientCapabilities ?? server.getClientCapabilities();
97
+ const unsupported = "This client does not support MCP elicitation, so a write action cannot be confirmed by the user. Write delegation is refused; do it from a session that supports elicitation, or in the owning profile directly.";
98
+ if (!caps?.elicitation)
99
+ return { ok: false, why: unsupported };
100
+ try {
101
+ const res = await server.elicitInput({
102
+ mode: "form",
103
+ message: `Allow a write action through account ${account.id}, run headless in profile "${account.profile}"` +
104
+ `${ctx.profile ? ` on behalf of profile "${ctx.profile}"` : ""}?\n\n` +
105
+ `Owner: ${account.profile}\nAccount: ${account.id}${account.description ? ` (${account.description})` : ""}\nTools: ${account.tools.join(", ")}\n\nTask:\n${task}`,
106
+ requestedSchema: {
107
+ type: "object",
108
+ properties: {
109
+ confirm: { type: "boolean", title: "Run this write action", description: "Check to allow it.", default: false },
110
+ },
111
+ required: ["confirm"],
112
+ },
113
+ }, { timeout: deps.confirmTimeoutMs ?? 10 * 60_000 });
114
+ if (res.action === "accept" && res.content?.confirm === true)
115
+ return { ok: true };
116
+ return { ok: false, why: res.action === "accept" ? "the user did not check confirm" : `the user chose ${res.action}` };
117
+ }
118
+ catch (err) {
119
+ if (err instanceof McpError && err.code === ErrorCode.MethodNotFound)
120
+ return { ok: false, why: unsupported };
121
+ return { ok: false, why: `confirmation failed: ${err.message}` };
122
+ }
123
+ }
124
+ async function run(account, task, write, progressToken, send) {
125
+ let beat;
126
+ if (progressToken !== undefined) {
127
+ let n = 0;
128
+ beat = setInterval(() => {
129
+ n += 1;
130
+ void send({
131
+ method: "notifications/progress",
132
+ params: { progressToken, progress: n, message: `waiting for ${account.profile} (${account.id})` },
133
+ }).catch(() => { });
134
+ }, deps.heartbeatMs ?? 15_000);
135
+ }
136
+ try {
137
+ const cwd = await sessionFolder();
138
+ return await delegate({
139
+ account,
140
+ task,
141
+ write,
142
+ ...(cwd ? { cwd } : {}),
143
+ maxTurns: deps.maxTurns ?? DEFAULT_MAX_TURNS,
144
+ timeoutMs: deps.timeoutMs ?? DEFAULT_TIMEOUT_MS,
145
+ }, { env, now, ...(deps.runner ? { runner: deps.runner } : {}) });
146
+ }
147
+ finally {
148
+ if (beat)
149
+ clearInterval(beat);
150
+ }
151
+ }
152
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
153
+ server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
154
+ const args = (req.params.arguments ?? {});
155
+ if (req.params.name === "accounts_list") {
156
+ try {
157
+ return await list();
158
+ }
159
+ catch (err) {
160
+ return text(`Cannot read the accounts registry: ${err.message}`, true);
161
+ }
162
+ }
163
+ if (req.params.name !== "accounts_delegate")
164
+ return text(`Unknown tool ${req.params.name}`, true);
165
+ const started = now();
166
+ const accountId = typeof args.account === "string" ? args.account : "";
167
+ const task = typeof args.task === "string" ? args.task.trim() : "";
168
+ const write = args.write === true;
169
+ let owner = null;
170
+ const record = (outcome, detail, costUsd = null, durationMs = now() - started) => audit({ caller, account: accountId, owner, write, task, outcome, detail, durationMs, costUsd });
171
+ if (!accountId || !task) {
172
+ record("error", "missing account or task");
173
+ return text("accounts_delegate needs both account and task.", true);
174
+ }
175
+ let reg;
176
+ try {
177
+ reg = registry();
178
+ }
179
+ catch (err) {
180
+ record("error", `registry: ${err.message}`);
181
+ return text(`Cannot read the accounts registry: ${err.message}`, true);
182
+ }
183
+ const account = reg.accounts[accountId];
184
+ if (!account) {
185
+ record("error", "unknown account");
186
+ const known = Object.keys(reg.accounts).sort();
187
+ return text(`Unknown account "${accountId}". Known accounts: ${known.length ? known.join(", ") : "none (see turno accounts add)"}.`, true);
188
+ }
189
+ owner = account.profile;
190
+ if (ctx.profile !== undefined && account.profile === ctx.profile) {
191
+ record("refused", "native account: not delegated");
192
+ return text(`${account.id} is native to this session (profile ${account.profile}). Do not delegate: call its tools directly (${account.tools.join(", ")}).`);
193
+ }
194
+ if (!hasLauncher(account.profile)) {
195
+ record("error", `launcher missing: ${launcherPath(account.profile, env)}`);
196
+ return text(`Cannot delegate to profile "${account.profile}": its launcher ${launcherPath(account.profile, env)} does not exist. Run \`turno setup\` or fix the account's profile.`, true);
197
+ }
198
+ if (write) {
199
+ const ok = await confirmWrite(account, task);
200
+ if (!ok.ok) {
201
+ record("refused", ok.why);
202
+ return text(`Write delegation to ${account.id} refused: ${ok.why}. Nothing was run.`, true);
203
+ }
204
+ }
205
+ const progressToken = req.params._meta?.progressToken;
206
+ const res = await run(account, task, write, progressToken, (n) => extra.sendNotification(n));
207
+ record(res.ok ? "ok" : "error", res.ok ? `${res.numTurns ?? "?"} turns` : res.text.slice(0, 500), res.costUsd, res.durationMs);
208
+ const footer = `\n\n[${account.id} via profile ${account.profile}; ${res.numTurns ?? "?"} turns; ${money(res.costUsd)}; ${Math.round(res.durationMs / 1000)}s]`;
209
+ return text(`${res.text}${footer}`, !res.ok);
210
+ });
211
+ return server;
212
+ };
213
+ }
214
+ //# sourceMappingURL=builtin.js.map
@@ -0,0 +1,185 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { paths } from "../core/paths.js";
5
+ export const DEFAULT_MAX_TURNS = 15;
6
+ export const DEFAULT_TIMEOUT_MS = 5 * 60_000;
7
+ /** The bridge itself: never reachable from a delegated run, so delegation cannot recurse. */
8
+ export const BRIDGE_TOOLS = "mcp__accounts__*";
9
+ /** Path of a profile's launcher (`claude-<profile>` in the turno bin dir). */
10
+ export function launcherPath(profile, env = process.env) {
11
+ return join(paths(env).bin, `claude-${profile}`);
12
+ }
13
+ export function launcherExists(profile, env = process.env) {
14
+ try {
15
+ return statSync(launcherPath(profile, env)).isFile();
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ /** The prompt the owning profile receives. */
22
+ export function delegationPrompt(account, task, write) {
23
+ const what = account.description ? `${account.id} (${account.description})` : account.id;
24
+ return [
25
+ "You are running headless on behalf of another Claude Code session, through the turno accounts bridge.",
26
+ `Account: ${what}, service ${account.service}.`,
27
+ `Use only these tools to reach it: ${account.tools.join(", ")}.`,
28
+ write
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
+ : "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.",
31
+ "",
32
+ "Task:",
33
+ task,
34
+ "",
35
+ "When you are done, reply with a concise outcome: what you did or found, with identifiers and links when relevant. No preamble.",
36
+ ].join("\n");
37
+ }
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.
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;
48
+ return {
49
+ command: launcherPath(req.account.profile, env),
50
+ args: [
51
+ "-p",
52
+ delegationPrompt(req.account, req.task, req.write),
53
+ "--permission-mode",
54
+ "dontAsk",
55
+ "--tools",
56
+ "",
57
+ "--allowedTools",
58
+ ...req.account.tools,
59
+ "--disallowedTools",
60
+ BRIDGE_TOOLS,
61
+ "--output-format",
62
+ "json",
63
+ "--max-turns",
64
+ String(req.maxTurns ?? DEFAULT_MAX_TURNS),
65
+ ],
66
+ cwd,
67
+ env: childEnv,
68
+ timeoutMs: req.timeoutMs ?? DEFAULT_TIMEOUT_MS,
69
+ };
70
+ }
71
+ function isDir(p) {
72
+ try {
73
+ return existsSync(p) && statSync(p).isDirectory();
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ /** Default runner: own process group, killed as a whole on timeout. */
80
+ export const spawnRunner = (spec) => new Promise((resolve) => {
81
+ const child = spawn(spec.command, spec.args, {
82
+ cwd: spec.cwd,
83
+ env: spec.env,
84
+ stdio: ["ignore", "pipe", "pipe"],
85
+ detached: true,
86
+ });
87
+ let stdout = "";
88
+ let stderr = "";
89
+ let timedOut = false;
90
+ let done = false;
91
+ const killGroup = (signal) => {
92
+ if (child.pid === undefined)
93
+ return;
94
+ try {
95
+ process.kill(-child.pid, signal);
96
+ }
97
+ catch {
98
+ /* already gone */
99
+ }
100
+ };
101
+ let hardKill;
102
+ const timer = setTimeout(() => {
103
+ timedOut = true;
104
+ killGroup("SIGTERM");
105
+ hardKill = setTimeout(() => killGroup("SIGKILL"), 5000);
106
+ hardKill.unref();
107
+ }, spec.timeoutMs);
108
+ child.stdout.setEncoding("utf8").on("data", (d) => (stdout += d));
109
+ child.stderr.setEncoding("utf8").on("data", (d) => {
110
+ if (stderr.length < 64 * 1024)
111
+ stderr += d;
112
+ });
113
+ const finish = (code) => {
114
+ if (done)
115
+ return;
116
+ done = true;
117
+ clearTimeout(timer);
118
+ // After a timeout the hard kill stays armed (unref'd) for grandchildren still alive.
119
+ resolve({ code, stdout, stderr, timedOut });
120
+ };
121
+ child.on("error", (err) => {
122
+ stderr += `${err.message}\n`;
123
+ finish(null);
124
+ });
125
+ child.on("close", (code) => finish(code));
126
+ });
127
+ /** The JSON object printed by `--output-format json` (the last line that parses). */
128
+ export function parseClaudeJson(stdout) {
129
+ const whole = stdout.trim();
130
+ if (!whole)
131
+ return undefined;
132
+ try {
133
+ const v = JSON.parse(whole);
134
+ if (v && typeof v === "object" && !Array.isArray(v))
135
+ return v;
136
+ }
137
+ catch {
138
+ /* try line by line */
139
+ }
140
+ const lines = whole.split("\n").reverse();
141
+ for (const line of lines) {
142
+ try {
143
+ const v = JSON.parse(line);
144
+ if (v && typeof v === "object" && !Array.isArray(v))
145
+ return v;
146
+ }
147
+ catch {
148
+ /* next */
149
+ }
150
+ }
151
+ return undefined;
152
+ }
153
+ function tail(text, n = 400) {
154
+ const t = text.trim();
155
+ return t.length > n ? `...${t.slice(-n)}` : t;
156
+ }
157
+ /** Run the task in the owning profile and interpret Claude Code's JSON result. */
158
+ export async function delegate(req, opts = {}) {
159
+ const env = opts.env ?? process.env;
160
+ const now = opts.now ?? Date.now;
161
+ const spec = buildDelegation(req, env);
162
+ const started = now();
163
+ const out = await (opts.runner ?? spawnRunner)(spec);
164
+ const durationMs = now() - started;
165
+ const json = parseClaudeJson(out.stdout);
166
+ const costUsd = typeof json?.total_cost_usd === "number" ? json.total_cost_usd : null;
167
+ const numTurns = typeof json?.num_turns === "number" ? json.num_turns : null;
168
+ 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 };
170
+ }
171
+ if (!json) {
172
+ 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 };
174
+ }
175
+ const result = typeof json.result === "string" ? json.result : "";
176
+ const isError = json.is_error === true || out.code !== 0;
177
+ let text = result;
178
+ if (!text) {
179
+ text = isError
180
+ ? `Delegation to ${req.account.profile} ended with an error${typeof json.subtype === "string" ? ` (${json.subtype})` : ""}${out.stderr.trim() ? `: ${tail(out.stderr)}` : "."}`
181
+ : "(the delegated run returned no text)";
182
+ }
183
+ return { ok: !isError, text, costUsd, numTurns, durationMs };
184
+ }
185
+ //# sourceMappingURL=delegate.js.map
@@ -0,0 +1,190 @@
1
+ import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve, sep } from "node:path";
3
+ import { parse, stringify } from "smol-toml";
4
+ import { ConfigError, isValidProfileName } from "../core/config.js";
5
+ import { expandHome, paths, tildify } from "../core/paths.js";
6
+ const ACCOUNT_ID = /^([a-z0-9][a-z0-9_-]*):([A-Za-z0-9][A-Za-z0-9_.@-]*)$/;
7
+ const SERVICE = /^[a-z0-9][a-z0-9_-]*$/;
8
+ /** Split and validate an account id (`service:label`); undefined when malformed. */
9
+ export function parseAccountId(id) {
10
+ const m = ACCOUNT_ID.exec(id);
11
+ return m ? { service: m[1], label: m[2] } : undefined;
12
+ }
13
+ export function isValidService(name) {
14
+ return SERVICE.test(name);
15
+ }
16
+ function table(v, file, key) {
17
+ if (v === undefined)
18
+ return {};
19
+ if (typeof v !== "object" || v === null || Array.isArray(v))
20
+ throw new ConfigError(file, `${key} must be a table`);
21
+ return v;
22
+ }
23
+ function optStr(v, file, key) {
24
+ if (v === undefined)
25
+ return undefined;
26
+ if (typeof v !== "string")
27
+ throw new ConfigError(file, `${key} must be a string`);
28
+ return v;
29
+ }
30
+ /** Validate one account definition; shared by the parser and `turno accounts add`. */
31
+ export function makeAccount(id, fields, file = "accounts.toml") {
32
+ const key = `account."${id}"`;
33
+ const parsed = parseAccountId(id);
34
+ if (!parsed)
35
+ throw new ConfigError(file, `invalid account id "${id}" (expected service:label, like linear:work)`);
36
+ const service = fields.service ?? parsed.service;
37
+ if (service !== parsed.service) {
38
+ throw new ConfigError(file, `${key}.service is "${service}" but the id starts with "${parsed.service}"`);
39
+ }
40
+ if (!fields.profile)
41
+ throw new ConfigError(file, `${key} needs profile`);
42
+ if (!isValidProfileName(fields.profile))
43
+ 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)}`);
50
+ }
51
+ }
52
+ return {
53
+ id,
54
+ service,
55
+ label: parsed.label,
56
+ profile: fields.profile,
57
+ tools: [...tools],
58
+ ...(fields.description ? { description: fields.description } : {}),
59
+ };
60
+ }
61
+ export function parseRegistry(text, file = "accounts.toml", env = process.env) {
62
+ let raw;
63
+ try {
64
+ raw = parse(text);
65
+ }
66
+ catch (err) {
67
+ throw new ConfigError(file, err.message);
68
+ }
69
+ const reg = { accounts: {}, prefer: [] };
70
+ for (const [id, value] of Object.entries(table(raw.account, file, "account"))) {
71
+ const v = table(value, file, `account."${id}"`);
72
+ const service = optStr(v.service, file, `account."${id}".service`);
73
+ const profile = optStr(v.profile, file, `account."${id}".profile`);
74
+ const description = optStr(v.description, file, `account."${id}".description`);
75
+ reg.accounts[id] = makeAccount(id, {
76
+ ...(service !== undefined ? { service } : {}),
77
+ ...(profile !== undefined ? { profile } : {}),
78
+ tools: v.tools,
79
+ ...(description !== undefined ? { description } : {}),
80
+ }, file);
81
+ }
82
+ const prefer = raw.prefer ?? [];
83
+ if (!Array.isArray(prefer))
84
+ throw new ConfigError(file, "prefer must be an array of tables ([[prefer]])");
85
+ for (const [i, item] of prefer.entries()) {
86
+ const v = table(item, file, `prefer[${i}]`);
87
+ const path = optStr(v.path, file, `prefer[${i}].path`);
88
+ if (!path)
89
+ throw new ConfigError(file, `prefer[${i}] needs path`);
90
+ const accounts = {};
91
+ for (const [service, target] of Object.entries(v)) {
92
+ if (service === "path")
93
+ continue;
94
+ if (typeof target !== "string")
95
+ throw new ConfigError(file, `prefer[${i}].${service} must be an account id`);
96
+ const acct = reg.accounts[target];
97
+ if (!acct)
98
+ throw new ConfigError(file, `prefer[${i}].${service}: unknown account "${target}"`);
99
+ if (acct.service !== service) {
100
+ throw new ConfigError(file, `prefer[${i}].${service}: account "${target}" belongs to service "${acct.service}"`);
101
+ }
102
+ accounts[service] = target;
103
+ }
104
+ reg.prefer.push({ path: normalize(expandHome(path, env)), accounts });
105
+ }
106
+ return reg;
107
+ }
108
+ /** Load accounts.toml; a missing file is an empty registry. */
109
+ export function loadRegistry(env = process.env) {
110
+ const file = paths(env).accountsFile;
111
+ let text = "";
112
+ try {
113
+ text = readFileSync(file, "utf8");
114
+ }
115
+ catch (err) {
116
+ if (err.code !== "ENOENT")
117
+ throw err;
118
+ }
119
+ return parseRegistry(text, file, env);
120
+ }
121
+ /** TOML text of a registry. Paths under the home are written with `~`. */
122
+ export function formatRegistry(reg, env = process.env) {
123
+ const account = {};
124
+ for (const id of Object.keys(reg.accounts).sort()) {
125
+ const a = reg.accounts[id];
126
+ account[id] = {
127
+ service: a.service,
128
+ profile: a.profile,
129
+ tools: a.tools,
130
+ ...(a.description ? { description: a.description } : {}),
131
+ };
132
+ }
133
+ const doc = { account };
134
+ if (reg.prefer.length)
135
+ doc.prefer = reg.prefer.map((r) => ({ path: tildify(r.path, env), ...r.accounts }));
136
+ return `# Accounts registry, managed by \`turno accounts\`. Comments are not preserved on rewrite.\n\n${stringify(doc)}\n`;
137
+ }
138
+ /**
139
+ * Rewrite accounts.toml from a registry. The whole file is regenerated (atomically), so
140
+ * comments and formatting of a hand-edited file are not preserved.
141
+ */
142
+ export function saveRegistry(reg, env = process.env, journal) {
143
+ const file = paths(env).accountsFile;
144
+ if (journal) {
145
+ journal.write(file, formatRegistry(reg, env));
146
+ return file;
147
+ }
148
+ mkdirSync(dirname(file), { recursive: true });
149
+ const tmp = `${file}.${process.pid}.tmp`;
150
+ writeFileSync(tmp, formatRegistry(reg, env));
151
+ renameSync(tmp, file);
152
+ return file;
153
+ }
154
+ function normalize(p) {
155
+ const r = resolve(p);
156
+ return r.length > 1 && r.endsWith(sep) ? r.slice(0, -1) : r;
157
+ }
158
+ function real(p) {
159
+ try {
160
+ return realpathSync(p);
161
+ }
162
+ catch {
163
+ return p;
164
+ }
165
+ }
166
+ function within(dir, root) {
167
+ return dir === root || root === sep || dir.startsWith(root + sep);
168
+ }
169
+ /**
170
+ * Preferred account per service for a folder. For each service the rule with the longest
171
+ * matching path wins. Both the folder and the rule paths are also compared through symlinks.
172
+ */
173
+ export function preferredFor(reg, cwd) {
174
+ const dirs = [...new Set([normalize(cwd), normalize(real(cwd))])];
175
+ const best = {};
176
+ for (const rule of reg.prefer) {
177
+ const roots = [...new Set([rule.path, normalize(real(rule.path))])];
178
+ const match = roots.filter((r) => dirs.some((d) => within(d, r))).map((r) => r.length);
179
+ if (!match.length)
180
+ continue;
181
+ const len = Math.max(...match);
182
+ for (const [service, account] of Object.entries(rule.accounts)) {
183
+ const cur = best[service];
184
+ if (!cur || len > cur.len)
185
+ best[service] = { len, account };
186
+ }
187
+ }
188
+ return Object.fromEntries(Object.entries(best).map(([s, v]) => [s, v.account]));
189
+ }
190
+ //# sourceMappingURL=registry.js.map