@cavelon/cli 0.1.14 → 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 (41) 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/change-confirmation.js +3 -2
  6. package/dist/commands/api.js +5 -4
  7. package/dist/commands/init.js +46 -10
  8. package/dist/commands/session.js +3 -0
  9. package/dist/commands/setup.js +17 -4
  10. package/dist/confirm-token.js +2 -1
  11. package/dist/fsutil.js +24 -7
  12. package/dist/jsonc-config.js +223 -0
  13. package/dist/kit-codes.js +1 -0
  14. package/dist/mcp-command.js +5 -0
  15. package/dist/mcp-directory.js +32 -0
  16. package/dist/mcp-entry.js +21 -0
  17. package/dist/mcp.js +25 -7
  18. package/dist/native-approval/client.js +126 -0
  19. package/dist/native-approval/ipc.js +191 -0
  20. package/dist/native-approval/opencode-server.js +74 -0
  21. package/dist/native-approval/opencode-tui.js +143 -0
  22. package/dist/native-approval/pi-extension.js +84 -0
  23. package/dist/native-approval/preview-pages.js +18 -0
  24. package/dist/native-approval/profile.js +113 -0
  25. package/dist/native-assets/JSONC-LICENSE +21 -0
  26. package/dist/native-assets/LICENSE +201 -0
  27. package/dist/native-assets/MCP-SDK-LICENSE +21 -0
  28. package/dist/native-assets/THIRD-PARTY-NOTICES +368 -0
  29. package/dist/native-assets/TYPEBOX-LICENSE +23 -0
  30. package/dist/native-assets/ZOD-LICENSE +21 -0
  31. package/dist/native-assets/manifest.json +60 -0
  32. package/dist/native-assets/opencode-server.mjs +32273 -0
  33. package/dist/native-assets/opencode-tui.mjs +19055 -0
  34. package/dist/native-assets/pi-extension.mjs +23302 -0
  35. package/dist/native-assets.js +44 -0
  36. package/dist/native-clients.js +181 -0
  37. package/dist/native-install.js +365 -0
  38. package/dist/printed.js +17 -5
  39. package/dist/setup-agents.js +73 -8
  40. package/dist/skills/cavelon-loop/SKILL.md +22 -5
  41. package/package.json +7 -3
@@ -0,0 +1,32 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { CavelonError, ExitCode, usageError } from "./errors.js";
4
+ import { cacheDir, configDir, realPath, within } from "./paths.js";
5
+ export async function solutionDirectory(io, selection) {
6
+ if (selection === undefined)
7
+ return { io };
8
+ if (typeof selection !== "string" || !selection.trim() || selection.includes("\0")) {
9
+ throw usageError("solution_dir must be a nonempty solution folder path.");
10
+ }
11
+ const root = await realPath(io.cwd);
12
+ const directory = await realPath(path.resolve(io.cwd, selection));
13
+ if (!within(root, directory)) {
14
+ throw new CavelonError(ExitCode.usage, {
15
+ code: "path_outside_solution",
16
+ message: `The solution folder ${selection} is outside the MCP workspace ${io.cwd}; nothing was done.`,
17
+ hint: "Select a folder inside the workspace, or start a separate MCP session in that repository.",
18
+ });
19
+ }
20
+ for (const privateDir of [configDir(io.env), cacheDir(io.env)]) {
21
+ if (within(await realPath(path.resolve(io.cwd, privateDir)), directory, true)) {
22
+ throw new CavelonError(ExitCode.usage, {
23
+ code: "path_in_kit_directory",
24
+ message: "solution_dir cannot select cavelon's credential or cache directory; nothing was done.",
25
+ });
26
+ }
27
+ }
28
+ const stat = await fs.stat(directory).catch(() => undefined);
29
+ if (!stat?.isDirectory())
30
+ throw usageError(`The solution folder ${selection} is not an existing directory; nothing was done.`);
31
+ return { io: { ...io, cwd: directory }, selected: selection, directory };
32
+ }
@@ -0,0 +1,21 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { INSTALLED_MCP_COMMAND, mcpCommand } from "./mcp-command.js";
3
+ export function encodeMcpEntry(command, format, extra = {}) {
4
+ return format === "command-array" ? { ...extra, command: [command.command, ...command.args] } : { ...extra, command: command.command, args: command.args };
5
+ }
6
+ export function decodeMcpEntry(value, format) {
7
+ if (!value || typeof value !== "object" || Array.isArray(value))
8
+ return undefined;
9
+ const entry = value;
10
+ const words = format === "command-array" ? entry.command : [entry.command, ...(Array.isArray(entry.args) ? entry.args : [])];
11
+ if (format === "command-args" && !Array.isArray(entry.args))
12
+ return undefined;
13
+ if (!Array.isArray(words) || !words.length || !words.every(word => typeof word === "string") || !words[0])
14
+ return undefined;
15
+ return { command: words[0], args: words.slice(1) };
16
+ }
17
+ export function isKitMcpEntry(value, format, extra = {}) {
18
+ if (!value || typeof value !== "object" || Array.isArray(value))
19
+ return false;
20
+ return [INSTALLED_MCP_COMMAND, mcpCommand("linux"), mcpCommand("win32")].some(command => isDeepStrictEqual(encodeMcpEntry(command, format, extra), value));
21
+ }
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";
@@ -15,7 +16,7 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
15
16
  "loop_start, sandbox_seed, artifacts_export) return operation ids at once; read them with operation_status, which returns " +
