@cavelon/cli 0.1.15 → 0.1.16

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 (39) hide show
  1. package/README.md +12 -0
  2. package/dist/agent-env.js +2 -0
  3. package/dist/agents.js +14 -7
  4. package/dist/approval-policy.js +1 -0
  5. package/dist/commands/init.js +46 -10
  6. package/dist/commands/session.js +3 -0
  7. package/dist/commands/setup.js +17 -4
  8. package/dist/confirm-token.js +2 -1
  9. package/dist/fsutil.js +24 -7
  10. package/dist/jsonc-config.js +223 -0
  11. package/dist/kit-codes.js +1 -0
  12. package/dist/mcp-command.js +5 -0
  13. package/dist/mcp-directory.js +32 -0
  14. package/dist/mcp-entry.js +21 -0
  15. package/dist/mcp.js +18 -2
  16. package/dist/native-approval/client.js +126 -0
  17. package/dist/native-approval/ipc.js +191 -0
  18. package/dist/native-approval/opencode-server.js +74 -0
  19. package/dist/native-approval/opencode-tui.js +143 -0
  20. package/dist/native-approval/pi-extension.js +84 -0
  21. package/dist/native-approval/preview-pages.js +18 -0
  22. package/dist/native-approval/profile.js +113 -0
  23. package/dist/native-assets/JSONC-LICENSE +21 -0
  24. package/dist/native-assets/LICENSE +201 -0
  25. package/dist/native-assets/MCP-SDK-LICENSE +21 -0
  26. package/dist/native-assets/THIRD-PARTY-NOTICES +368 -0
  27. package/dist/native-assets/TYPEBOX-LICENSE +23 -0
  28. package/dist/native-assets/ZOD-LICENSE +21 -0
  29. package/dist/native-assets/manifest.json +60 -0
  30. package/dist/native-assets/opencode-server.mjs +32273 -0
  31. package/dist/native-assets/opencode-tui.mjs +19055 -0
  32. package/dist/native-assets/pi-extension.mjs +23302 -0
  33. package/dist/native-assets.js +44 -0
  34. package/dist/native-clients.js +181 -0
  35. package/dist/native-install.js +365 -0
  36. package/dist/printed.js +17 -5
  37. package/dist/setup-agents.js +73 -8
  38. package/dist/skills/cavelon-loop/SKILL.md +7 -0
  39. package/package.json +7 -3
