@cavelon/cli 0.1.15 → 0.1.17

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 (51) hide show
  1. package/README.md +44 -1
  2. package/dist/agent-env.js +3 -0
  3. package/dist/agents.js +16 -7
  4. package/dist/approval-policy.js +1 -0
  5. package/dist/commands/db.js +6 -2
  6. package/dist/commands/init.js +46 -10
  7. package/dist/commands/limits-set.js +11 -1
  8. package/dist/commands/limits.js +7 -1
  9. package/dist/commands/session.js +3 -0
  10. package/dist/commands/setup.js +18 -5
  11. package/dist/confirm-token.js +2 -1
  12. package/dist/database-limits.js +46 -0
  13. package/dist/fsutil.js +24 -7
  14. package/dist/jsonc-config.js +223 -0
  15. package/dist/kit-codes.js +1 -0
  16. package/dist/mcp-command.js +5 -0
  17. package/dist/mcp-directory.js +32 -0
  18. package/dist/mcp-entry.js +21 -0
  19. package/dist/mcp.js +18 -2
  20. package/dist/native-approval/client.js +126 -0
  21. package/dist/native-approval/ipc.js +191 -0
  22. package/dist/native-approval/kilo-server.js +33 -0
  23. package/dist/native-approval/kilo-tui.js +13 -0
  24. package/dist/native-approval/omp-extension.js +8 -0
  25. package/dist/native-approval/opencode-server.js +74 -0
  26. package/dist/native-approval/opencode-tui.js +143 -0
  27. package/dist/native-approval/pi-extension.js +86 -0
  28. package/dist/native-approval/preview-pages.js +18 -0
  29. package/dist/native-approval/profile.js +120 -0
  30. package/dist/native-assets/JSONC-LICENSE +21 -0
  31. package/dist/native-assets/LICENSE +201 -0
  32. package/dist/native-assets/MCP-SDK-LICENSE +21 -0
  33. package/dist/native-assets/THIRD-PARTY-NOTICES +386 -0
  34. package/dist/native-assets/TYPEBOX-LICENSE +23 -0
  35. package/dist/native-assets/ZOD-LICENSE +21 -0
  36. package/dist/native-assets/kilo-server.mjs +39719 -0
  37. package/dist/native-assets/kilo-tui.mjs +26477 -0
  38. package/dist/native-assets/manifest.json +82 -0
  39. package/dist/native-assets/omp-extension.mjs +30729 -0
  40. package/dist/native-assets/opencode-server.mjs +39692 -0
  41. package/dist/native-assets/opencode-tui.mjs +26474 -0
  42. package/dist/native-assets/pi-extension.mjs +30726 -0
  43. package/dist/native-assets.js +44 -0
  44. package/dist/native-clients.js +397 -0
  45. package/dist/native-install.js +390 -0
  46. package/dist/omp-config.js +85 -0
  47. package/dist/printed.js +17 -5
  48. package/dist/setup-agents.js +82 -8
  49. package/dist/skills/cavelon-loop/SKILL.md +7 -0
  50. package/dist/yaml-config.js +215 -0
  51. package/package.json +7 -3
