@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,223 @@
1
+ import { applyEdits, createScanner, findNodeAtLocation, modify, parseTree } from "jsonc-parser";
2
+ function document(text) {
3
+ const errors = [];
4
+ const root = parseTree(text, errors, { allowTrailingComma: true });
5
+ if (errors.length || !root)
6
+ return { error: "it has a JSONC syntax error" };
7
+ if (root.type !== "object")
8
+ return { error: "it is not a JSON object" };
9
+ const duplicate = (node) => {
10
+ if (node.type === "object") {
11
+ const names = node.children?.map(property => property.children[0].value) ?? [];
12
+ if (new Set(names).size !== names.length)
13
+ return true;
14
+ }
15
+ return node.children?.some(duplicate) ?? false;
16
+ };
17
+ if (duplicate(root))
18
+ return { error: "it has duplicate keys, so its effective configuration is ambiguous" };
19
+ return { root };
20
+ }
21
+ function valueOf(node) {
22
+ if (!node)
23
+ return undefined;
24
+ if (node.type === "object")
25
+ return Object.fromEntries((node.children ?? []).map(property => [property.children[0].value, valueOf(property.children[1])]));
26
+ if (node.type === "array")
27
+ return (node.children ?? []).map(valueOf);
28
+ return node.value;
29
+ }
30
+ function comments(text) {
31
+ const scanner = createScanner(text);
32
+ const found = [];
33
+ for (let token = scanner.scan(); token !== 17; token = scanner.scan()) {
34
+ if (token === 12 || token === 13) {
35
+ found.push(text.slice(scanner.getTokenOffset(), scanner.getTokenOffset() + scanner.getTokenLength()));
36
+ }
37
+ }
38
+ return found;
39
+ }
40
+ function same(left, right) {
41
+ if (left === right)
42
+ return true;
43
+ if (!left || !right || typeof left !== "object" || typeof right !== "object")
44
+ return false;
45
+ if (Array.isArray(left) || Array.isArray(right))
46
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => same(item, right[index]));
47
+ const keys = Object.keys(left);
48
+ return keys.length === Object.keys(right).length && keys.every(key => Object.hasOwn(right, key) && same(left[key], right[key]));
49
+ }
50
+ function validPath(keys) {
51
+ return keys.length > 0 && keys.every(key => key.length > 0 && !["__proto__", "constructor", "prototype"].includes(key));
52
+ }
53
+ export function readJsoncEntry(text, keys) {
54
+ if (!validPath(keys))
55
+ return { error: "the configuration entry path is invalid" };
56
+ if (text === undefined)
57
+ return { value: undefined, kept: 0 };
58
+ const parsed = document(text);
59
+ if ("error" in parsed)
60
+ return parsed;
61
+ let kept = 0;
62
+ for (let depth = 1; depth <= keys.length; depth++) {
63
+ const node = findNodeAtLocation(parsed.root, keys.slice(0, depth));
64
+ if (!node)
65
+ break;
66
+ if (depth < keys.length && node.type !== "object")
67
+ return { error: `its "${keys.slice(0, depth).join(".")}" is not an object` };
68
+ kept = depth;
69
+ }
70
+ return { value: valueOf(findNodeAtLocation(parsed.root, keys)), kept };
71
+ }
72
+ function removalEdits(text, root, keys) {
73
+ const parent = findNodeAtLocation(root, keys.slice(0, -1));
74
+ const children = parent?.children ?? [];
75
+ const index = children.findIndex(property => property.children?.[0]?.value === keys.at(-1));
76
+ if (index < 0)
77
+ return [];
78
+ return itemRemovalEdits(text, children, index);
79
+ }
80
+ function itemRemovalEdits(text, children, index) {
81
+ const item = children[index];
82
+ const edits = [{ offset: item.offset, length: item.length, content: "" }];
83
+ const scanner = createScanner(text, true);
84
+ scanner.setPosition(item.offset + item.length);
85
+ if (scanner.scan() === 5)
86
+ edits.push({ offset: scanner.getTokenOffset(), length: 1, content: "" });
87
+ else if (index > 0) {
88
+ const previous = children[index - 1];
89
+ scanner.setPosition(previous.offset + previous.length);
90
+ if (scanner.scan() !== 5)
91
+ throw new Error("Missing property separator.");
92
+ edits.push({ offset: scanner.getTokenOffset(), length: 1, content: "" });
93
+ }
94
+ return edits;
95
+ }
96
+ function checkedEdits(text, edits) {
97
+ const content = applyEdits(text, edits);
98
+ const parsed = document(content);
99
+ if ("error" in parsed)
100
+ return { outcome: "skipped", reason: parsed.error };
101
+ if (!same(comments(text), comments(content)))
102
+ return { outcome: "skipped", reason: "changing this entry would remove a personal comment; edit it manually" };
103
+ return content === text ? { outcome: "unchanged" } : { outcome: "updated", content };
104
+ }
105
+ function edit(text, keys, value) {
106
+ try {
107
+ const before = document(text);
108
+ if ("error" in before)
109
+ return { outcome: "skipped", reason: before.error };
110
+ return checkedEdits(text, value === undefined ? removalEdits(text, before.root, keys) : modify(text, keys, value, {}));
111
+ }
112
+ catch {
113
+ return { outcome: "skipped", reason: "this configuration cannot be edited safely" };
114
+ }
115
+ }
116
+ export function upsertJsoncEntry(existing, keys, value, options = {}) {
117
+ if (!validPath(keys))
118
+ return { outcome: "skipped", reason: "the configuration entry path is invalid" };
119
+ if (existing === undefined) {
120
+ if (options.onlyExisting)
121
+ return { outcome: "skipped", reason: "the file does not exist" };
122
+ let root = value;
123
+ for (const key of [...keys].reverse())
124
+ root = { [key]: root };
125
+ return { outcome: "created", content: JSON.stringify(root, null, 2) + "\n" };
126
+ }
127
+ const current = readJsoncEntry(existing, keys);
128
+ if ("error" in current)
129
+ return { outcome: "skipped", reason: current.error };
130
+ if (same(current.value, value))
131
+ return { outcome: "unchanged" };
132
+ if (current.value === undefined && options.onlyExisting)
133
+ return { outcome: "skipped", reason: "it has no Cavelon entry" };
134
+ if (current.value !== undefined && !options.matches?.(current.value))
135
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" is a personal or conflicting entry` };
136
+ const result = edit(existing, keys, value);
137
+ return result.outcome === "updated" && current.value === undefined ? { ...result, outcome: "appended" } : result;
138
+ }
139
+ export function removeJsoncEntry(existing, keys, matches, keep = 0) {
140
+ if (existing === undefined)
141
+ return { outcome: "unchanged" };
142
+ const current = readJsoncEntry(existing, keys);
143
+ if ("error" in current)
144
+ return { outcome: "skipped", reason: current.error };
145
+ if (current.value === undefined)
146
+ return { outcome: "unchanged" };
147
+ if (!matches(current.value))
148
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" was changed since cavelon wrote it` };
149
+ const removed = edit(existing, keys, undefined);
150
+ if (removed.outcome !== "updated")
151
+ return removed;
152
+ let content = removed.content;
153
+ for (let depth = keys.length - 1; depth > keep; depth--) {
154
+ const parsed = document(content);
155
+ if ("error" in parsed)
156
+ break;
157
+ const parent = findNodeAtLocation(parsed.root, keys.slice(0, depth));
158
+ if (!parent || parent.type !== "object" || parent.children?.length || comments(content.slice(parent.offset, parent.offset + parent.length)).length)
159
+ break;
160
+ const trimmed = edit(content, keys.slice(0, depth), undefined);
161
+ if (trimmed.outcome !== "updated")
162
+ break;
163
+ content = trimmed.content;
164
+ }
165
+ const parsed = document(content);
166
+ const empty = "root" in parsed && !parsed.root.children?.length && comments(content).length === 0;
167
+ return { outcome: "updated", content, empty };
168
+ }
169
+ export function appendJsoncMember(existing, keys, member) {
170
+ const current = readJsoncEntry(existing, keys);
171
+ if ("error" in current)
172
+ return { outcome: "skipped", reason: current.error };
173
+ if (current.value === undefined)
174
+ return upsertJsoncEntry(existing, keys, [member]);
175
+ if (!Array.isArray(current.value))
176
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" is not an array` };
177
+ const count = current.value.filter(item => same(item, member)).length;
178
+ if (count > 1)
179
+ return { outcome: "skipped", reason: "the Cavelon member occurs more than once; resolve duplicate entries manually" };
180
+ if (count === 1)
181
+ return { outcome: "unchanged" };
182
+ try {
183
+ const result = checkedEdits(existing, modify(existing, [...keys, current.value.length], member, { isArrayInsertion: true }));
184
+ return result.outcome === "updated" ? { ...result, outcome: "appended" } : result;
185
+ }
186
+ catch {
187
+ return { outcome: "skipped", reason: "this configuration cannot be edited safely" };
188
+ }
189
+ }
190
+ export function removeJsoncMember(existing, keys, member, options = {}) {
191
+ const current = readJsoncEntry(existing, keys);
192
+ if ("error" in current)
193
+ return { outcome: "skipped", reason: current.error };
194
+ if (current.value === undefined)
195
+ return { outcome: "unchanged" };
196
+ if (!Array.isArray(current.value))
197
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" is not an array` };
198
+ const indices = current.value.flatMap((item, index) => same(item, member) ? [index] : []);
199
+ if (!indices.length)
200
+ return { outcome: "unchanged" };
201
+ if (indices.length > 1)
202
+ return { outcome: "skipped", reason: "the Cavelon member occurs more than once; resolve duplicate entries manually" };
203
+ try {
204
+ const before = document(existing);
205
+ if ("error" in before)
206
+ return { outcome: "skipped", reason: before.error };
207
+ const node = findNodeAtLocation(before.root, keys);
208
+ const result = checkedEdits(existing, itemRemovalEdits(existing, node.children, indices[0]));
209
+ if (result.outcome !== "updated")
210
+ return result;
211
+ const parsed = document(result.content);
212
+ if ("error" in parsed)
213
+ return { outcome: "skipped", reason: parsed.error };
214
+ const remaining = findNodeAtLocation(parsed.root, keys);
215
+ if (options.removeEmpty && !remaining.children?.length && !comments(result.content.slice(remaining.offset, remaining.offset + remaining.length)).length) {
216
+ return removeJsoncEntry(result.content, keys, value => Array.isArray(value) && !value.length, keys.length - 1);
217
+ }
218
+ return { ...result, empty: !parsed.root.children?.length && comments(result.content).length === 0 };
219
+ }
220
+ catch {
221
+ return { outcome: "skipped", reason: "this configuration cannot be edited safely" };
222
+ }
223
+ }
package/dist/kit-codes.js CHANGED
@@ -65,6 +65,7 @@ export const KIT_ERROR_CODES = [
65
65
  { code: "preview_expired", area: "cli", message: "The preview is older than the kit keeps previews; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
66
66
  { code: "confirm_token_required", area: "cli", message: "Over MCP, or run by a coding agent in its shell, a changing command confirms only with the token its preview returned, never with true or a bare --confirm.", hint: "Call the tool (or run the command) without confirm, show the person the preview, then call it again with the same arguments and confirm set to its confirm_token (--confirm <token> in a shell)." },
67
67
  { code: "confirm_needs_person", area: "cli", message: "A coding agent cannot confirm this change, even with its preview's token: it reaches live traffic or the whole tenant, or cannot be taken back, and the agent's MCP client cannot ask the person (or the agent runs cavelon in its shell). Nothing was changed.", hint: "Show the person the preview; they run the command the refusal names in their own terminal, outside the agent." },
68
+ { code: "native_ui_disconnected", area: "cli", message: "The native person UI call failed after routing. Its outcome may be unknown, so the adapter never retries through another connection.", hint: "Inspect the instance's current state before repeating the change. Reconnect the client; a new guarded attempt needs a fresh preview and person answer." },
68
69
  { code: "confirm_declined", area: "cli", message: "The MCP client asked the person to approve the change, and they declined or did not answer in time. Nothing was changed.", hint: "Ask the person whether they want the change; with their yes, confirm again with the same token, or they run the command in their own terminal." },
69
70
  { code: "token_mismatch", area: "cli", message: "The confirm token is not the one for this change: it belongs to another preview, or the change differs from what its preview showed; nothing was changed (exit code 4).", hint: "Show the person the new preview this answer carries, and confirm only with its confirm_token after their yes; a token confirms exactly the change its preview showed." },
70
71
  { code: "unknown_argument", area: "cli", message: "An MCP tool was called with an argument its schema does not list; nothing was done.", hint: "Call it again with the argument the error names (the tool's schema lists them all), spelled in snake_case." },
@@ -0,0 +1,5 @@
1
+ export const MCP_COMMAND = { command: "npx", args: ["-y", "@cavelon/cli@0.1", "mcp"] };
2
+ export const INSTALLED_MCP_COMMAND = { command: "cavelon", args: ["mcp"] };
3
+ export function mcpCommand(platform = process.platform) {
4
+ return platform === "win32" ? { command: "cmd", args: ["/c", MCP_COMMAND.command, ...MCP_COMMAND.args] } : MCP_COMMAND;
5
+ }
@@ -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, [format === "goose-stdio" ? "cmd" : "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[format === "goose-stdio" ? "cmd" : "command"], ...(Array.isArray(entry.args) ? entry.args : [])];
11
+ if (format !== "command-array" && !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";
@@ -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
- 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");
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
+ }