@@ -0,0 +1,44 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { embeddedContent } from "./embedded.js";
6
+ import { KIT_VERSION } from "./version.js";
7
+ async function readAssets() {
8
+ const here = path.dirname(fileURLToPath(import.meta.url));
9
+ for (const directory of [path.join(here, "native-assets"), path.resolve(here, "..", "dist", "native-assets")]) {
10
+ let names;
11
+ try {
12
+ names = await fs.readdir(directory);
13
+ }
14
+ catch (error) {
15
+ if (error.code === "ENOENT")
16
+ continue;
17
+ throw error;
18
+ }
19
+ return Promise.all(names.map(async (name) => ({ path: name, content: await fs.readFile(path.join(directory, name), "utf8") })));
20
+ }
21
+ throw new Error("Missing native assets; build or reinstall Cavelon.");
22
+ }
23
+ export async function bundledNativeAssets() {
24
+ const assets = embeddedContent()?.nativeAssets ?? await readAssets();
25
+ const raw = assets.find(asset => asset.path === "manifest.json");
26
+ if (!raw)
27
+ throw new Error("Missing native asset manifest; reinstall Cavelon.");
28
+ const manifest = JSON.parse(raw.content);
29
+ if (manifest.format !== 1 || manifest.version !== KIT_VERSION || !Array.isArray(manifest.files)
30
+ || assets.length !== manifest.files.length + 1)
31
+ throw new Error("Invalid native asset manifest; reinstall Cavelon.");
32
+ const seen = new Set();
33
+ for (const listed of manifest.files) {
34
+ if (typeof listed.path !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(listed.path) || seen.has(listed.path) || listed.path === "manifest.json") {
35
+ throw new Error("Invalid native asset path.");
36
+ }
37
+ seen.add(listed.path);
38
+ const asset = assets.find(asset => asset.path === listed.path);
39
+ if (!asset || Buffer.byteLength(asset.content) !== listed.size
40
+ || createHash("sha256").update(asset.content).digest("hex") !== listed.sha256)
41
+ throw new Error("Native asset checksum mismatch; reinstall Cavelon.");
42
+ }
43
+ return assets.toSorted((a, b) => a.path.localeCompare(b.path, "en"));
44
+ }
@@ -0,0 +1,181 @@
1
+ import path from "node:path";
2
+ import { parseTree } from "jsonc-parser";
3
+ import { readTextFile } from "./fsutil.js";
4
+ import { readJsoncEntry } from "./jsonc-config.js";
5
+ import { isKitMcpEntry } from "./mcp-entry.js";
6
+ import { homeDir } from "./paths.js";
7
+ const openCodeConfig = (file, files, blocked) => ({
8
+ client: "opencode", format: "native", file, files, syntax: "jsonc", keys: ["mcp", "cavelon"], entryFormat: "command-array", extra: { type: "local" },
9
+ ...(blocked ? { blocked } : {}),
10
+ });
11
+ const piConfig = (file) => ({
12
+ client: "pi", format: "native", file, files: [file], syntax: "json", keys: ["mcpServers", "cavelon"], entryFormat: "command-args", extra: {},
13
+ });
14
+ const piDir = (env) => env.PI_CODING_AGENT_DIR || path.join(homeDir(env), ".pi", "agent");
15
+ function qwenDir(env) {
16
+ const raw = env.QWEN_HOME;
17
+ if (!raw)
18
+ return path.join(homeDir(env), ".qwen");
19
+ const expanded = raw === "~" ? homeDir(env) : raw.startsWith("~/") || raw.startsWith("~\\")
20
+ ? path.join(homeDir(env), ...raw.slice(2).split(/[/\\]+/)) : raw;
21
+ return path.resolve(expanded);
22
+ }
23
+ function qwenManagedFiles(env, platform) {
24
+ const system = env.QWEN_CODE_SYSTEM_SETTINGS_PATH || (platform === "darwin" ? "/Library/Application Support/QwenCode/settings.json"
25
+ : platform === "win32" ? "C:\\ProgramData\\qwen-code\\settings.json" : "/etc/qwen-code/settings.json");
26
+ return [env.QWEN_CODE_SYSTEM_DEFAULTS_PATH || path.join(path.dirname(system), "system-defaults.json"), system];
27
+ }
28
+ const qwenConfig = (file, env, platform = process.platform) => ({
29
+ client: "qwen", format: "native", file, files: [file], syntax: "json-comments", keys: ["mcpServers", "cavelon"],
30
+ entryFormat: "command-args", extra: {}, managedFiles: qwenManagedFiles(env, platform),
31
+ });
32
+ export function hasNativeApprovalAdapter(config) {
33
+ return config.client === "opencode" || config.client === "pi";
34
+ }
35
+ function openCodeUserFiles(env) {
36
+ const dir = path.join(env.XDG_CONFIG_HOME || path.join(homeDir(env), ".config"), "opencode");
37
+ return [path.join(dir, "config.json"), path.join(dir, "opencode.json"), path.join(dir, "opencode.jsonc"), ...(env.OPENCODE_CONFIG ? [env.OPENCODE_CONFIG] : [])];
38
+ }
39
+ export const NATIVE_CLIENTS = [
40
+ {
41
+ name: "opencode", label: "OpenCode", aliases: ["opencode-ai"], commands: ["opencode"], projectSkills: [],
42
+ project: (env = {}) => ({ ...openCodeConfig("opencode.json", ["opencode.json", "opencode.jsonc", ".opencode/opencode.json", ".opencode/opencode.jsonc"], env.OPENCODE_CONFIG_CONTENT ? "OPENCODE_CONFIG_CONTENT overrides file settings; configure Cavelon in that managed configuration" :
43
+ env.OPENCODE_DISABLE_PROJECT_CONFIG === "true" || env.OPENCODE_DISABLE_PROJECT_CONFIG === "1" ? "OpenCode project configuration is disabled" :
44
+ env.OPENCODE_CONFIG_DIR ? "OPENCODE_CONFIG_DIR may override project settings; configure Cavelon in that directory" : undefined), shadowFiles: openCodeUserFiles(env) }),
45
+ user: env => {
46
+ const global = path.join(env.XDG_CONFIG_HOME || path.join(homeDir(env), ".config"), "opencode");
47
+ const dir = env.OPENCODE_CONFIG_DIR || global;
48
+ const files = openCodeUserFiles(env);
49
+ if (dir !== global)
50
+ files.push(path.join(dir, "opencode.json"), path.join(dir, "opencode.jsonc"));
51
+ return {
52
+ mcp: openCodeConfig(env.OPENCODE_CONFIG || path.join(dir, "opencode.json"), [...new Set(files)], env.OPENCODE_CONFIG_CONTENT ? "OPENCODE_CONFIG_CONTENT overrides file settings; configure Cavelon in that managed configuration" : undefined),
53
+ skills: path.join(dir, "skills"), folders: [...new Set([global, dir])],
54
+ };
55
+ },
56
+ notes: ["Setup installs separate native OpenCode server/TUI plugins and disables only its duplicate Cavelon MCP entry. Guarded changes require a fresh person dialog; missing UI returns a command for the person's own terminal. File checks do not certify actual UI loading."],
57
+ },
58
+ {
59
+ name: "pi", label: "Pi", aliases: ["pi-coding-agent"], commands: ["pi"], projectSkills: [".pi/skills"],
60
+ project: (env = {}) => ({ ...piConfig(".pi/mcp.json"), shadowFiles: [path.join(piDir(env), "mcp.json")] }),
61
+ user: env => {
62
+ const dir = piDir(env);
63
+ return { mcp: piConfig(path.join(dir, "mcp.json")), skills: path.join(dir, "skills"), folders: [dir] };
64
+ },
65
+ notes: [
66
+ "Pi reads project MCP only after the person grants project trust. A project entry overrides a user entry with the same name.",
67
+ "Replacement /mcp extensions can override Pi's built-in MCP; inspect them in Pi before using these settings. Setup does not install or disable another MCP extension.",
68
+ "Setup installs the native Cavelon extension and disables only its duplicate built-in MCP entry. Guarded changes require a fresh person dialog; missing UI returns a command for the person's own terminal. File checks do not certify actual UI loading.",
69
+ ],
70
+ },
71
+ {
72
+ name: "qwen", label: "Qwen Code CLI", aliases: ["qwen-code", "qwen-cli"], commands: ["qwen"], projectSkills: [".qwen/skills"],
73
+ project: (env = {}) => ({ ...qwenConfig(".qwen/settings.json", env), shadowFiles: [path.join(qwenDir(env), "settings.json")] }),
74
+ user: (env, platform = process.platform) => {
75
+ const dir = qwenDir(env);
76
+ return { mcp: qwenConfig(path.join(dir, "settings.json"), env, platform), skills: path.join(dir, "skills"), folders: [dir] };
77
+ },
78
+ notes: [
79
+ "Qwen Code CLI 0.25.0 reads native Cavelon skills and MCP settings; project settings depend on project trust. System MCP policies and personal servers are preserved.",
80
+ "This client does not advertise MCP form elicitation. Guarded changes return a preview and a command for the person's own terminal; tool permission approval and automatic modes cannot confirm the Cavelon change.",
81
+ ],
82
+ },
83
+ ];
84
+ export const nativeClient = (name) => NATIVE_CLIENTS.find(client => client.name === name || client.aliases.includes(name));
85
+ export function readNativeMcp(text, config) {
86
+ if (text !== undefined && config.syntax === "json") {
87
+ try {
88
+ JSON.parse(text);
89
+ }
90
+ catch {
91
+ return { error: "this client requires plain JSON; correct the file before setup" };
92
+ }
93
+ }
94
+ if (text !== undefined && config.syntax === "json-comments") {
95
+ const errors = [];
96
+ parseTree(text, errors, { allowTrailingComma: false });
97
+ if (errors.length)
98
+ return { error: "this client accepts JSON comments but not trailing commas; correct the file before setup" };
99
+ }
100
+ return readJsoncEntry(text, config.keys);
101
+ }
102
+ function serverMatches(pattern) {
103
+ let positions = new Set([0]);
104
+ for (const char of pattern) {
105
+ const next = new Set();
106
+ for (const at of positions) {
107
+ if (char === "*")
108
+ for (let end = at; end <= "cavelon".length; end++)
109
+ next.add(end);
110
+ else if (at < "cavelon".length && (char === "?" || char === "cavelon"[at]))
111
+ next.add(at + 1);
112
+ }
113
+ positions = next;
114
+ }
115
+ return positions.has("cavelon".length);
116
+ }
117
+ async function qwenPolicy(config, full) {
118
+ for (const file of new Set([...(config.managedFiles ?? []), ...(config.shadowFiles ?? []), ...config.files.map(full)])) {
119
+ const text = await readTextFile(file);
120
+ if (text === undefined)
121
+ continue;
122
+ const parsed = readNativeMcp(text, config);
123
+ if ("error" in parsed)
124
+ return `${file}: ${parsed.error}`;
125
+ if (config.managedFiles?.includes(file) && parsed.value !== undefined)
126
+ return `managed settings in ${file} define Cavelon; review that binding with the operator instead of writing another entry`;
127
+ const policy = readJsoncEntry(text, ["mcp"]);
128
+ if ("error" in policy)
129
+ return `${file}: ${policy.error}`;
130
+ if (policy.value === undefined)
131
+ continue;
132
+ if (!policy.value || typeof policy.value !== "object" || Array.isArray(policy.value))
133
+ return `the MCP policy in ${file} is invalid; review it manually`;
134
+ const settings = policy.value;
135
+ for (const key of ["allowed", "excluded"]) {
136
+ const patterns = settings[key];
137
+ if (patterns === undefined)
138
+ continue;
139
+ if (!Array.isArray(patterns) || !patterns.every(pattern => typeof pattern === "string"))
140
+ return `the MCP ${key} policy in ${file} is invalid; review it manually`;
141
+ const matches = patterns.some(serverMatches);
142
+ if (key === "allowed" ? !matches : matches)
143
+ return `the MCP ${key} policy in ${file} prevents Cavelon; ask the person or operator to review it`;
144
+ }
145
+ }
146
+ return undefined;
147
+ }
148
+ export async function resolveNativeMcp(config, root) {
149
+ const full = (file) => root ? path.resolve(root, file) : path.resolve(file);
150
+ if (config.blocked)
151
+ return { file: full(config.file), error: config.blocked };
152
+ if (config.client === "qwen") {
153
+ const error = await qwenPolicy(config, full);
154
+ if (error)
155
+ return { file: full(config.file), error };
156
+ }
157
+ for (const file of config.shadowFiles ?? []) {
158
+ const entry = readNativeMcp(await readTextFile(file), config);
159
+ if ("error" in entry)
160
+ return { file: full(config.file), error: `${file}: ${entry.error}; review user/project precedence manually` };
161
+ if (entry.value !== undefined && !isKitMcpEntry(entry.value, config.entryFormat, config.extra)) {
162
+ return { file: full(config.file), error: `a personal Cavelon server in ${file} would be shadowed; review user/project precedence manually` };
163
+ }
164
+ }
165
+ const found = [];
166
+ for (const candidate of config.files) {
167
+ const file = full(candidate);
168
+ const text = await readTextFile(file);
169
+ if (text === undefined)
170
+ continue;
171
+ const entry = readNativeMcp(text, config);
172
+ if ("error" in entry)
173
+ return { file, error: entry.error };
174
+ found.push({ file, text, current: entry.value, kept: Math.min(entry.kept, config.keys.length - 1) });
175
+ }
176
+ const owners = found.filter(candidate => candidate.current !== undefined);
177
+ if (owners.length > 1)
178
+ return { file: owners.at(-1).file, error: `multiple configuration files define ${config.keys.join(".")}; resolve their precedence manually` };
179
+ const selected = owners[0] ?? found.at(-1);
180
+ return selected ?? { file: full(config.file), text: undefined, current: undefined, kept: 0 };
181
+ }
@@ -0,0 +1,365 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { fileURLToPath } from "node:url";
6
+ import { bundledNativeAssets } from "./native-assets.js";
7
+ import { readTextFile, writeFileAtomic } from "./fsutil.js";
8
+ import { appendJsoncMember, readJsoncEntry, removeJsoncEntry, removeJsoncMember, upsertJsoncEntry } from "./jsonc-config.js";
9
+ import { decodeMcpEntry, encodeMcpEntry, isKitMcpEntry } from "./mcp-entry.js";
10
+ import { nativeClient, hasNativeApprovalAdapter, readNativeMcp, resolveNativeMcp } from "./native-clients.js";
11
+ import { nativeEntryHash } from "./native-approval/profile.js";
12
+ import { KIT_VERSION } from "./version.js";
13
+ const hash = (text) => createHash("sha256").update(text).digest("hex");
14
+ const portable = (base, file) => path.relative(base, file).split(path.sep).join("/") || ".";
15
+ const memberPath = (file, target) => "./" + portable(path.dirname(file), target);
16
+ const json = (value) => JSON.stringify(value, null, 2) + "\n";
17
+ const inside = (root, file) => {
18
+ const relative = path.relative(root, file);
19
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
20
+ };
21
+ async function safeFile(file, root) {
22
+ const stat = await fs.lstat(file).catch(error => { if (error.code === "ENOENT")
23
+ return undefined; throw error; });
24
+ if (stat?.isSymbolicLink() || (stat && !stat.isFile()))
25
+ throw new Error(`Native installation will not replace a symlink or non-file: ${file}`);
26
+ if (root) {
27
+ let parent = path.dirname(file);
28
+ while (!await fs.stat(parent).then(() => true, error => { if (error.code === "ENOENT")
29
+ return false; throw error; }))
30
+ parent = path.dirname(parent);
31
+ const canonical = path.join(await fs.realpath(parent), path.relative(parent, file));
32
+ if (!inside(await fs.realpath(root), canonical))
33
+ throw new Error("Native installation cannot write outside its project.");
34
+ }
35
+ }
36
+ async function readInstallation(directory) {
37
+ const stat = await fs.lstat(directory).catch(error => { if (error.code === "ENOENT")
38
+ return undefined; throw error; });
39
+ if (!stat)
40
+ return undefined;
41
+ if (!stat.isDirectory() || stat.isSymbolicLink())
42
+ throw new Error("The native directory is not an owned regular directory.");
43
+ const file = path.join(directory, "installation.json");
44
+ await safeFile(file);
45
+ const text = await readTextFile(file);
46
+ if (!text)
47
+ throw new Error("The native directory belongs to a personal integration; no Cavelon ownership record exists.");
48
+ let record;
49
+ try {
50
+ record = JSON.parse(text);
51
+ }
52
+ catch {
53
+ throw new Error("Invalid native ownership record; inspect the installation before repeating setup.");
54
+ }
55
+ if (record.format !== 1 || !["opencode", "pi"].includes(record.client) || !["user", "project"].includes(record.scope)
56
+ || typeof record.version !== "string" || !record.files || typeof record.files !== "object" || Array.isArray(record.files)
57
+ || !record.mcp || typeof record.mcp.file !== "string" || !/^[a-f0-9]{64}$/.test(record.mcp.hash)
58
+ || typeof record.mcp.created !== "boolean" || !Number.isInteger(record.mcp.kept) || record.mcp.kept < 0 || record.mcp.kept > 1
59
+ || !Array.isArray(record.references) || !record.references.length
60
+ || record.references.some(ref => !ref || typeof ref.file !== "string" || !["plugin", "extensions"].includes(ref.key) || typeof ref.member !== "string"
61
+ || typeof ref.created !== "boolean" || typeof ref.kept !== "boolean")
62
+ || (record.scope === "project" && record.projectRoot !== "../..")) {
63
+ throw new Error("Invalid native ownership record; inspect the installation before repeating setup.");
64
+ }
65
+ for (const [name, digest] of Object.entries(record.files)) {
66
+ if (!/^[a-zA-Z0-9_.-]+$/.test(name) || name === "installation.json" || !/^[a-f0-9]{64}$/.test(digest))
67
+ throw new Error("Invalid native asset ownership.");
68
+ }
69
+ return record;
70
+ }
71
+ const fileOf = (directory, file) => path.resolve(directory, file);
72
+ async function referenceCount(file, value, member) {
73
+ const target = path.resolve(path.dirname(file), member);
74
+ const canonical = await fs.realpath(target).catch(() => target);
75
+ let count = 0;
76
+ for (const item of value) {
77
+ const spec = Array.isArray(item) ? item[0] : item;
78
+ if (typeof spec !== "string")
79
+ continue;
80
+ let full;
81
+ try {
82
+ if (spec.startsWith("file:"))
83
+ full = fileURLToPath(spec);
84
+ else if (path.isAbsolute(spec) || spec.startsWith("./") || spec.startsWith("../"))
85
+ full = path.resolve(path.dirname(file), spec);
86
+ else
87
+ continue;
88
+ }
89
+ catch {
90
+ continue;
91
+ }
92
+ if (await fs.realpath(full).catch(() => full) === canonical)
93
+ count++;
94
+ }
95
+ return count;
96
+ }
97
+ async function verify(directory, record) {
98
+ const root = record.scope === "project" ? fileOf(directory, record.projectRoot) : undefined;
99
+ for (const [name, digest] of Object.entries(record.files)) {
100
+ const file = path.join(directory, name);
101
+ await safeFile(file, root);
102
+ const text = await readTextFile(file);
103
+ if (text === undefined || hash(text) !== digest)
104
+ throw new Error(`Native asset ${name} was edited or removed; personal changes are preserved.`);
105
+ }
106
+ const mcpFile = fileOf(directory, record.mcp.file);
107
+ await safeFile(mcpFile, root);
108
+ const mcp = nativeClient(record.client).project();
109
+ const selected = readNativeMcp(await readTextFile(mcpFile), mcp);
110
+ if ("error" in selected || selected.value === undefined || nativeEntryHash(selected.value) !== record.mcp.hash)
111
+ throw new Error("The native Cavelon MCP entry was edited; review it before update or removal.");
112
+ for (const ref of record.references) {
113
+ const file = fileOf(directory, ref.file);
114
+ await safeFile(file, root);
115
+ const entry = readJsoncEntry(await readTextFile(file), [ref.key]);
116
+ if ("error" in entry || !Array.isArray(entry.value) || entry.value.filter(member => isDeepStrictEqual(member, ref.member)).length !== 1
117
+ || await referenceCount(file, entry.value, ref.member) !== 1) {
118
+ throw new Error("A native plugin reference was edited or duplicated; personal settings are preserved.");
119
+ }
120
+ }
121
+ }
122
+ async function chooseFile(files, fallback) {
123
+ const present = [];
124
+ for (const file of files)
125
+ if (await readTextFile(file) !== undefined)
126
+ present.push(file);
127
+ return present.at(-1) ?? fallback;
128
+ }
129
+ async function references(client, directory, mcpFile, env, root) {
130
+ if (client === "pi")
131
+ return [{ file: path.join(path.dirname(directory), "settings.json"), key: "extensions", member: memberPath(path.join(path.dirname(directory), "settings.json"), path.join(directory, "pi-extension.mjs")) }];
132
+ const global = path.dirname(nativeClient(client).user({ ...env, OPENCODE_CONFIG_DIR: undefined }).skills);
133
+ const configDir = env.OPENCODE_CONFIG_DIR;
134
+ const files = root ? [path.join(root, "tui.json"), path.join(root, "tui.jsonc"), path.join(root, ".opencode", "tui.json"), path.join(root, ".opencode", "tui.jsonc")] :
135
+ [path.join(global, "tui.json"), path.join(global, "tui.jsonc"), ...(env.OPENCODE_TUI_CONFIG ? [env.OPENCODE_TUI_CONFIG] : []),
136
+ ...(configDir ? [path.join(configDir, "tui.json"), path.join(configDir, "tui.jsonc")] : [])];
137
+ if (root && env.OPENCODE_TUI_CONFIG)
138
+ throw new Error("OPENCODE_TUI_CONFIG overrides project UI settings; use user setup for that configuration.");
139
+ const fallback = !root && configDir ? path.join(configDir, "tui.json") : !root && env.OPENCODE_TUI_CONFIG ? env.OPENCODE_TUI_CONFIG : path.join(root ?? global, "tui.json");
140
+ const tuiFile = await chooseFile(files, fallback);
141
+ return [
142
+ { file: mcpFile, key: "plugin", member: memberPath(mcpFile, path.join(directory, "opencode-server-entry.mjs")) },
143
+ { file: tuiFile, key: "plugin", member: memberPath(tuiFile, path.join(directory, "opencode-tui-entry.mjs")) },
144
+ ];
145
+ }
146
+ export async function planNativeInstallation(config, command, env, options = {}) {
147
+ if (!hasNativeApprovalAdapter(config))
148
+ throw new Error("This client has no native person-dialog adapter.");
149
+ const root = options.root;
150
+ const expectedDirectory = root ? path.join(root, config.client === "pi" ? ".pi" : ".opencode", "cavelon") : path.join(path.dirname(nativeClient(config.client).user(env).skills), "cavelon");
151
+ const directory = options.directory ?? expectedDirectory;
152
+ const skipped = (reason) => ({ directory, outcome: "skipped", reason, writes: [] });
153
+ try {
154
+ if (path.resolve(directory) !== path.resolve(expectedDirectory))
155
+ return skipped("Native config directories changed; remove the recorded integration before setting up the new location.");
156
+ const previous = await readInstallation(directory);
157
+ if (previous) {
158
+ if (previous.client !== config.client || previous.scope !== (root ? "project" : "user"))
159
+ return skipped("The native directory is owned by another integration.");
160
+ await verify(directory, previous);
161
+ }
162
+ let effective = config;
163
+ let user;
164
+ if (root) {
165
+ const userDirectory = path.join(path.dirname(nativeClient(config.client).user(env).skills), "cavelon");
166
+ user = await readInstallation(userDirectory);
167
+ if (user) {
168
+ if (user.client !== config.client || user.scope !== "user")
169
+ return skipped("The user native directory belongs to another integration.");
170
+ await verify(userDirectory, user);
171
+ const userFile = fileOf(userDirectory, user.mcp.file);
172
+ effective = { ...config, shadowFiles: config.shadowFiles?.filter(file => path.resolve(file) !== userFile) };
173
+ }
174
+ }
175
+ const selected = await resolveNativeMcp(effective, root);
176
+ if ("error" in selected)
177
+ return skipped(selected.error);
178
+ if (root && user && selected.current === undefined && !previous)
179
+ return { directory, outcome: "unchanged", reason: "The verified user native integration already serves this project; no duplicate project integration was added.", writes: [] };
180
+ if (previous && fileOf(directory, previous.mcp.file) !== selected.file)
181
+ return skipped("The selected MCP config changed; remove the recorded integration first.");
182
+ if (selected.current !== undefined && !(previous && nativeEntryHash(selected.current) === previous.mcp.hash)
183
+ && !isKitMcpEntry(selected.current, config.entryFormat, config.extra))
184
+ return skipped("A personal Cavelon server already exists; it is not owned by native setup.");
185
+ const disabled = encodeMcpEntry(command, config.entryFormat, { ...config.extra, enabled: false });
186
+ const assets = await bundledNativeAssets();
187
+ const profile = { ...(root ? { format: 2, projectRoot: portable(directory, root) } : {}),
188
+ client: config.client, version: KIT_VERSION, scope: root ? "project" : "user", configFile: root ? portable(directory, selected.file) : selected.file, entryHash: nativeEntryHash(disabled) };
189
+ const contents = new Map(assets.map(asset => [asset.path, asset.content]));
190
+ contents.set("profile.json", json(profile));
191
+ if (config.client === "opencode")
192
+ for (const surface of ["server", "tui"]) {
193
+ contents.set(`opencode-${surface}-entry.mjs`, `import adapter from "./opencode-${surface}.mjs";\nexport default { ...adapter, id: "cavelon.native-approval.${root ? "project" : "user"}" };\n`);
194
+ }
195
+ const writes = new Map();
196
+ const replace = async (file, after) => {
197
+ await safeFile(file, root);
198
+ const before = await readTextFile(file);
199
+ writes.set(file, { file, before, after, mode: await fs.stat(file).then(stat => stat.mode & 0o777, () => 0o600) });
200
+ };
201
+ for (const [name, content] of contents) {
202
+ if (previous && !(name in previous.files) && await readTextFile(path.join(directory, name)) !== undefined)
203
+ return skipped(`The new native asset ${name} belongs to a personal file; it is preserved.`);
204
+ await replace(path.join(directory, name), content);
205
+ }
206
+ const refs = [];
207
+ for (const ref of await references(config.client, directory, selected.file, env, root)) {
208
+ const before = writes.get(ref.file)?.after ?? await readTextFile(ref.file);
209
+ if (config.client === "pi" && before !== undefined) {
210
+ try {
211
+ JSON.parse(before);
212
+ }
213
+ catch {
214
+ return skipped("Pi settings require plain JSON; correct the file before native installation.");
215
+ }
216
+ }
217
+ for (const id of ["cavelon.native-approval", `cavelon.native-approval.${root ? "project" : "user"}`]) {
218
+ const enabled = readJsoncEntry(before, ["plugin_enabled", id]);
219
+ if ("error" in enabled)
220
+ return skipped(enabled.error);
221
+ if (enabled.value === false)
222
+ return skipped("The person turned off the Cavelon plugin; setup does not enable it.");
223
+ }
224
+ const current = readJsoncEntry(before, [ref.key]);
225
+ if ("error" in current)
226
+ return skipped(current.error);
227
+ if (Array.isArray(current.value)) {
228
+ const aliases = await referenceCount(ref.file, current.value, ref.member);
229
+ if (aliases > 1 || (aliases === 1 && !current.value.includes(ref.member)))
230
+ return skipped("An aliased or duplicate Cavelon plugin reference exists; review it manually.");
231
+ }
232
+ const added = appendJsoncMember(before, [ref.key], ref.member);
233
+ if (added.outcome === "skipped")
234
+ return skipped(added.reason);
235
+ if (!previous && added.outcome === "unchanged")
236
+ return skipped("An existing native plugin reference is not owned by setup; review it manually.");
237
+ await replace(ref.file, added.content ?? before);
238
+ const old = previous?.references.find(item => fileOf(directory, item.file) === ref.file && item.key === ref.key && item.member === ref.member);
239
+ refs.push({ file: root ? portable(directory, ref.file) : ref.file, key: ref.key, member: ref.member, created: old?.created ?? before === undefined, kept: old?.kept ?? current.value !== undefined });
240
+ }
241
+ if (previous && previous.references.some(old => !refs.some(ref => isDeepStrictEqual(ref, old))))
242
+ return skipped("Native reference locations changed; remove the recorded integration first.");
243
+ const before = writes.get(selected.file)?.after ?? selected.text;
244
+ const entry = upsertJsoncEntry(before, config.keys, disabled, { matches: value => isKitMcpEntry(value, config.entryFormat, config.extra)
245
+ || Boolean(previous && nativeEntryHash(value) === previous.mcp.hash) });
246
+ if (entry.outcome === "skipped")
247
+ return skipped(entry.reason);
248
+ await replace(selected.file, entry.content ?? before);
249
+ const record = { format: 1, client: config.client, scope: root ? "project" : "user", version: KIT_VERSION,
250
+ ...(root ? { projectRoot: portable(directory, root) } : {}), files: Object.fromEntries([...contents].map(([name, content]) => [name, hash(content)])),
251
+ mcp: { file: root ? portable(directory, selected.file) : selected.file, hash: nativeEntryHash(disabled), created: previous?.mcp.created ?? (options.mcpRecord?.file === selected.file ? options.mcpRecord.created : selected.text === undefined), kept: previous?.mcp.kept ?? options.mcpRecord?.kept ?? selected.kept }, references: refs };
252
+ await replace(path.join(directory, "installation.json"), json(record));
253
+ const changed = [...writes.values()].filter(write => write.before !== write.after);
254
+ return { directory, outcome: changed.length ? "planned" : "unchanged", writes: changed };
255
+ }
256
+ catch (error) {
257
+ return skipped(error instanceof Error ? error.message : String(error));
258
+ }
259
+ }
260
+ export async function applyNativeInstallation(plan, writer = writeFileAtomic) {
261
+ if (plan.outcome !== "planned")
262
+ return;
263
+ await fs.mkdir(path.dirname(plan.directory), { recursive: true, mode: 0o700 });
264
+ const lockFile = plan.directory + ".lock";
265
+ const lock = await fs.open(lockFile, "wx", 0o600).catch(error => {
266
+ if (error.code === "EEXIST")
267
+ throw new Error("Another native installer holds this directory's lock; inspect it before retrying.");
268
+ throw error;
269
+ });
270
+ const lockIdentity = await lock.stat();
271
+ const done = [];
272
+ try {
273
+ await lock.writeFile(`cavelon-native ${process.pid}\n`);
274
+ for (const write of plan.writes) {
275
+ await safeFile(write.file);
276
+ if (await readTextFile(write.file) !== write.before)
277
+ throw new Error("Native configuration changed after planning; no further edits were made.");
278
+ done.push(write);
279
+ if (write.after === undefined)
280
+ await fs.rm(write.file);
281
+ else
282
+ await writer(write.file, write.after, write.mode, 0o700);
283
+ }
284
+ }
285
+ catch (error) {
286
+ for (const write of done.reverse()) {
287
+ if (await readTextFile(write.file) !== write.after)
288
+ continue;
289
+ if (write.before === undefined)
290
+ await fs.rm(write.file, { force: true });
291
+ else
292
+ await writeFileAtomic(write.file, write.before, write.mode, 0o700);
293
+ }
294
+ await fs.rmdir(plan.directory).catch(() => undefined);
295
+ throw error;
296
+ }
297
+ finally {
298
+ await lock.close();
299
+ const stat = await fs.lstat(lockFile).catch(() => undefined);
300
+ if (stat?.isFile() && stat.dev === lockIdentity.dev && stat.ino === lockIdentity.ino)
301
+ await fs.rm(lockFile);
302
+ }
303
+ }
304
+ export async function checkNativeInstallation(directory) {
305
+ try {
306
+ const record = await readInstallation(directory);
307
+ if (!record)
308
+ throw new Error("No recorded native installation exists.");
309
+ await verify(directory, record);
310
+ for (const ref of record.references) {
311
+ const text = await readTextFile(fileOf(directory, ref.file));
312
+ for (const id of ["cavelon.native-approval", `cavelon.native-approval.${record.scope}`]) {
313
+ const enabled = readJsoncEntry(text, ["plugin_enabled", id]);
314
+ if ("error" in enabled)
315
+ throw new Error(enabled.error);
316
+ if (enabled.value === false)
317
+ throw new Error("The person turned off the Cavelon plugin; enable it in the client only if intended.");
318
+ }
319
+ }
320
+ const config = nativeClient(record.client).project();
321
+ const entry = readNativeMcp(await readTextFile(fileOf(directory, record.mcp.file)), config);
322
+ if ("error" in entry)
323
+ throw new Error(entry.error);
324
+ return { command: decodeMcpEntry(entry.value, config.entryFormat) };
325
+ }
326
+ catch (error) {
327
+ return { reason: error instanceof Error ? error.message : String(error) };
328
+ }
329
+ }
330
+ export async function removeNativeInstallation(directory) {
331
+ try {
332
+ const record = await readInstallation(directory);
333
+ if (!record)
334
+ return { removed: true };
335
+ await verify(directory, record);
336
+ const writes = new Map();
337
+ const replace = async (file, after) => {
338
+ const before = await readTextFile(file);
339
+ writes.set(file, { file, before, after, mode: await fs.stat(file).then(stat => stat.mode & 0o777, () => 0o600) });
340
+ };
341
+ for (const ref of record.references) {
342
+ const file = fileOf(directory, ref.file);
343
+ const before = writes.get(file)?.after ?? await readTextFile(file);
344
+ const removed = removeJsoncMember(before, [ref.key], ref.member, { removeEmpty: !ref.kept });
345
+ if (removed.outcome === "skipped")
346
+ throw new Error(removed.reason);
347
+ await replace(file, removed.empty && ref.created ? undefined : removed.content ?? before);
348
+ }
349
+ const mcpFile = fileOf(directory, record.mcp.file);
350
+ const before = writes.get(mcpFile)?.after ?? await readTextFile(mcpFile);
351
+ const config = nativeClient(record.client).project();
352
+ const removed = removeJsoncEntry(before, config.keys, value => nativeEntryHash(value) === record.mcp.hash, record.mcp.kept);
353
+ if (removed.outcome === "skipped")
354
+ throw new Error(removed.reason);
355
+ await replace(mcpFile, removed.empty && record.mcp.created ? undefined : removed.content ?? before);
356
+ for (const name of [...Object.keys(record.files), "installation.json"])
357
+ await replace(path.join(directory, name), undefined);
358
+ await applyNativeInstallation({ directory, outcome: "planned", writes: [...writes.values()].filter(write => write.before !== write.after) });
359
+ await fs.rmdir(directory).catch(() => undefined);
360
+ return { removed: true };
361
+ }
362
+ catch (error) {
363
+ return { removed: false, reason: error instanceof Error ? error.message : String(error) };
364
+ }
365
+ }
package/dist/printed.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { ownsTenant, propertyName } from "./command.js";
3
3
  import { CavelonError } from "./errors.js";