@@ -0,0 +1,390 @@
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", "kilo", "omp"].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", "autoload"].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
+ if (ref.key === "autoload") {
116
+ if (await readTextFile(file) !== ref.member)
117
+ throw new Error("The native autoload entry was edited; personal changes are preserved.");
118
+ continue;
119
+ }
120
+ const entry = readJsoncEntry(await readTextFile(file), [ref.key]);
121
+ if ("error" in entry || !Array.isArray(entry.value) || entry.value.filter(member => isDeepStrictEqual(member, ref.member)).length !== 1
122
+ || await referenceCount(file, entry.value, ref.member) !== 1) {
123
+ throw new Error("A native plugin reference was edited or duplicated; personal settings are preserved.");
124
+ }
125
+ }
126
+ }
127
+ async function chooseFile(files, fallback) {
128
+ const present = [];
129
+ for (const file of files)
130
+ if (await readTextFile(file) !== undefined)
131
+ present.push(file);
132
+ return present.at(-1) ?? fallback;
133
+ }
134
+ async function references(client, directory, mcpFile, env, root) {
135
+ if (client === "omp")
136
+ return [{ file: path.join(path.dirname(directory), "extensions", "cavelon.js"), key: "autoload", member: 'export { default } from "../cavelon/omp-extension.mjs";\n' }];
137
+ if (client === "pi")
138
+ 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")) }];
139
+ const prefix = client.toUpperCase();
140
+ const global = path.dirname(nativeClient(client).user({ ...env, [`${prefix}_CONFIG_DIR`]: undefined }).skills);
141
+ const configDir = env[`${prefix}_CONFIG_DIR`];
142
+ const tuiConfig = env[`${prefix}_TUI_CONFIG`];
143
+ const projectDirs = client === "kilo" ? [".kilocode", ".kilo"] : [".opencode"];
144
+ const files = root ? [path.join(root, "tui.json"), path.join(root, "tui.jsonc"), ...projectDirs.flatMap(dir => [path.join(root, dir, "tui.json"), path.join(root, dir, "tui.jsonc")])] :
145
+ [path.join(global, "tui.json"), path.join(global, "tui.jsonc"), ...(tuiConfig ? [tuiConfig] : []),
146
+ ...(configDir ? [path.join(configDir, "tui.json"), path.join(configDir, "tui.jsonc")] : [])];
147
+ if (root && tuiConfig)
148
+ throw new Error(`${prefix}_TUI_CONFIG overrides project UI settings; use user setup for that configuration.`);
149
+ const fallback = !root && configDir ? path.join(configDir, "tui.json") : !root && tuiConfig ? tuiConfig : path.join(root ?? global, "tui.json");
150
+ const tuiFile = await chooseFile(files, fallback);
151
+ return [
152
+ { file: mcpFile, key: "plugin", member: memberPath(mcpFile, path.join(directory, `${client}-server-entry.mjs`)) },
153
+ { file: tuiFile, key: "plugin", member: memberPath(tuiFile, path.join(directory, `${client}-tui-entry.mjs`)) },
154
+ ];
155
+ }
156
+ export async function planNativeInstallation(config, command, env, options = {}) {
157
+ if (!hasNativeApprovalAdapter(config))
158
+ throw new Error("This client has no native person-dialog adapter.");
159
+ const root = options.root;
160
+ const expectedDirectory = root ? path.join(root, `.${config.client}`, "cavelon") : path.join(path.dirname(nativeClient(config.client).user(env).skills), "cavelon");
161
+ const directory = options.directory ?? expectedDirectory;
162
+ const skipped = (reason) => ({ directory, outcome: "skipped", reason, writes: [] });
163
+ try {
164
+ if (path.resolve(directory) !== path.resolve(expectedDirectory))
165
+ return skipped("Native config directories changed; remove the recorded integration before setting up the new location.");
166
+ const previous = await readInstallation(directory);
167
+ if (previous) {
168
+ if (previous.client !== config.client || previous.scope !== (root ? "project" : "user"))
169
+ return skipped("The native directory is owned by another integration.");
170
+ await verify(directory, previous);
171
+ }
172
+ let effective = config;
173
+ let user;
174
+ if (root) {
175
+ const userDirectory = path.join(path.dirname(nativeClient(config.client).user(env).skills), "cavelon");
176
+ user = await readInstallation(userDirectory);
177
+ if (user) {
178
+ if (user.client !== config.client || user.scope !== "user")
179
+ return skipped("The user native directory belongs to another integration.");
180
+ await verify(userDirectory, user);
181
+ const userFile = fileOf(userDirectory, user.mcp.file);
182
+ effective = { ...config, shadowFiles: config.shadowFiles?.filter(file => path.resolve(file) !== userFile) };
183
+ }
184
+ }
185
+ const selected = await resolveNativeMcp(effective, root);
186
+ if ("error" in selected)
187
+ return skipped(selected.error);
188
+ if (root && user && selected.current === undefined && !previous)
189
+ return { directory, outcome: "unchanged", reason: "The verified user native integration already serves this project; no duplicate project integration was added.", writes: [] };
190
+ if (previous && fileOf(directory, previous.mcp.file) !== selected.file)
191
+ return skipped("The selected MCP config changed; remove the recorded integration first.");
192
+ if (selected.current !== undefined && !(previous && nativeEntryHash(selected.current) === previous.mcp.hash)
193
+ && !isKitMcpEntry(selected.current, config.entryFormat, config.extra))
194
+ return skipped("A personal Cavelon server already exists; it is not owned by native setup.");
195
+ const disabled = encodeMcpEntry(command, config.entryFormat, { ...config.extra, enabled: false });
196
+ const assets = await bundledNativeAssets();
197
+ const profile = { ...(root ? { format: 2, projectRoot: portable(directory, root) } : {}),
198
+ client: config.client, version: KIT_VERSION, scope: root ? "project" : "user", configFile: root ? portable(directory, selected.file) : selected.file, entryHash: nativeEntryHash(disabled) };
199
+ const contents = new Map(assets.map(asset => [asset.path, asset.content]));
200
+ contents.set("profile.json", json(profile));
201
+ if (config.client !== "pi" && config.client !== "omp")
202
+ for (const surface of ["server", "tui"]) {
203
+ contents.set(`${config.client}-${surface}-entry.mjs`, `import adapter from "./${config.client}-${surface}.mjs";\nexport default { ...adapter, id: "cavelon.native-approval.${config.client === "kilo" ? "kilo." : ""}${root ? "project" : "user"}" };\n`);
204
+ }
205
+ const writes = new Map();
206
+ const replace = async (file, after) => {
207
+ await safeFile(file, root);
208
+ const before = await readTextFile(file);
209
+ writes.set(file, { file, before, after, mode: await fs.stat(file).then(stat => stat.mode & 0o777, () => 0o600) });
210
+ };
211
+ for (const [name, content] of contents) {
212
+ if (previous && !(name in previous.files) && await readTextFile(path.join(directory, name)) !== undefined)
213
+ return skipped(`The new native asset ${name} belongs to a personal file; it is preserved.`);
214
+ await replace(path.join(directory, name), content);
215
+ }
216
+ const refs = [];
217
+ for (const ref of await references(config.client, directory, selected.file, env, root)) {
218
+ const before = writes.get(ref.file)?.after ?? await readTextFile(ref.file);
219
+ if (ref.key === "autoload") {
220
+ if (before !== undefined && !previous)
221
+ return skipped("The native autoload entry belongs to a personal extension; it is preserved.");
222
+ await replace(ref.file, ref.member);
223
+ refs.push({ file: root ? portable(directory, ref.file) : ref.file, key: ref.key, member: ref.member, created: true, kept: false });
224
+ continue;
225
+ }
226
+ if (config.client === "pi" && before !== undefined) {
227
+ try {
228
+ JSON.parse(before);
229
+ }
230
+ catch {
231
+ return skipped("Pi settings require plain JSON; correct the file before native installation.");
232
+ }
233
+ }
234
+ for (const id of ["cavelon.native-approval", `cavelon.native-approval.${root ? "project" : "user"}`,
235
+ ...(config.client === "kilo" ? ["cavelon.native-approval.kilo", `cavelon.native-approval.kilo.${root ? "project" : "user"}`] : [])]) {
236
+ const enabled = readJsoncEntry(before, ["plugin_enabled", id]);
237
+ if ("error" in enabled)
238
+ return skipped(enabled.error);
239
+ if (enabled.value === false)
240
+ return skipped("The person turned off the Cavelon plugin; setup does not enable it.");
241
+ }
242
+ const current = readJsoncEntry(before, [ref.key]);
243
+ if ("error" in current)
244
+ return skipped(current.error);
245
+ if (Array.isArray(current.value)) {
246
+ const aliases = await referenceCount(ref.file, current.value, ref.member);
247
+ if (aliases > 1 || (aliases === 1 && !current.value.includes(ref.member)))
248
+ return skipped("An aliased or duplicate Cavelon plugin reference exists; review it manually.");
249
+ }
250
+ const added = appendJsoncMember(before, [ref.key], ref.member);
251
+ if (added.outcome === "skipped")
252
+ return skipped(added.reason);
253
+ if (!previous && added.outcome === "unchanged")
254
+ return skipped("An existing native plugin reference is not owned by setup; review it manually.");
255
+ await replace(ref.file, added.content ?? before);
256
+ const old = previous?.references.find(item => fileOf(directory, item.file) === ref.file && item.key === ref.key && item.member === ref.member);
257
+ 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 });
258
+ }
259
+ if (previous && previous.references.some(old => !refs.some(ref => isDeepStrictEqual(ref, old))))
260
+ return skipped("Native reference locations changed; remove the recorded integration first.");
261
+ const before = writes.get(selected.file)?.after ?? selected.text;
262
+ const entry = upsertJsoncEntry(before, config.keys, disabled, { matches: value => isKitMcpEntry(value, config.entryFormat, config.extra)
263
+ || Boolean(previous && nativeEntryHash(value) === previous.mcp.hash) });
264
+ if (entry.outcome === "skipped")
265
+ return skipped(entry.reason);
266
+ await replace(selected.file, entry.content ?? before);
267
+ const record = { format: 1, client: config.client, scope: root ? "project" : "user", version: KIT_VERSION,
268
+ ...(root ? { projectRoot: portable(directory, root) } : {}), files: Object.fromEntries([...contents].map(([name, content]) => [name, hash(content)])),
269
+ 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 };
270
+ await replace(path.join(directory, "installation.json"), json(record));
271
+ const changed = [...writes.values()].filter(write => write.before !== write.after);
272
+ return { directory, outcome: changed.length ? "planned" : "unchanged", writes: changed };
273
+ }
274
+ catch (error) {
275
+ return skipped(error instanceof Error ? error.message : String(error));
276
+ }
277
+ }
278
+ export async function applyNativeInstallation(plan, writer = writeFileAtomic) {
279
+ if (plan.outcome !== "planned")
280
+ return;
281
+ await fs.mkdir(path.dirname(plan.directory), { recursive: true, mode: 0o700 });
282
+ const lockFile = plan.directory + ".lock";
283
+ const lock = await fs.open(lockFile, "wx", 0o600).catch(error => {
284
+ if (error.code === "EEXIST")
285
+ throw new Error("Another native installer holds this directory's lock; inspect it before retrying.");
286
+ throw error;
287
+ });
288
+ const lockIdentity = await lock.stat();
289
+ const done = [];
290
+ try {
291
+ await lock.writeFile(`cavelon-native ${process.pid}\n`);
292
+ for (const write of plan.writes) {
293
+ await safeFile(write.file);
294
+ if (await readTextFile(write.file) !== write.before)
295
+ throw new Error("Native configuration changed after planning; no further edits were made.");
296
+ done.push(write);
297
+ if (write.after === undefined)
298
+ await fs.rm(write.file);
299
+ else
300
+ await writer(write.file, write.after, write.mode, 0o700);
301
+ }
302
+ }
303
+ catch (error) {
304
+ for (const write of done.reverse()) {
305
+ if (await readTextFile(write.file) !== write.after)
306
+ continue;
307
+ if (write.before === undefined)
308
+ await fs.rm(write.file, { force: true });
309
+ else
310
+ await writeFileAtomic(write.file, write.before, write.mode, 0o700);
311
+ }
312
+ await fs.rmdir(plan.directory).catch(() => undefined);
313
+ throw error;
314
+ }
315
+ finally {
316
+ await lock.close();
317
+ const stat = await fs.lstat(lockFile).catch(() => undefined);
318
+ if (stat?.isFile() && stat.dev === lockIdentity.dev && stat.ino === lockIdentity.ino)
319
+ await fs.rm(lockFile);
320
+ }
321
+ }
322
+ export async function checkNativeInstallation(directory) {
323
+ try {
324
+ const record = await readInstallation(directory);
325
+ if (!record)
326
+ throw new Error("No recorded native installation exists.");
327
+ await verify(directory, record);
328
+ for (const ref of record.references) {
329
+ if (ref.key === "autoload")
330
+ continue;
331
+ const text = await readTextFile(fileOf(directory, ref.file));
332
+ for (const id of ["cavelon.native-approval", `cavelon.native-approval.${record.scope}`,
333
+ ...(record.client === "kilo" ? ["cavelon.native-approval.kilo", `cavelon.native-approval.kilo.${record.scope}`] : [])]) {
334
+ const enabled = readJsoncEntry(text, ["plugin_enabled", id]);
335
+ if ("error" in enabled)
336
+ throw new Error(enabled.error);
337
+ if (enabled.value === false)
338
+ throw new Error("The person turned off the Cavelon plugin; enable it in the client only if intended.");
339
+ }
340
+ }
341
+ const config = nativeClient(record.client).project();
342
+ const entry = readNativeMcp(await readTextFile(fileOf(directory, record.mcp.file)), config);
343
+ if ("error" in entry)
344
+ throw new Error(entry.error);
345
+ return { command: decodeMcpEntry(entry.value, config.entryFormat) };
346
+ }
347
+ catch (error) {
348
+ return { reason: error instanceof Error ? error.message : String(error) };
349
+ }
350
+ }
351
+ export async function removeNativeInstallation(directory) {
352
+ try {
353
+ const record = await readInstallation(directory);
354
+ if (!record)
355
+ return { removed: true };
356
+ await verify(directory, record);
357
+ const writes = new Map();
358
+ const replace = async (file, after) => {
359
+ const before = await readTextFile(file);
360
+ writes.set(file, { file, before, after, mode: await fs.stat(file).then(stat => stat.mode & 0o777, () => 0o600) });
361
+ };
362
+ for (const ref of record.references) {
363
+ const file = fileOf(directory, ref.file);
364
+ const before = writes.get(file)?.after ?? await readTextFile(file);
365
+ if (ref.key === "autoload") {
366
+ await replace(file, undefined);
367
+ continue;
368
+ }
369
+ const removed = removeJsoncMember(before, [ref.key], ref.member, { removeEmpty: !ref.kept });
370
+ if (removed.outcome === "skipped")
371
+ throw new Error(removed.reason);
372
+ await replace(file, removed.empty && ref.created ? undefined : removed.content ?? before);
373
+ }
374
+ const mcpFile = fileOf(directory, record.mcp.file);
375
+ const before = writes.get(mcpFile)?.after ?? await readTextFile(mcpFile);
376
+ const config = nativeClient(record.client).project();
377
+ const removed = removeJsoncEntry(before, config.keys, value => nativeEntryHash(value) === record.mcp.hash, record.mcp.kept);
378
+ if (removed.outcome === "skipped")
379
+ throw new Error(removed.reason);
380
+ await replace(mcpFile, removed.empty && record.mcp.created ? undefined : removed.content ?? before);
381
+ for (const name of [...Object.keys(record.files), "installation.json"])
382
+ await replace(path.join(directory, name), undefined);
383
+ await applyNativeInstallation({ directory, outcome: "planned", writes: [...writes.values()].filter(write => write.before !== write.after) });
384
+ await fs.rmdir(directory).catch(() => undefined);
385
+ return { removed: true };
386
+ }
387
+ catch (error) {
388
+ return { removed: false, reason: error instanceof Error ? error.message : String(error) };
389
+ }
390
+ }
@@ -0,0 +1,85 @@
1
+ import path from "node:path";
2
+ import { homeDir } from "./paths.js";
3
+ import { readTextFile } from "./fsutil.js";
4
+ import { readJsoncEntry } from "./jsonc-config.js";
5
+ export function ompDirectory(env) {
6
+ const home = homeDir(env);
7
+ const root = path.join(home, env.PI_CONFIG_DIR || ".omp");
8
+ const profile = (env.OMP_PROFILE !== undefined ? env.OMP_PROFILE : env.PI_PROFILE)?.trim();
9
+ if (profile && profile !== "default") {
10
+ if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(profile) || profile === ".." || profile.endsWith(".") || /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\..*)?$/i.test(profile)) {
11
+ return { directory: path.join(root, "agent"), blocked: "Invalid OMP profile; select a valid profile before setup." };
12
+ }
13
+ return { directory: path.join(root, "profiles", profile, "agent") };
14
+ }
15
+ return { directory: env.PI_CODING_AGENT_DIR ? path.resolve(env.PI_CODING_AGENT_DIR) : path.join(root, "agent") };
16
+ }
17
+ const nativeFiles = (directory) => [path.join(directory, "mcp.json"), path.join(directory, ".mcp.json")];
18
+ const compatibleFiles = (directory) => [
19
+ ".claude.json", ".mcp.json", "mcp.json", ".claude/.mcp.json", ".cursor/mcp.json", ".vscode/mcp.json",
20
+ ".gemini/settings.json", ".qwen/settings.json", ".opencode/opencode.json", ".opencode/opencode.jsonc",
21
+ "opencode.json", "opencode.jsonc", ".codex/config.toml",
22
+ ].map(file => path.join(directory, file));
23
+ export function ompConfig(env, project = false) {
24
+ const user = ompDirectory(env);
25
+ const directory = project ? ".omp" : user.directory;
26
+ return {
27
+ client: "omp", format: "native", file: path.join(directory, "mcp.json"), files: nativeFiles(directory),
28
+ syntax: "json", keys: ["mcpServers", "cavelon"], entryFormat: "command-args", extra: {},
29
+ compatibilityFiles: compatibleFiles(project ? "." : homeDir(env)),
30
+ ...(project ? { shadowFiles: nativeFiles(user.directory), managedFiles: [path.join(user.directory, "mcp.json")] } : {}),
31
+ ...(user.blocked ? { blocked: user.blocked } : {}),
32
+ };
33
+ }
34
+ export function ompListPolicy(text) {
35
+ for (const key of ["disabledServers", "enabledServers"]) {
36
+ const selected = readJsoncEntry(text, [key]);
37
+ if ("error" in selected)
38
+ return selected.error;
39
+ if (selected.value === undefined)
40
+ continue;
41
+ if (!Array.isArray(selected.value) || !selected.value.every(value => typeof value === "string"))
42
+ return `The OMP ${key} policy is invalid; review it manually.`;
43
+ if (selected.value.includes("cavelon"))
44
+ return `The OMP ${key} policy names Cavelon; review it in OMP before native setup.`;
45
+ }
46
+ return undefined;
47
+ }
48
+ export async function ompRuntimePolicy(configFile, env) {
49
+ const files = new Set([...nativeFiles(path.dirname(configFile)), path.join(ompDirectory(env).directory, "mcp.json")]);
50
+ for (const file of files) {
51
+ const error = ompListPolicy(await readTextFile(file));
52
+ if (error)
53
+ return `${file}: ${error}`;
54
+ }
55
+ return undefined;
56
+ }
57
+ export async function ompPolicy(config, full) {
58
+ for (const file of new Set([...(config.managedFiles ?? []), ...config.files.map(full)])) {
59
+ const error = ompListPolicy(await readTextFile(file));
60
+ if (error)
61
+ return `${file}: ${error}`;
62
+ }
63
+ for (const candidate of config.compatibilityFiles ?? []) {
64
+ const file = full(candidate);
65
+ const error = compatiblePolicy(await readTextFile(file), file);
66
+ if (error)
67
+ return error;
68
+ }
69
+ return undefined;
70
+ }
71
+ function compatiblePolicy(text, file) {
72
+ if (text === undefined)
73
+ return undefined;
74
+ if (file.endsWith(".toml")) {
75
+ return /cavelon/i.test(text) ? `A compatible Cavelon binding may exist in ${file}; inspect its TOML before OMP setup.` : undefined;
76
+ }
77
+ for (const key of ["mcpServers", "mcp", "servers"]) {
78
+ const selected = readJsoncEntry(text, [key, "cavelon"]);
79
+ if ("error" in selected)
80
+ return `${file}: ${selected.error}`;
81
+ if (selected.value !== undefined)
82
+ return `A compatible Cavelon server in ${file} is preserved; review that binding before OMP setup.`;
83
+ }
84
+ return undefined;
85
+ }
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;