16
17
  `the state at once, or waits up to its timeout (at most ${MCP_MAX_WAIT_MS / 1000} s) when given one, and reports waited_ms, ` +
17
18
  "and follow a loop with loop_iterations. What needs confirmation: apply imports only with confirm set to a preview's id; " +
18
- "tenant_create, variables_set where it replaces another value, loop_start, limits_set, models_set_limit, loop_cancel, sandbox_seed, " +
19
+ "tenant_create, variables_set where it replaces another value, variables_delete, loop_start, limits_set, models_set_limit, loop_cancel, sandbox_seed, " +
19
20
  "trigger_identity, harness_default, activate of a solution a channel or trigger reaches or with make_default, deactivate, " +
20
21
  "and api for an operation that is not read-only, " +
21
22
  "return what they would do and a confirm_token, and change nothing until called again with the same arguments and " +
@@ -24,14 +25,16 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
24
25
  "or that cannot be taken back, is the person's to confirm, and the token alone does not make it: its preview says " +
25
26
  "needs_person. With needs_person \"client\", call again with the token and the client asks the person to approve exactly that " +
26
27
  "change; their no, or no answer, changes nothing (confirm_declined). Only after their yes does cavelon ask the instance for " +
27
- "the confirmation it checks itself; confirmation_required or confirmation_invalid changed nothing: preview again, never retry " +
28
+ "confirmation bound to the token, tenant and exact request. The instance does not verify the person's answer: asking them " +
29
+ "is the kit's responsibility alone. Ask before every guarded change; never answer on the person's behalf or reuse an earlier yes for another change. " +
30
+ "confirmation_required or confirmation_invalid changed nothing: preview again, never retry " +
28
31
  "on your own. With needs_person \"terminal\" this client cannot ask " +
29
32
  "them: give the person the preview's confirm command, which they run in their own terminal, never in yours. These are " +
30
33
  "harness_default and activate (the default route and a solution something reaches: live traffic), deactivate, tenant_create, " +
31
- "variables_set replacing a value (every solution of the tenant reads it), limits_set, models_set_limit, trigger_identity, " +
34
+ "variables_set replacing a value (every solution of the tenant reads it), variables_delete, limits_set, models_set_limit, trigger_identity, " +
32
35
  "api for an operation that is not read-only, loop_start unless the trigger's solution is a draft (a run acts as the person " +
33
36
  "and spends budget), and apply where its preview says show_to_person (tenant-wide sections, an active solution, deletions, " +
34
- "env/prod). A draft's apply, a draft's loop_start, loop_cancel, sandbox_seed and kb_upload's replace you confirm with the " +
37
+ "env/prod, or database_queries.would_write). A draft's apply with no query writes or other person requirement, a draft's loop_start, loop_cancel, sandbox_seed and kb_upload's replace you confirm with the " +
35
38
  "token once the person saw the preview. " +
36
39
  "chat sends one message to a solution and returns its answer: the way to try one that is not the default route. " +
37
40
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
@@ -48,6 +51,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
48
51
  "Run from your shell, cavelon's api command applies the same guards, and sends a changing operation only with --confirm and the token " +
49
52
  "its preview printed. Tools read and write files only " +
50
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 " +
51
57
  "config or cache directory. Read limits before planning a solution: it lists what the " +
52
58
  "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
53
59
  "Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
@@ -55,7 +61,7 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
55
61
  "db_connections, db_queries and db_runs read database connections, saved queries and their runs. Connection commands " +
56
62
  "and query-writing apply follow the permissions and needs_a_person the instance publishes: use whoami, including " +
57
63
  "database_connectors.manage, instead of assuming every token is blocked. An authorized personal access token may " +
58
- "manage definitions. Query changes need the person's approval even on a draft; after approval cavelon sends the " +
64
+ "manage definitions. Creating, changing or deleting a query, including imports that create or change one, needs the person's approval even on a draft; after approval cavelon sends the " +
59
65
  "instance's confirmation for the exact change where required. Passwords, privilege acknowledgment and enabling writes " +
60
66
  "stay with a person in the Admin; never accept or pass the database password or set allows_writes through a tool. " +
61
67
  "variables_list/variables_get/variables_set handle plain-text {{var:…}} values; setting one needs a role that may manage " +
@@ -120,6 +126,11 @@ export function inputSchema(spec, commands = []) {
120
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.",
121
127
  };
122
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
+ };
123
134
  return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
124
135
  }
125
136
  export function notForThisCredential(spec, access) {
@@ -284,14 +295,21 @@ export function createMcpServer(io, commands, updates = {}) {
284
295
  }
285
296
  const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
286
297
  const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
287
- const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv, sessionTenants }, "mcp");
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");
288
306
  if (clientAsks(server))
289
307
  ctx.askPerson = (message) => askThroughClient(server, message, requestId);
290
308
  for (const message of renamed)
291
309
  ctx.warn(message);
292
310
  try {
293
311
  const chosen = tenant ?? (await ctx.session().then((s) => (s.tenantSource === "session" ? s.tenant : undefined), () => undefined));
294
- 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 () => {
295
313
  try {
296
314
  const done = await spec.run(ctx, inputFrom(spec, args));
297
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
+ };