4
- import { shellWord } from "./shell.js";
4
+ import { currentShell, shellWord } from "./shell.js";
5
5
  export function fill(name) {
6
6
  return { placeholder: name };
7
7
  }
@@ -17,7 +17,7 @@ export function cavelonCommand(...words) {
17
17
  }
18
18
  export function folderCommand(...words) {
19
19
  const target = current.getStore();
20
- return target ? current.run({ mode: target.mode, commands: target.commands, agentShell: target.agentShell }, () => printedCommand(words)) : printedCommand(words);
20
+ return target ? current.run({ mode: target.mode, commands: target.commands, agentShell: target.agentShell, solutionDir: target.solutionDir, personCwd: target.personCwd }, () => printedCommand(words)) : printedCommand(words);
21
21
  }
22
22
  export function printedCommand(words, override = {}) {
23
23
  const target = current.getStore();
@@ -30,14 +30,24 @@ export function printedCommand(words, override = {}) {
30
30
  return call;
31
31
  }
32
32
  const line = withTarget(spec, words, { ...target, env });
33
- return commandLine(target.agentShell ? withTokenPlaceholder(line) : line);
33
+ return inPersonFolder(commandLine(target.agentShell ? withTokenPlaceholder(line) : line), target);
34
34
  }
35
- return commandLine(words);
35
+ return inPersonFolder(commandLine(words), target);
36
36
  }
