@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.
- package/README.md +12 -0
- package/dist/agent-env.js +2 -0
- package/dist/agents.js +14 -7
- package/dist/approval-policy.js +1 -0
- package/dist/commands/init.js +46 -10
- package/dist/commands/session.js +3 -0
- package/dist/commands/setup.js +17 -4
- package/dist/confirm-token.js +2 -1
- package/dist/fsutil.js +24 -7
- package/dist/jsonc-config.js +223 -0
- package/dist/kit-codes.js +1 -0
- package/dist/mcp-command.js +5 -0
- package/dist/mcp-directory.js +32 -0
- package/dist/mcp-entry.js +21 -0
- package/dist/mcp.js +18 -2
- package/dist/native-approval/client.js +126 -0
- package/dist/native-approval/ipc.js +191 -0
- package/dist/native-approval/opencode-server.js +74 -0
- package/dist/native-approval/opencode-tui.js +143 -0
- package/dist/native-approval/pi-extension.js +84 -0
- package/dist/native-approval/preview-pages.js +18 -0
- package/dist/native-approval/profile.js +113 -0
- package/dist/native-assets/JSONC-LICENSE +21 -0
- package/dist/native-assets/LICENSE +201 -0
- package/dist/native-assets/MCP-SDK-LICENSE +21 -0
- package/dist/native-assets/THIRD-PARTY-NOTICES +368 -0
- package/dist/native-assets/TYPEBOX-LICENSE +23 -0
- package/dist/native-assets/ZOD-LICENSE +21 -0
- package/dist/native-assets/manifest.json +60 -0
- package/dist/native-assets/opencode-server.mjs +32273 -0
- package/dist/native-assets/opencode-tui.mjs +19055 -0
- package/dist/native-assets/pi-extension.mjs +23302 -0
- package/dist/native-assets.js +44 -0
- package/dist/native-clients.js +181 -0
- package/dist/native-install.js +365 -0
- package/dist/printed.js +17 -5
- package/dist/setup-agents.js +73 -8
- package/dist/skills/cavelon-loop/SKILL.md +7 -0
- package/package.json +7 -3
package/dist/mcp.js
CHANGED
|
@@ -5,6 +5,7 @@ import { formerlyWarning, ownsTenant, propertyName } from "./command.js";
|
|
|
5
5
|
import { MCP_MAX_WAIT_MS } from "./commands/async.js";
|
|
6
6
|
import { PERSON_WAIT_MS } from "./confirm-token.js";
|
|
7
7
|
import { createContext, withWarnings } from "./context.js";
|
|
8
|
+
import { solutionDirectory } from "./mcp-directory.js";
|
|
8
9
|
import { asCavelonError, CavelonError, ExitCode, usageError } from "./errors.js";
|
|
9
10
|
import { closest } from "./package-references.js";
|
|
10
11
|
import { printingFor, spoken, spokenError, spokenHints } from "./printed.js";
|
|
@@ -50,6 +51,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
|
|
|
50
51
|
"Run from your shell, cavelon's api command applies the same guards, and sends a changing operation only with --confirm and the token " +
|
|
51
52
|
"its preview printed. Tools read and write files only " +
|
|
52
53
|
"inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
|
|
54
|
+
"directories. In a repository with several solutions, pass solution_dir to select a folder inside the server's startup workspace. " +
|
|
55
|
+
"Use the same solution_dir for preview, confirmation and follow-up tools; harness selects an instance solution, not its local folder. Never infer a folder from a harness name. " +
|
|
56
|
+
"Tools cannot select a folder outside the original workspace or in cavelon's " +
|
|
53
57
|
"config or cache directory. Read limits before planning a solution: it lists what the " +
|
|
54
58
|
"instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
|
|
55
59
|
"Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
|
|
@@ -122,6 +126,11 @@ export function inputSchema(spec, commands = []) {
|
|
|
122
126
|
description: "Tenant slug or id, when not the one chosen for this directory or with use_tenant in this session. A preview names the tenant it acts on.",
|
|
123
127
|
};
|
|
124
128
|
}
|
|
129
|
+
properties.solution_dir = {
|
|
130
|
+
type: "string",
|
|
131
|
+
minLength: 1,
|
|
132
|
+
description: "Solution folder inside this MCP session's workspace, relative to its startup folder or an absolute path inside it. Omit to use the startup folder. Use the same folder for preview, confirmation and follow-up calls; harness selects an instance solution, not this folder.",
|
|
133
|
+
};
|
|
125
134
|
return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
|
|
126
135
|
}
|
|
127
136
|
export function notForThisCredential(spec, access) {
|
|
@@ -286,14 +295,21 @@ export function createMcpServer(io, commands, updates = {}) {
|
|
|
286
295
|
}
|
|
287
296
|
const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
|
|
288
297
|
const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
|
|
289
|
-
|
|
298
|
+
let folder;
|
|
299
|
+
try {
|
|
300
|
+
folder = await solutionDirectory(io, args.solution_dir);
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
return fail(error);
|
|
304
|
+
}
|
|
305
|
+
const ctx = createContext(mcpIo(folder.io), { json: true, tenant, solutionEnv, sessionTenants }, "mcp");
|
|
290
306
|
if (clientAsks(server))
|
|
291
307
|
ctx.askPerson = (message) => askThroughClient(server, message, requestId);
|
|
292
308
|
for (const message of renamed)
|
|
293
309
|
ctx.warn(message);
|
|
294
310
|
try {
|
|
295
311
|
const chosen = tenant ?? (await ctx.session().then((s) => (s.tenantSource === "session" ? s.tenant : undefined), () => undefined));
|
|
296
|
-
const { result, warnings } = await printingFor({ mode: "mcp", commands, ...(spec.storesTarget ? {} : { tenant: chosen, env: solutionEnv }) }, async () => {
|
|
312
|
+
const { result, warnings } = await printingFor({ mode: "mcp", commands, solutionDir: folder.selected, personCwd: folder.directory, ...(spec.storesTarget ? {} : { tenant: chosen, env: solutionEnv }) }, async () => {
|
|
297
313
|
try {
|
|
298
314
|
const done = await spec.run(ctx, inputFrom(spec, args));
|
|
299
315
|
return { result: { ...done, data: spokenHints(done.data) }, warnings: ctx.warnings.map(spoken) };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
3
|
+
import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
4
|
+
import { PERSON_WAIT_MS } from "../approval-policy.js";
|
|
5
|
+
export class NativeApprovalClient {
|
|
6
|
+
options;
|
|
7
|
+
client;
|
|
8
|
+
waitMs;
|
|
9
|
+
closed = false;
|
|
10
|
+
tail = Promise.resolve();
|
|
11
|
+
active;
|
|
12
|
+
closing;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.options = options;
|
|
15
|
+
this.waitMs = options.waitMs ?? PERSON_WAIT_MS;
|
|
16
|
+
if (!Number.isFinite(this.waitMs) || this.waitMs <= 0 || this.waitMs > PERSON_WAIT_MS) {
|
|
17
|
+
throw new Error("The native person wait must be positive and at most ten minutes.");
|
|
18
|
+
}
|
|
19
|
+
this.client = new Client({ name: "cavelon-native", version: options.version }, {
|
|
20
|
+
capabilities: options.interactive ? { elicitation: { form: {} } } : {},
|
|
21
|
+
});
|
|
22
|
+
if (options.interactive)
|
|
23
|
+
this.client.setRequestHandler(ElicitRequestSchema, async (request, extra) => {
|
|
24
|
+
const call = this.active;
|
|
25
|
+
if (request.params.mode === "url")
|
|
26
|
+
return { action: "cancel" };
|
|
27
|
+
const schema = request.params.requestedSchema;
|
|
28
|
+
if (!call || call.dialog || call.controller.signal.aborted || schema.type !== "object"
|
|
29
|
+
|| schema.required?.length !== 1 || schema.required[0] !== "approve"
|
|
30
|
+
|| Object.keys(schema.properties).length !== 1 || schema.properties.approve?.type !== "boolean") {
|
|
31
|
+
return { action: "cancel" };
|
|
32
|
+
}
|
|
33
|
+
call.dialog = true;
|
|
34
|
+
const signal = AbortSignal.any([call.controller.signal, extra.signal]);
|
|
35
|
+
try {
|
|
36
|
+
if (signal.aborted || !call.ask)
|
|
37
|
+
return { action: "cancel" };
|
|
38
|
+
const answer = await Promise.race([
|
|
39
|
+
call.ask(request.params.message, signal, this.waitMs),
|
|
40
|
+
new Promise(resolve => signal.addEventListener("abort", () => resolve(undefined), { once: true })),
|
|
41
|
+
]);
|
|
42
|
+
if (signal.aborted || this.active !== call || answer !== true)
|
|
43
|
+
return { action: "decline" };
|
|
44
|
+
return { action: "accept", content: { approve: true } };
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return { action: "cancel" };
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
call.dialog = false;
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
this.client.onclose = () => {
|
|
54
|
+
this.closed = true;
|
|
55
|
+
this.active?.controller.abort();
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async connect() {
|
|
59
|
+
try {
|
|
60
|
+
await this.client.connect(this.options.transport, { timeout: 15_000 });
|
|
61
|
+
return this;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
await this.close().catch(() => undefined);
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async tools() {
|
|
69
|
+
const tools = [];
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
let cursor;
|
|
72
|
+
for (let pageNumber = 0; pageNumber < 128; pageNumber++) {
|
|
73
|
+
const page = await this.client.listTools(cursor ? { cursor } : undefined, { timeout: 15_000 });
|
|
74
|
+
tools.push(...page.tools);
|
|
75
|
+
if (!page.nextCursor)
|
|
76
|
+
return tools;
|
|
77
|
+
if (seen.has(page.nextCursor))
|
|
78
|
+
throw new Error("The Cavelon tool list repeated its pagination cursor.");
|
|
79
|
+
seen.add(page.nextCursor);
|
|
80
|
+
cursor = page.nextCursor;
|
|
81
|
+
}
|
|
82
|
+
throw new Error("The Cavelon tool list exceeded its bounded page limit.");
|
|
83
|
+
}
|
|
84
|
+
call(name, args = {}, options = {}) {
|
|
85
|
+
const run = async () => {
|
|
86
|
+
if (this.closed || options.signal?.aborted)
|
|
87
|
+
throw new Error("Cavelon call cancelled or disconnected.");
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const active = { controller, ask: options.ask, dialog: false };
|
|
90
|
+
const abort = () => controller.abort();
|
|
91
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
92
|
+
const timer = setTimeout(abort, this.waitMs);
|
|
93
|
+
this.active = active;
|
|
94
|
+
try {
|
|
95
|
+
return await this.client.callTool({ name, arguments: args }, undefined, {
|
|
96
|
+
signal: controller.signal, timeout: this.waitMs + 15_000,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
const cancelled = controller.signal.aborted;
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
options.signal?.removeEventListener("abort", abort);
|
|
103
|
+
controller.abort();
|
|
104
|
+
this.active = undefined;
|
|
105
|
+
if (cancelled || this.closed)
|
|
106
|
+
await this.close();
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
const result = this.tail.then(run, run);
|
|
110
|
+
this.tail = result.catch(() => undefined);
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
close() {
|
|
114
|
+
if (!this.closing) {
|
|
115
|
+
this.closed = true;
|
|
116
|
+
this.active?.controller.abort();
|
|
117
|
+
this.closing = this.client.close();
|
|
118
|
+
}
|
|
119
|
+
return this.closing;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
export async function nativeStdioClient(command, interactive, version) {
|
|
123
|
+
const transport = new StdioClientTransport({ ...command, stderr: "pipe" });
|
|
124
|
+
transport.stderr?.on("data", () => undefined);
|
|
125
|
+
return new NativeApprovalClient({ transport, interactive, version }).connect();
|
|
126
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createConnection, createServer } from "node:net";
|
|
2
|
+
import { randomUUID, randomBytes } from "node:crypto";
|
|
3
|
+
import { promises as fs } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { StringDecoder } from "node:string_decoder";
|
|
6
|
+
import { PERSON_WAIT_MS } from "../approval-policy.js";
|
|
7
|
+
const MAX_FRAME = 4 * 1024 * 1024;
|
|
8
|
+
const MAX_UIS = 16;
|
|
9
|
+
export class NativeUiUnavailable extends Error {
|
|
10
|
+
}
|
|
11
|
+
async function privatePath(file, directory) {
|
|
12
|
+
const stat = await fs.lstat(file);
|
|
13
|
+
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile())
|
|
14
|
+
|| (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0))) {
|
|
15
|
+
throw new Error("The native UI path must be private and owned by this person.");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function frame(consume, fail) {
|
|
19
|
+
const decoder = new StringDecoder("utf8");
|
|
20
|
+
let input = "";
|
|
21
|
+
let bytes = 0;
|
|
22
|
+
let done = false;
|
|
23
|
+
return chunk => {
|
|
24
|
+
if (done)
|
|
25
|
+
return;
|
|
26
|
+
bytes += chunk.length;
|
|
27
|
+
if (bytes > MAX_FRAME) {
|
|
28
|
+
done = true;
|
|
29
|
+
fail();
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
input += decoder.write(chunk);
|
|
33
|
+
const end = input.indexOf("\n");
|
|
34
|
+
if (end < 0)
|
|
35
|
+
return;
|
|
36
|
+
done = true;
|
|
37
|
+
consume(input.slice(0, end));
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export async function startUiSocket(directory, currentSession, invoke) {
|
|
41
|
+
await fs.mkdir(directory, { mode: 0o700 }).catch(error => { if (error.code !== "EEXIST")
|
|
42
|
+
throw error; });
|
|
43
|
+
await privatePath(directory, true);
|
|
44
|
+
const privateDir = await fs.mkdtemp(path.join(directory, "tui-"));
|
|
45
|
+
await fs.chmod(privateDir, 0o700);
|
|
46
|
+
const key = randomBytes(32).toString("hex");
|
|
47
|
+
const address = process.platform === "win32" ? `\\\\.\\pipe\\cavelon-ui-${randomUUID()}` : path.join(privateDir, "ui.sock");
|
|
48
|
+
if (process.platform !== "win32" && Buffer.byteLength(address) > 103) {
|
|
49
|
+
await fs.rm(privateDir, { recursive: true, force: true });
|
|
50
|
+
throw new Error("Native UI socket path is too long; use the short Cavelon runtime directory.");
|
|
51
|
+
}
|
|
52
|
+
const descriptor = path.join(privateDir, "runtime.json");
|
|
53
|
+
const sockets = new Set();
|
|
54
|
+
const server = createServer(socket => {
|
|
55
|
+
sockets.add(socket);
|
|
56
|
+
const abort = new AbortController();
|
|
57
|
+
const timer = setTimeout(() => { abort.abort(); socket.destroy(); }, PERSON_WAIT_MS + 15_000);
|
|
58
|
+
socket.on("close", () => { clearTimeout(timer); sockets.delete(socket); abort.abort(); });
|
|
59
|
+
socket.on("error", () => abort.abort());
|
|
60
|
+
socket.on("data", frame(input => {
|
|
61
|
+
void (async () => {
|
|
62
|
+
try {
|
|
63
|
+
const request = JSON.parse(input);
|
|
64
|
+
if (request.key !== key)
|
|
65
|
+
throw new Error("Unbound native UI request.");
|
|
66
|
+
let result;
|
|
67
|
+
if (request.operation === "hello")
|
|
68
|
+
result = { session: currentSession() };
|
|
69
|
+
else if (request.operation === "call" && typeof request.session === "string" && currentSession() === request.session
|
|
70
|
+
&& typeof request.name === "string" && request.arguments && typeof request.arguments === "object" && !Array.isArray(request.arguments)) {
|
|
71
|
+
result = await invoke(request.name, request.arguments, request.session, abort.signal);
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
throw new Error("No native tool call for this session.");
|
|
75
|
+
const output = JSON.stringify({ result }) + "\n";
|
|
76
|
+
if (Buffer.byteLength(output) > MAX_FRAME)
|
|
77
|
+
throw new Error("Native UI response too large.");
|
|
78
|
+
if (!socket.destroyed)
|
|
79
|
+
socket.end(output);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
if (!socket.destroyed)
|
|
83
|
+
socket.end(JSON.stringify({ error: "Native UI call failed; its outcome may be unknown. Do not retry automatically." }) + "\n");
|
|
84
|
+
}
|
|
85
|
+
})();
|
|
86
|
+
}, () => socket.destroy()));
|
|
87
|
+
});
|
|
88
|
+
try {
|
|
89
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(address, resolve); });
|
|
90
|
+
if (process.platform !== "win32")
|
|
91
|
+
await fs.chmod(address, 0o600);
|
|
92
|
+
await fs.writeFile(descriptor, JSON.stringify({ address, key }) + "\n", { mode: 0o600, flag: "wx" });
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
server.close();
|
|
96
|
+
await fs.rm(privateDir, { recursive: true, force: true });
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
let closing;
|
|
100
|
+
return {
|
|
101
|
+
descriptor,
|
|
102
|
+
close() {
|
|
103
|
+
return closing ??= (async () => {
|
|
104
|
+
for (const socket of sockets)
|
|
105
|
+
socket.destroy();
|
|
106
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
107
|
+
await fs.rm(privateDir, { recursive: true, force: true });
|
|
108
|
+
await fs.rmdir(directory).catch(() => undefined);
|
|
109
|
+
})();
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
async function requestSocket(descriptor, body, signal, timeout) {
|
|
114
|
+
await privatePath(path.dirname(descriptor), true);
|
|
115
|
+
await privatePath(descriptor, false);
|
|
116
|
+
const parsed = JSON.parse(await fs.readFile(descriptor, "utf8"));
|
|
117
|
+
if (typeof parsed.key !== "string" || !/^[a-f0-9]{64}$/.test(parsed.key) || typeof parsed.address !== "string"
|
|
118
|
+
|| (process.platform === "win32" ? !/^\\\\\.\\pipe\\cavelon-ui-[a-f0-9-]+$/.test(parsed.address) : parsed.address !== path.join(path.dirname(descriptor), "ui.sock"))) {
|
|
119
|
+
throw new Error("Invalid native UI descriptor.");
|
|
120
|
+
}
|
|
121
|
+
if (signal?.aborted)
|
|
122
|
+
throw new Error("Cavelon call cancelled.");
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
const socket = createConnection(parsed.address);
|
|
125
|
+
const timer = setTimeout(() => socket.destroy(new Error("Native UI timeout.")), timeout);
|
|
126
|
+
const abort = () => socket.destroy(new Error("Cavelon call cancelled."));
|
|
127
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
128
|
+
let done = false;
|
|
129
|
+
const finish = (error, value) => {
|
|
130
|
+
if (done)
|
|
131
|
+
return;
|
|
132
|
+
done = true;
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
signal?.removeEventListener("abort", abort);
|
|
135
|
+
socket.destroy();
|
|
136
|
+
if (error)
|
|
137
|
+
reject(error);
|
|
138
|
+
else
|
|
139
|
+
resolve(value);
|
|
140
|
+
};
|
|
141
|
+
socket.once("connect", () => {
|
|
142
|
+
const output = JSON.stringify({ ...body, key: parsed.key }) + "\n";
|
|
143
|
+
if (Buffer.byteLength(output) > MAX_FRAME)
|
|
144
|
+
finish(new Error("Native UI request too large."));
|
|
145
|
+
else
|
|
146
|
+
socket.write(output);
|
|
147
|
+
});
|
|
148
|
+
socket.once("error", error => finish(error));
|
|
149
|
+
socket.once("close", () => finish(new Error("Native UI disconnected.")));
|
|
150
|
+
socket.on("data", frame(input => {
|
|
151
|
+
try {
|
|
152
|
+
const response = JSON.parse(input);
|
|
153
|
+
finish(response.error ? new Error("Native UI call failed; do not retry automatically.") : undefined, response.result);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
finish(new Error("Invalid native UI response."));
|
|
157
|
+
}
|
|
158
|
+
}, () => finish(new Error("Native UI response too large."))));
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
export async function callUi(directory, session, name, args, signal, timeout = PERSON_WAIT_MS + 15_000) {
|
|
162
|
+
try {
|
|
163
|
+
await privatePath(directory, true);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (error.code === "ENOENT")
|
|
167
|
+
throw new NativeUiUnavailable("No native TUI displays this session.");
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
const entries = (await fs.readdir(directory, { withFileTypes: true })).filter(item => item.isDirectory() && item.name.startsWith("tui-"));
|
|
171
|
+
if (entries.length > MAX_UIS)
|
|
172
|
+
throw new Error("Too many native UI descriptors; close inactive clients and inspect the runtime directory.");
|
|
173
|
+
const candidates = await Promise.all(entries.map(async (entry) => {
|
|
174
|
+
const descriptor = path.join(directory, entry.name, "runtime.json");
|
|
175
|
+
try {
|
|
176
|
+
const hello = await requestSocket(descriptor, { operation: "hello" }, signal, 1000);
|
|
177
|
+
return hello.session === session ? descriptor : undefined;
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
}));
|
|
183
|
+
if (signal?.aborted)
|
|
184
|
+
throw new Error("Cavelon call cancelled.");
|
|
185
|
+
const matches = candidates.filter((item) => item !== undefined);
|
|
186
|
+
if (!matches.length)
|
|
187
|
+
throw new NativeUiUnavailable("No native TUI displays this session.");
|
|
188
|
+
if (matches.length !== 1)
|
|
189
|
+
throw new Error("Multiple native TUIs display this session; choose one before calling Cavelon.");
|
|
190
|
+
return requestSocket(matches[0], { operation: "call", session, name, arguments: args }, signal, timeout);
|
|
191
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { nativeStdioClient } from "./client.js";
|
|
4
|
+
import { callUi, NativeUiUnavailable } from "./ipc.js";
|
|
5
|
+
import { assertNativeWorkspace, hasNativeProjectOwner, loadNativeRuntime } from "./profile.js";
|
|
6
|
+
import { PERSON_WAIT_MS } from "../approval-policy.js";
|
|
7
|
+
function toolArguments(input) {
|
|
8
|
+
const schema = z.fromJSONSchema(input);
|
|
9
|
+
if (!(schema instanceof z.ZodObject))
|
|
10
|
+
throw new Error("A Cavelon tool must declare an object input schema.");
|
|
11
|
+
return schema.shape;
|
|
12
|
+
}
|
|
13
|
+
export async function startOpenCodeServer(input, options) {
|
|
14
|
+
await assertNativeWorkspace(options, input.directory);
|
|
15
|
+
if (await hasNativeProjectOwner(options, "opencode", input.directory))
|
|
16
|
+
return { dispose: async () => undefined, tool: {} };
|
|
17
|
+
const command = { ...options.command, cwd: input.directory };
|
|
18
|
+
const discovery = await nativeStdioClient(command, false, options.version);
|
|
19
|
+
const tools = await discovery.tools().finally(() => discovery.close());
|
|
20
|
+
let fallback;
|
|
21
|
+
let disposed = false;
|
|
22
|
+
const headless = async () => {
|
|
23
|
+
if (disposed)
|
|
24
|
+
throw new Error("Cavelon adapter closed.");
|
|
25
|
+
const previous = fallback;
|
|
26
|
+
if (previous && (await previous).closed && fallback === previous)
|
|
27
|
+
fallback = undefined;
|
|
28
|
+
if (!fallback) {
|
|
29
|
+
const opening = nativeStdioClient(command, false, options.version);
|
|
30
|
+
fallback = opening;
|
|
31
|
+
opening.catch(() => { if (fallback === opening)
|
|
32
|
+
fallback = undefined; });
|
|
33
|
+
}
|
|
34
|
+
return fallback;
|
|
35
|
+
};
|
|
36
|
+
const dispose = async () => {
|
|
37
|
+
disposed = true;
|
|
38
|
+
await (await fallback?.catch(() => undefined))?.close();
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
dispose,
|
|
42
|
+
tool: Object.fromEntries(tools.map(tool => [`cavelon_${tool.name}`, {
|
|
43
|
+
description: tool.description ?? tool.name,
|
|
44
|
+
args: toolArguments(tool.inputSchema),
|
|
45
|
+
async execute(args, context) {
|
|
46
|
+
if (disposed)
|
|
47
|
+
throw new Error("Cavelon adapter closed.");
|
|
48
|
+
try {
|
|
49
|
+
const result = await callUi(options.runtimeDir, context.sessionID, tool.name, args, context.abort, (options.waitMs ?? PERSON_WAIT_MS) + 15_000);
|
|
50
|
+
return { output: JSON.stringify(result), metadata: { isError: result.isError === true } };
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error instanceof NativeUiUnavailable) {
|
|
54
|
+
const result = await (await headless()).call(tool.name, args, { signal: context.abort });
|
|
55
|
+
return { output: JSON.stringify(result), metadata: { isError: result.isError === true } };
|
|
56
|
+
}
|
|
57
|
+
return { output: JSON.stringify({ error: {
|
|
58
|
+
code: "native_ui_disconnected", message: "The native UI call failed. Inspect the instance before repeating this change.",
|
|
59
|
+
outcome_unknown: true, automatic_retry: false,
|
|
60
|
+
} }), metadata: { isError: true } };
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
}])),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export default {
|
|
67
|
+
id: "cavelon.native-approval",
|
|
68
|
+
async server(input, options) {
|
|
69
|
+
const profile = options?.profile === undefined ? fileURLToPath(new URL("./profile.json", import.meta.url)) : options.profile;
|
|
70
|
+
if (typeof profile !== "string")
|
|
71
|
+
throw new Error("Cavelon native approval needs its setup profile.");
|
|
72
|
+
return startOpenCodeServer(input, await loadNativeRuntime(profile, "opencode"));
|
|
73
|
+
},
|
|
74
|
+
};
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { nativeStdioClient } from "./client.js";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { startUiSocket } from "./ipc.js";
|
|
4
|
+
import { assertNativeWorkspace, hasNativeProjectOwner, loadNativeRuntime } from "./profile.js";
|
|
5
|
+
import { previewPages } from "./preview-pages.js";
|
|
6
|
+
export async function startOpenCodeTui(api, options) {
|
|
7
|
+
await assertNativeWorkspace(options, api.state.path.directory);
|
|
8
|
+
if (await hasNativeProjectOwner(options, "opencode", api.state.path.directory))
|
|
9
|
+
return;
|
|
10
|
+
const clients = new Map();
|
|
11
|
+
const pending = new Set();
|
|
12
|
+
const retiring = new Set();
|
|
13
|
+
let disposed = false;
|
|
14
|
+
const session = () => api.route.current.name === "session" ? api.route.current.params?.sessionID : undefined;
|
|
15
|
+
const retire = (id, opening) => {
|
|
16
|
+
if (clients.get(id) !== opening)
|
|
17
|
+
return;
|
|
18
|
+
clients.delete(id);
|
|
19
|
+
const closing = opening.then(client => client.close()).catch(() => undefined);
|
|
20
|
+
retiring.add(closing);
|
|
21
|
+
void closing.finally(() => retiring.delete(closing));
|
|
22
|
+
};
|
|
23
|
+
const reap = setInterval(() => {
|
|
24
|
+
for (const [id, opening] of clients)
|
|
25
|
+
if (id !== session())
|
|
26
|
+
retire(id, opening);
|
|
27
|
+
}, 100);
|
|
28
|
+
reap.unref();
|
|
29
|
+
const connect = async (id) => {
|
|
30
|
+
if (disposed)
|
|
31
|
+
throw new Error("Cavelon adapter closed.");
|
|
32
|
+
const previous = clients.get(id);
|
|
33
|
+
if (previous && (await previous).closed && clients.get(id) === previous)
|
|
34
|
+
clients.delete(id);
|
|
35
|
+
if (!clients.has(id)) {
|
|
36
|
+
const opening = nativeStdioClient({ ...options.command, cwd: api.state.path.directory }, true, options.version);
|
|
37
|
+
clients.set(id, opening);
|
|
38
|
+
opening.catch(() => { if (clients.get(id) === opening)
|
|
39
|
+
clients.delete(id); });
|
|
40
|
+
}
|
|
41
|
+
return clients.get(id);
|
|
42
|
+
};
|
|
43
|
+
const ask = (message, signal) => new Promise(resolve => {
|
|
44
|
+
if (signal.aborted || api.ui.dialog.open || disposed) {
|
|
45
|
+
resolve(false);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
let pages;
|
|
49
|
+
try {
|
|
50
|
+
pages = previewPages(message, api.renderer.width, api.renderer.height);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
resolve(false);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let done = false;
|
|
57
|
+
let page = 0;
|
|
58
|
+
let replacing = false;
|
|
59
|
+
const finish = (answer, clear = true) => {
|
|
60
|
+
if (done)
|
|
61
|
+
return;
|
|
62
|
+
done = true;
|
|
63
|
+
signal.removeEventListener("abort", cancel);
|
|
64
|
+
if (clear)
|
|
65
|
+
api.ui.dialog.clear();
|
|
66
|
+
resolve(answer === true && !signal.aborted && !disposed);
|
|
67
|
+
};
|
|
68
|
+
const cancel = () => finish(false);
|
|
69
|
+
const closed = () => { if (!replacing)
|
|
70
|
+
finish(false, false); };
|
|
71
|
+
const show = () => {
|
|
72
|
+
if (signal.aborted) {
|
|
73
|
+
finish(false);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
replacing = true;
|
|
77
|
+
api.ui.dialog.replace(() => pages.length > 1 && page < pages.length
|
|
78
|
+
? api.ui.DialogAlert({ title: `Cavelon preview ${page + 1}/${pages.length}`, message: pages[page], onConfirm: () => {
|
|
79
|
+
replacing = true;
|
|
80
|
+
page++;
|
|
81
|
+
queueMicrotask(() => {
|
|
82
|
+
replacing = false;
|
|
83
|
+
if (done)
|
|
84
|
+
return;
|
|
85
|
+
if (api.ui.dialog.open)
|
|
86
|
+
finish(false, false);
|
|
87
|
+
else
|
|
88
|
+
show();
|
|
89
|
+
});
|
|
90
|
+
} })
|
|
91
|
+
: api.ui.DialogConfirm({
|
|
92
|
+
title: "Cavelon: approve this exact change",
|
|
93
|
+
message: pages.length === 1 ? message : `Approve the exact change shown in all ${pages.length} preview pages?`,
|
|
94
|
+
onConfirm: () => finish(true), onCancel: cancel,
|
|
95
|
+
}), closed);
|
|
96
|
+
api.ui.dialog.setSize("large");
|
|
97
|
+
replacing = false;
|
|
98
|
+
};
|
|
99
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
100
|
+
show();
|
|
101
|
+
});
|
|
102
|
+
const socket = await startUiSocket(options.runtimeDir, session, async (name, args, id, callerSignal) => {
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
pending.add(controller);
|
|
105
|
+
const abort = () => controller.abort();
|
|
106
|
+
callerSignal.addEventListener("abort", abort, { once: true });
|
|
107
|
+
const timer = setInterval(() => { if (session() !== id)
|
|
108
|
+
controller.abort(); }, 100);
|
|
109
|
+
try {
|
|
110
|
+
if (callerSignal.aborted || session() !== id || disposed)
|
|
111
|
+
throw new Error("Native UI session changed.");
|
|
112
|
+
const bridge = await connect(id);
|
|
113
|
+
return await bridge.call(name, args, { signal: controller.signal, ask });
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
clearInterval(timer);
|
|
117
|
+
pending.delete(controller);
|
|
118
|
+
callerSignal.removeEventListener("abort", abort);
|
|
119
|
+
}
|
|
120
|
+
}).catch(error => { clearInterval(reap); throw error; });
|
|
121
|
+
let closing;
|
|
122
|
+
const close = () => closing ??= (async () => {
|
|
123
|
+
disposed = true;
|
|
124
|
+
clearInterval(reap);
|
|
125
|
+
for (const controller of pending)
|
|
126
|
+
controller.abort();
|
|
127
|
+
await socket.close();
|
|
128
|
+
await Promise.all([...clients.values()].map(async (opening) => (await opening.catch(() => undefined))?.close()));
|
|
129
|
+
await Promise.all(retiring);
|
|
130
|
+
clients.clear();
|
|
131
|
+
})();
|
|
132
|
+
api.lifecycle.onDispose(close);
|
|
133
|
+
return { close, descriptor: socket.descriptor };
|
|
134
|
+
}
|
|
135
|
+
export default {
|
|
136
|
+
id: "cavelon.native-approval",
|
|
137
|
+
async tui(api, options) {
|
|
138
|
+
const profile = options?.profile === undefined ? fileURLToPath(new URL("./profile.json", import.meta.url)) : options.profile;
|
|
139
|
+
if (typeof profile !== "string")
|
|
140
|
+
throw new Error("Cavelon native approval needs its setup profile.");
|
|
141
|
+
await startOpenCodeTui(api, await loadNativeRuntime(profile, "opencode"));
|
|
142
|
+
},
|
|
143
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { nativeStdioClient } from "./client.js";
|
|
4
|
+
import { assertNativeWorkspace, hasNativeProjectOwner, loadNativeRuntime } from "./profile.js";
|
|
5
|
+
import { previewPages } from "./preview-pages.js";
|
|
6
|
+
export function installPiExtension(pi, options) {
|
|
7
|
+
let opening;
|
|
8
|
+
let current;
|
|
9
|
+
let generation = 0;
|
|
10
|
+
const owned = new Set();
|
|
11
|
+
const close = async () => {
|
|
12
|
+
generation++;
|
|
13
|
+
current = undefined;
|
|
14
|
+
const previous = opening;
|
|
15
|
+
opening = undefined;
|
|
16
|
+
await (await previous?.catch(() => undefined))?.close();
|
|
17
|
+
};
|
|
18
|
+
const start = async (ctx) => {
|
|
19
|
+
if (options.scope === "project" && !ctx.isProjectTrusted()) {
|
|
20
|
+
throw new Error("Cavelon project integration requires the person's trust for this project.");
|
|
21
|
+
}
|
|
22
|
+
await assertNativeWorkspace(options, ctx.cwd);
|
|
23
|
+
const previous = opening;
|
|
24
|
+
if (previous && (await previous).closed && opening === previous)
|
|
25
|
+
opening = undefined;
|
|
26
|
+
if (!opening) {
|
|
27
|
+
const connection = nativeStdioClient({ ...options.command, cwd: ctx.cwd }, ctx.hasUI && ctx.mode === "tui", options.version);
|
|
28
|
+
opening = connection;
|
|
29
|
+
connection.catch(() => { if (opening === connection)
|
|
30
|
+
opening = undefined; });
|
|
31
|
+
}
|
|
32
|
+
return opening;
|
|
33
|
+
};
|
|
34
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
35
|
+
await close();
|
|
36
|
+
if (ctx.isProjectTrusted() && await hasNativeProjectOwner(options, "pi", ctx.cwd))
|
|
37
|
+
return;
|
|
38
|
+
current = ctx;
|
|
39
|
+
const epoch = generation;
|
|
40
|
+
const client = await start(ctx);
|
|
41
|
+
const tools = await client.tools();
|
|
42
|
+
if (epoch !== generation)
|
|
43
|
+
return;
|
|
44
|
+
const existing = new Set(pi.getAllTools().map(tool => tool.name));
|
|
45
|
+
if (tools.some(tool => existing.has(`mcp__cavelon__${tool.name}`) && !owned.has(`mcp__cavelon__${tool.name}`))) {
|
|
46
|
+
await close();
|
|
47
|
+
throw new Error("Cavelon tools already exist. Disable only the duplicate Cavelon MCP entry or replacement extension before loading native approval.");
|
|
48
|
+
}
|
|
49
|
+
for (const tool of tools) {
|
|
50
|
+
const name = `mcp__cavelon__${tool.name}`;
|
|
51
|
+
owned.add(name);
|
|
52
|
+
pi.registerTool({
|
|
53
|
+
name, label: tool.annotations?.title ?? tool.name, description: tool.description ?? tool.name,
|
|
54
|
+
parameters: Type.Unsafe(tool.inputSchema), annotations: tool.annotations, executionMode: "sequential",
|
|
55
|
+
async execute(_id, params, signal, _update, ctx) {
|
|
56
|
+
if (!current)
|
|
57
|
+
throw new Error("The Cavelon native session has ended.");
|
|
58
|
+
const callGeneration = generation;
|
|
59
|
+
const result = await (await start(ctx)).call(tool.name, params, {
|
|
60
|
+
signal,
|
|
61
|
+
ask: ctx.hasUI && ctx.mode === "tui" ? async (message, dialogSignal, timeout) => {
|
|
62
|
+
const pages = previewPages(message, process.stdout.columns || 80, process.stdout.rows || 24);
|
|
63
|
+
if (pages.length > 1)
|
|
64
|
+
for (let page = 0; page < pages.length; page++) {
|
|
65
|
+
if (dialogSignal.aborted || callGeneration !== generation)
|
|
66
|
+
return false;
|
|
67
|
+
if (await ctx.ui.confirm(`Cavelon preview ${page + 1}/${pages.length}: continue`, pages[page], { signal: dialogSignal, timeout }) !== true)
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (dialogSignal.aborted || callGeneration !== generation)
|
|
71
|
+
return false;
|
|
72
|
+
return ctx.ui.confirm("Cavelon: approve this exact change", pages.length === 1 ? message : `Approve the exact change shown in all ${pages.length} preview pages?`, { signal: dialogSignal, timeout });
|
|
73
|
+
} : undefined,
|
|
74
|
+
});
|
|
75
|
+
return { content: result.content, details: { isError: result.isError === true } };
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
pi.on("session_shutdown", close);
|
|
81
|
+
}
|
|
82
|
+
export default async function cavelon(pi) {
|
|
83
|
+
installPiExtension(pi, await loadNativeRuntime(fileURLToPath(new URL("./profile.json", import.meta.url)), "pi"));
|
|
84
|
+
}
|