37
37
  export function personCommand(...words) {
38
38
  const target = current.getStore();
39
39
  const spec = target ? commandOf(target.commands, words) : undefined;
40
- return commandLine(target && spec ? withTarget(spec, words, target) : words);
40
+ return inPersonFolder(commandLine(target && spec ? withTarget(spec, words, target) : words), target);
41
+ }
42
+ function inPersonFolder(line, target) {
43
+ if (!target?.personCwd)
44
+ return line;
45
+ const directory = shellWord(target.personCwd);
46
+ switch (currentShell()) {
47
+ case "posix": return `cd -- ${directory} && ${line}`;
48
+ case "cmd": return `cd /d ${directory} && ${line}`;
49
+ case "powershell": return `& { Set-Location -LiteralPath ${directory} -ErrorAction Stop; ${line} }`;
50
+ }
41
51
  }
42
52
  function withTokenPlaceholder(words) {
43
53
  const at = words.indexOf("--confirm");
@@ -144,6 +154,8 @@ function toolCall(target, spec, args, env) {
144
154
  out.tenant = target.tenant;
145
155
  if (env && tool.options?.env && out.env === undefined)
146
156
  out.env = env;
157
+ if (target.solutionDir !== undefined)
158
+ out.solution_dir = target.solutionDir;
147
159
  return `${tool.mcpTool} ${JSON.stringify(out)}`;
148
160
  }
149
161
  const NAMED_COMMAND = /`cavelon ([^`]+)`/g;