@cavelon/cli 0.0.0 → 0.1.1
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 +697 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +91 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +243 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +452 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +624 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +792 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +667 -0
- package/dist/commands/session.js +476 -0
- package/dist/commands/solution.js +760 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +383 -0
- package/dist/commands/work.js +744 -0
- package/dist/context.js +56 -0
- package/dist/contracts.js +189 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +37 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +40 -0
- package/dist/git.js +41 -0
- package/dist/http.js +286 -0
- package/dist/invoke.js +161 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +299 -0
- package/dist/local-state.js +60 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +130 -0
- package/dist/openapi.js +223 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +329 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +28 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +138 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +66 -0
- package/dist/session.js +166 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +214 -0
- package/dist/skills/cavelon-long-running/SKILL.md +181 -0
- package/dist/skills/cavelon-loop/SKILL.md +158 -0
- package/dist/skills/cavelon-testing/SKILL.md +90 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { table } from "../format.js";
|
|
2
|
+
import { api, apiDescribe, apiList } from "./api.js";
|
|
3
|
+
import { wait, watch } from "./async.js";
|
|
4
|
+
import { docsGet, docsSearch } from "./docs.js";
|
|
5
|
+
import { login, logout, status, use, whoami } from "./session.js";
|
|
6
|
+
import { init } from "./init.js";
|
|
7
|
+
import { limits } from "./limits.js";
|
|
8
|
+
import { limitsSet } from "./limits-set.js";
|
|
9
|
+
import { modelsList, modelsSetLimit } from "./models.js";
|
|
10
|
+
import { activate, apply, explain, pull, validate } from "./solution.js";
|
|
11
|
+
import { harnessClone, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
|
|
12
|
+
import { kbUpload, testRun, trace } from "./work.js";
|
|
13
|
+
import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
|
|
14
|
+
import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
|
|
15
|
+
import { artifactsExport, sandboxActivity, sandboxCat, sandboxFiles, sandboxList, sandboxLogs, sandboxReceipt, sandboxRefresh, sandboxSeed, sandboxValidate, } from "./sandboxes.js";
|
|
16
|
+
const commandsList = {
|
|
17
|
+
name: "commands",
|
|
18
|
+
summary: "List every command, whether it is read-only, and its MCP tool.",
|
|
19
|
+
readOnly: true,
|
|
20
|
+
idempotent: true,
|
|
21
|
+
mcpTool: false,
|
|
22
|
+
async run() {
|
|
23
|
+
const items = COMMANDS.map((c) => ({
|
|
24
|
+
command: c.name,
|
|
25
|
+
read_only: c.readOnly,
|
|
26
|
+
destructive: Boolean(c.destructive),
|
|
27
|
+
mcp_tool: c.mcpTool || null,
|
|
28
|
+
summary: c.summary,
|
|
29
|
+
}));
|
|
30
|
+
return { data: { items }, text: table(items, ["command", "read_only", "mcp_tool", "summary"], 70) };
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
const mcp = {
|
|
34
|
+
name: "mcp",
|
|
35
|
+
summary: "Serve the commands as MCP tools on stdio (for coding agents).",
|
|
36
|
+
description: "Started by the agent's plugin (`cavelon mcp`); it does not return until the agent disconnects.",
|
|
37
|
+
readOnly: false,
|
|
38
|
+
mcpTool: false,
|
|
39
|
+
async run(ctx) {
|
|
40
|
+
const { createMcpServer } = await import("../mcp.js");
|
|
41
|
+
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
|
42
|
+
const server = createMcpServer(ctx.io, COMMANDS);
|
|
43
|
+
const transport = new StdioServerTransport();
|
|
44
|
+
const closed = new Promise((resolve) => {
|
|
45
|
+
server.onclose = () => resolve();
|
|
46
|
+
ctx.io.stdin.on?.("end", () => resolve());
|
|
47
|
+
ctx.io.stdin.on?.("close", () => resolve());
|
|
48
|
+
});
|
|
49
|
+
await server.connect(transport);
|
|
50
|
+
await closed;
|
|
51
|
+
await server.close().catch(() => undefined);
|
|
52
|
+
return { data: undefined, text: "" };
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
export const COMMANDS = [
|
|
56
|
+
login,
|
|
57
|
+
logout,
|
|
58
|
+
whoami,
|
|
59
|
+
use,
|
|
60
|
+
status,
|
|
61
|
+
limits,
|
|
62
|
+
limitsSet,
|
|
63
|
+
modelsList,
|
|
64
|
+
modelsSetLimit,
|
|
65
|
+
tenantCreate,
|
|
66
|
+
tenantList,
|
|
67
|
+
harnessList,
|
|
68
|
+
harnessNew,
|
|
69
|
+
harnessClone,
|
|
70
|
+
activate,
|
|
71
|
+
init,
|
|
72
|
+
pull,
|
|
73
|
+
validate,
|
|
74
|
+
apply,
|
|
75
|
+
explain,
|
|
76
|
+
variablesList,
|
|
77
|
+
variablesGet,
|
|
78
|
+
variablesSet,
|
|
79
|
+
variablesDelete,
|
|
80
|
+
secretsList,
|
|
81
|
+
secretsSet,
|
|
82
|
+
secretsDelete,
|
|
83
|
+
apiList,
|
|
84
|
+
apiDescribe,
|
|
85
|
+
api,
|
|
86
|
+
docsSearch,
|
|
87
|
+
docsGet,
|
|
88
|
+
wait,
|
|
89
|
+
watch,
|
|
90
|
+
kbUpload,
|
|
91
|
+
testRun,
|
|
92
|
+
trace,
|
|
93
|
+
loopStart,
|
|
94
|
+
loopCancel,
|
|
95
|
+
loopWatch,
|
|
96
|
+
loopIterations,
|
|
97
|
+
loopPause,
|
|
98
|
+
loopResume,
|
|
99
|
+
triggerIdentity,
|
|
100
|
+
sandboxList,
|
|
101
|
+
sandboxValidate,
|
|
102
|
+
sandboxFiles,
|
|
103
|
+
sandboxCat,
|
|
104
|
+
sandboxActivity,
|
|
105
|
+
sandboxLogs,
|
|
106
|
+
sandboxReceipt,
|
|
107
|
+
sandboxSeed,
|
|
108
|
+
sandboxRefresh,
|
|
109
|
+
artifactsExport,
|
|
110
|
+
commandsList,
|
|
111
|
+
mcp,
|
|
112
|
+
];
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseDocument } from "yaml";
|
|
4
|
+
import { boolOption, listOption, stringOption } from "../command.js";
|
|
5
|
+
import { AGENTS, bundledSkills, generatedCopy, parseAgents, SKILL_ROOTS } from "../agents.js";
|
|
6
|
+
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
7
|
+
import { readTextFile, writeFileAtomic } from "../fsutil.js";
|
|
8
|
+
import { git } from "../git.js";
|
|
9
|
+
import { ensureStateDir, STATE_DIR } from "../local-state.js";
|
|
10
|
+
import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
|
|
11
|
+
import { packageVersionOf } from "../package-check.js";
|
|
12
|
+
import { defaultLayoutFor, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
|
|
13
|
+
import { readPrincipal } from "../principal.js";
|
|
14
|
+
import { ENV_DIR, parseProject, PROJECT_FILE } from "../project.js";
|
|
15
|
+
import { requireInstance, requireToken } from "../session.js";
|
|
16
|
+
import { schemaFor, setProjectKey } from "./solution.js";
|
|
17
|
+
const HOOK_LINES = (prefix) => [
|
|
18
|
+
"# Check the Cavelon package before each commit (`cavelon init --hook`).",
|
|
19
|
+
'cavelon_cmd="npx -y @cavelon/cli"; command -v cavelon >/dev/null 2>&1 && cavelon_cmd=cavelon',
|
|
20
|
+
`if ( cd "./${prefix}" && $cavelon_cmd validate ); then cavelon_code=0; else cavelon_code=$?; fi`,
|
|
21
|
+
'if [ "$cavelon_code" -eq 3 ]; then exit 1; fi',
|
|
22
|
+
'if [ "$cavelon_code" -ne 0 ]; then echo "warning: cavelon validate could not run (exit $cavelon_code); the package was not checked." >&2; fi',
|
|
23
|
+
];
|
|
24
|
+
export const AGENTS_BLOCK = [
|
|
25
|
+
"## Cavelon solution",
|
|
26
|
+
"",
|
|
27
|
+
"This folder is a Cavelon solution (`cavelon.yaml`): edit `package/`, `tests/` and `env/`, then run `cavelon validate` and `cavelon apply`.",
|
|
28
|
+
"Use the Cavelon skills (cavelon-loop, cavelon-authoring, cavelon-testing, cavelon-long-running); without them, `cavelon --help` and `cavelon docs search <query>` lead on.",
|
|
29
|
+
"`cavelon apply` only previews; show a preview that reaches an active solution or `env/prod` to a person before `cavelon apply --confirm <id>`.",
|
|
30
|
+
"`cavelon status` shows the instance, tenant and open previews, and `.cavelon/inventory.md` the tenant's solutions, knowledge bases and tools. A person runs `cavelon login`; never handle a token.",
|
|
31
|
+
].join("\n");
|
|
32
|
+
const GITIGNORE_BLOCK = ["# Local cavelon state (inventory, previews); never committed.", `${STATE_DIR}/`].join("\n");
|
|
33
|
+
function rel(root, file) {
|
|
34
|
+
return path.relative(root, file).split(path.sep).join("/");
|
|
35
|
+
}
|
|
36
|
+
async function realFile(file) {
|
|
37
|
+
try {
|
|
38
|
+
return await fs.realpath(file);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return file;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function applyBlock(root, file, result, mode) {
|
|
45
|
+
if (result.content !== undefined && result.outcome !== "unchanged" && result.outcome !== "skipped") {
|
|
46
|
+
const target = await realFile(file);
|
|
47
|
+
const current = await fs.stat(target).then((st) => st.mode & 0o777, () => undefined);
|
|
48
|
+
await writeFileAtomic(target, result.content, current ?? mode);
|
|
49
|
+
}
|
|
50
|
+
return { file: rel(root, file), action: result.outcome, ...(result.reason ? { reason: result.reason } : {}) };
|
|
51
|
+
}
|
|
52
|
+
async function block(root, relative, body, style, options = {}) {
|
|
53
|
+
const file = path.join(root, relative);
|
|
54
|
+
return applyBlock(root, file, upsertBlock(await readTextFile(file), body, style, options));
|
|
55
|
+
}
|
|
56
|
+
async function claudeImport(root, onlyExisting) {
|
|
57
|
+
const claude = path.join(root, "CLAUDE.md");
|
|
58
|
+
if ((await readTextFile(claude)) === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
if ((await realFile(claude)) === (await realFile(path.join(root, "AGENTS.md")))) {
|
|
61
|
+
return { file: "CLAUDE.md", action: "unchanged", reason: "it is AGENTS.md" };
|
|
62
|
+
}
|
|
63
|
+
return block(root, "CLAUDE.md", "@AGENTS.md", "html", { onlyExisting });
|
|
64
|
+
}
|
|
65
|
+
async function ownFile(root, relative, content) {
|
|
66
|
+
const file = path.join(root, relative);
|
|
67
|
+
if ((await readTextFile(file)) !== undefined)
|
|
68
|
+
return { file: relative, action: "unchanged" };
|
|
69
|
+
await writeFileAtomic(file, content);
|
|
70
|
+
return { file: relative, action: "created" };
|
|
71
|
+
}
|
|
72
|
+
async function generatedFile(root, relative, content) {
|
|
73
|
+
const file = path.join(root, relative);
|
|
74
|
+
const existing = await readTextFile(file);
|
|
75
|
+
if (existing === undefined) {
|
|
76
|
+
await writeFileAtomic(file, content);
|
|
77
|
+
return { file: relative, action: "created" };
|
|
78
|
+
}
|
|
79
|
+
if (!isGenerated(existing))
|
|
80
|
+
return { file: relative, action: "skipped", reason: "it was not written by cavelon" };
|
|
81
|
+
if (existing === content)
|
|
82
|
+
return { file: relative, action: "unchanged" };
|
|
83
|
+
await writeFileAtomic(file, content);
|
|
84
|
+
return { file: relative, action: "updated" };
|
|
85
|
+
}
|
|
86
|
+
async function folder(root, relative) {
|
|
87
|
+
const dir = path.join(root, relative);
|
|
88
|
+
try {
|
|
89
|
+
await fs.stat(dir);
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
await fs.mkdir(dir, { recursive: true });
|
|
94
|
+
await writeFileAtomic(path.join(dir, ".gitkeep"), "");
|
|
95
|
+
return [{ file: `${relative}/`, action: "created" }];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function writeSkills(root, roots) {
|
|
99
|
+
const skills = await bundledSkills();
|
|
100
|
+
if (!skills.length) {
|
|
101
|
+
throw new CavelonError(ExitCode.failure, {
|
|
102
|
+
code: "skills_missing",
|
|
103
|
+
message: "This cavelon has no skills to install (its package is incomplete).",
|
|
104
|
+
hint: "Reinstall @cavelon/cli.",
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const actions = [];
|
|
108
|
+
for (const skillRoot of roots) {
|
|
109
|
+
for (const skill of skills) {
|
|
110
|
+
for (const file of skill.files) {
|
|
111
|
+
actions.push(await generatedFile(root, `${skillRoot}/${skill.name}/${file.path}`, generatedCopy(file)));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return actions;
|
|
116
|
+
}
|
|
117
|
+
async function writeMcp(root, target, onlyExisting) {
|
|
118
|
+
const file = path.join(root, target.file);
|
|
119
|
+
const existing = await readTextFile(file);
|
|
120
|
+
if (target.format === "toml")
|
|
121
|
+
return applyBlock(root, file, upsertBlock(existing, target.block, "hash", { onlyExisting }));
|
|
122
|
+
if (onlyExisting) {
|
|
123
|
+
let present = false;
|
|
124
|
+
try {
|
|
125
|
+
present = Boolean(existing && JSON.parse(existing)[target.keys[0]]?.[target.keys[1]]);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
present = false;
|
|
129
|
+
}
|
|
130
|
+
if (!present)
|
|
131
|
+
return { file: target.file, action: "skipped", reason: "it has no cavelon entry" };
|
|
132
|
+
}
|
|
133
|
+
const result = upsertJsonEntry(existing, target.keys, target.entry);
|
|
134
|
+
if (result.outcome === "skipped") {
|
|
135
|
+
result.reason = `${result.reason}; add "${target.keys.join(".")}": ${JSON.stringify(target.entry)} yourself`;
|
|
136
|
+
}
|
|
137
|
+
return applyBlock(root, file, result);
|
|
138
|
+
}
|
|
139
|
+
async function installedFallback(root) {
|
|
140
|
+
const skillRoots = [];
|
|
141
|
+
for (const skillRoot of SKILL_ROOTS) {
|
|
142
|
+
try {
|
|
143
|
+
const names = await fs.readdir(path.join(root, skillRoot));
|
|
144
|
+
for (const name of names.filter((n) => n.startsWith("cavelon-"))) {
|
|
145
|
+
if (isGenerated(await readTextFile(path.join(root, skillRoot, name, "SKILL.md")))) {
|
|
146
|
+
skillRoots.push(skillRoot);
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const agents = [];
|
|
155
|
+
for (const agent of AGENTS) {
|
|
156
|
+
if (!agent.mcp)
|
|
157
|
+
continue;
|
|
158
|
+
const text = await readTextFile(path.join(root, agent.mcp.file));
|
|
159
|
+
if (text?.includes("cavelon"))
|
|
160
|
+
agents.push(agent);
|
|
161
|
+
}
|
|
162
|
+
return { skillRoots, agents };
|
|
163
|
+
}
|
|
164
|
+
async function installHook(root, onlyExisting) {
|
|
165
|
+
const hooks = (await git(["rev-parse", "--git-path", "hooks"], root))?.trim();
|
|
166
|
+
const prefix = (await git(["rev-parse", "--show-prefix"], root))?.trim();
|
|
167
|
+
if (!hooks || prefix === undefined) {
|
|
168
|
+
return { file: ".git/hooks/pre-commit", action: "skipped", reason: "this folder is not in a git repository" };
|
|
169
|
+
}
|
|
170
|
+
const file = path.resolve(root, hooks, "pre-commit");
|
|
171
|
+
const body = HOOK_LINES(prefix).join("\n");
|
|
172
|
+
const existing = await readTextFile(file);
|
|
173
|
+
let result = upsertBlock(existing, body, "hash", { onlyExisting, afterShebang: true });
|
|
174
|
+
if (result.outcome === "created")
|
|
175
|
+
result = { ...result, content: `#!/bin/sh\n${result.content}` };
|
|
176
|
+
const action = await applyBlock(root, file, result, 0o700);
|
|
177
|
+
if (action.action !== "skipped" && action.action !== "unchanged") {
|
|
178
|
+
const mode = (await fs.stat(file)).mode & 0o777;
|
|
179
|
+
if (!(mode & 0o100))
|
|
180
|
+
await fs.chmod(file, mode | 0o100).catch(() => undefined);
|
|
181
|
+
}
|
|
182
|
+
return action;
|
|
183
|
+
}
|
|
184
|
+
function solutionYaml(values) {
|
|
185
|
+
return [
|
|
186
|
+
"# A Cavelon solution. `cavelon` finds this file from the working directory upwards;",
|
|
187
|
+
"# it names the instance, tenant and solution, never a token.",
|
|
188
|
+
toYaml(values).trimEnd(),
|
|
189
|
+
"",
|
|
190
|
+
].join("\n");
|
|
191
|
+
}
|
|
192
|
+
function envYaml(name, harness) {
|
|
193
|
+
return [
|
|
194
|
+
`# Where \`cavelon apply --env ${name}\` goes. Never a token or a secret value.`,
|
|
195
|
+
"# tenant: <slug or id> # default: the tenant in cavelon.yaml",
|
|
196
|
+
harness ? `harness: ${harness}` : "# harness: <slug> # created as a draft when it does not exist yet",
|
|
197
|
+
"# mode: overwrite # or replace",
|
|
198
|
+
"# runtime_bindings: # the package's runtime requirement key -> this tenant's resource id",
|
|
199
|
+
"# <key>: <id>",
|
|
200
|
+
"",
|
|
201
|
+
].join("\n");
|
|
202
|
+
}
|
|
203
|
+
async function hasPackageFiles(root, dir) {
|
|
204
|
+
try {
|
|
205
|
+
return (await fs.readdir(path.join(root, dir))).some((n) => /\.(ya?ml|json)$/i.test(n));
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const MAX_PACKAGE_FILE_BYTES = 50 * 1024 * 1024;
|
|
212
|
+
function importFileError(from, reason, hint) {
|
|
213
|
+
return new CavelonError(ExitCode.usage, {
|
|
214
|
+
code: "package_import_invalid",
|
|
215
|
+
message: `${from} is not a package file: ${reason}.`,
|
|
216
|
+
hint: hint ?? "Pass a package export: a JSON or YAML file with one key per section (manifest, harnesses, agents, …).",
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
async function readImportFile(cwd, from) {
|
|
220
|
+
const file = path.resolve(cwd, from);
|
|
221
|
+
const stat = await fs.stat(file).catch(() => undefined);
|
|
222
|
+
if (!stat?.isFile())
|
|
223
|
+
throw usageError(`No file ${from}.`, "Pass the path of a package export (JSON or YAML) to --from.");
|
|
224
|
+
if (stat.size > MAX_PACKAGE_FILE_BYTES)
|
|
225
|
+
throw importFileError(from, `it is larger than ${MAX_PACKAGE_FILE_BYTES / 1024 / 1024} MB`);
|
|
226
|
+
const text = (await readTextFile(file)) ?? "";
|
|
227
|
+
let value;
|
|
228
|
+
if (/\.json$/i.test(file)) {
|
|
229
|
+
try {
|
|
230
|
+
value = JSON.parse(text);
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
throw importFileError(from, `not valid JSON (${error.message})`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
const doc = parseDocument(text, { uniqueKeys: true, prettyErrors: false });
|
|
238
|
+
if (doc.errors.length)
|
|
239
|
+
throw importFileError(from, `not valid YAML (${doc.errors[0].message.split("\n")[0]})`);
|
|
240
|
+
value = doc.toJS({ maxAliasCount: 1000 });
|
|
241
|
+
}
|
|
242
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
243
|
+
throw importFileError(from, "its top level is not a mapping of sections");
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
function onlyHarnessSlug(pkg) {
|
|
247
|
+
const harnesses = Array.isArray(pkg.harnesses) ? pkg.harnesses : [];
|
|
248
|
+
if (harnesses.length !== 1)
|
|
249
|
+
return undefined;
|
|
250
|
+
const slug = harnesses[0]?.slug;
|
|
251
|
+
return typeof slug === "string" && slug.trim() ? slug.trim() : undefined;
|
|
252
|
+
}
|
|
253
|
+
async function importPackage(ctx, project, from, pkg, force) {
|
|
254
|
+
const version = packageVersionOf(pkg);
|
|
255
|
+
const { schema } = await schemaFor(ctx, version ?? project.packageVersion, false);
|
|
256
|
+
if (!schema)
|
|
257
|
+
ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
|
|
258
|
+
const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
|
|
259
|
+
const overwritten = [];
|
|
260
|
+
for (const file of planned.written) {
|
|
261
|
+
if ((await readTextFile(path.join(project.root, file))) !== undefined)
|
|
262
|
+
overwritten.push(file);
|
|
263
|
+
}
|
|
264
|
+
const conflicts = [...overwritten, ...planned.removed].sort((a, b) => a.localeCompare(b, "en"));
|
|
265
|
+
if (conflicts.length && !force) {
|
|
266
|
+
throw new CavelonError(ExitCode.conflict, {
|
|
267
|
+
code: "package_files_differ",
|
|
268
|
+
message: `${from} would change or remove package files that hold something else: ${conflicts.slice(0, 5).join(", ")}` +
|
|
269
|
+
`${conflicts.length > 5 ? ` and ${conflicts.length - 5} more` : ""}. Nothing was written.`,
|
|
270
|
+
hint: "Commit or compare them first, then pass --force to replace them with the file's package.",
|
|
271
|
+
details: { files: conflicts },
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
const files = await writePackage(project.root, project.layout, pkg, schema, {});
|
|
275
|
+
if (version && project.packageVersion !== version)
|
|
276
|
+
await setProjectKey(project, "package_version", version);
|
|
277
|
+
const known = new Set(schemaSections(schema));
|
|
278
|
+
const ignored = schema ? Object.keys(pkg).filter((section) => !known.has(section) && safeSectionName(section)) : [];
|
|
279
|
+
for (const section of ignored) {
|
|
280
|
+
ctx.warn(`This instance's package schema has no section "${section}"; it was written, apply sends it as it is, and the instance ignores it.`);
|
|
281
|
+
}
|
|
282
|
+
for (const section of files.refused)
|
|
283
|
+
ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
|
|
284
|
+
return { from, files, ignored, package_version: version ?? null };
|
|
285
|
+
}
|
|
286
|
+
async function runInit(ctx, input) {
|
|
287
|
+
const update = boolOption(input, "update");
|
|
288
|
+
const from = stringOption(input, "from");
|
|
289
|
+
const agentNames = listOption(input, "agents");
|
|
290
|
+
const agents = agentNames.length ? parseAgents(agentNames) : [];
|
|
291
|
+
const session = await ctx.session();
|
|
292
|
+
const actions = [];
|
|
293
|
+
const next = [];
|
|
294
|
+
if (from !== undefined && !from.trim())
|
|
295
|
+
throw usageError("--from needs the path of a package file.");
|
|
296
|
+
if (from && update)
|
|
297
|
+
throw usageError("--from and --update do not go together.", "Run `cavelon init --from <file>` and `cavelon init --update` one after the other.");
|
|
298
|
+
if (boolOption(input, "force") && !from)
|
|
299
|
+
throw usageError("--force only applies to --from.");
|
|
300
|
+
const imported = from ? await readImportFile(ctx.io.cwd, from) : undefined;
|
|
301
|
+
if (update) {
|
|
302
|
+
if (!session.project)
|
|
303
|
+
throw usageError("No cavelon.yaml here or above.", "Run `cavelon init` first.");
|
|
304
|
+
const root = session.project.root;
|
|
305
|
+
actions.push(await block(root, "AGENTS.md", AGENTS_BLOCK, "html", { onlyExisting: true }));
|
|
306
|
+
const claude = await claudeImport(root, true);
|
|
307
|
+
if (claude)
|
|
308
|
+
actions.push(claude);
|
|
309
|
+
actions.push(await block(root, ".gitignore", GITIGNORE_BLOCK, "hash", { onlyExisting: true }));
|
|
310
|
+
actions.push(await installHook(root, !boolOption(input, "hook")));
|
|
311
|
+
const installed = await installedFallback(root);
|
|
312
|
+
const skillRoots = agents.length ? SKILL_ROOTS : installed.skillRoots;
|
|
313
|
+
if (skillRoots.length)
|
|
314
|
+
actions.push(...(await writeSkills(root, skillRoots)));
|
|
315
|
+
for (const agent of new Set([...installed.agents, ...agents])) {
|
|
316
|
+
if (agent.mcp)
|
|
317
|
+
actions.push(await writeMcp(root, agent.mcp, !agents.includes(agent)));
|
|
318
|
+
}
|
|
319
|
+
return { root, actions: actions.filter((a) => !(a.action === "skipped" && /does not exist|no cavelon (block|entry)/.test(a.reason ?? ""))), next, imported: undefined };
|
|
320
|
+
}
|
|
321
|
+
const packageHarness = imported ? onlyHarnessSlug(imported) : undefined;
|
|
322
|
+
const root = ctx.io.cwd;
|
|
323
|
+
const existing = await readTextFile(path.join(root, PROJECT_FILE));
|
|
324
|
+
if (existing !== undefined) {
|
|
325
|
+
actions.push({ file: PROJECT_FILE, action: "unchanged" });
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
const url = requireInstance(session);
|
|
329
|
+
requireToken(session);
|
|
330
|
+
const contracts = await ctx.contracts();
|
|
331
|
+
const caps = await contracts.capabilities();
|
|
332
|
+
if (contracts.needsTenant) {
|
|
333
|
+
throw new CavelonError(ExitCode.usage, {
|
|
334
|
+
code: "tenant_required",
|
|
335
|
+
message: "A solution belongs to one tenant, and none is chosen.",
|
|
336
|
+
hint: "Pass --tenant <slug>, or run `cavelon use <tenant>` first.",
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
const schema = await contracts.packageSchema();
|
|
340
|
+
await contracts.errorCatalog().catch(() => null);
|
|
341
|
+
if (!schema)
|
|
342
|
+
ctx.warn("The instance does not publish its package schema; `validate` will have nothing to check against.");
|
|
343
|
+
let tenant = session.tenant;
|
|
344
|
+
if (!tenant && session.tokenKind !== "api_key") {
|
|
345
|
+
const principal = await readPrincipal(await ctx.client());
|
|
346
|
+
tenant = principal?.tenant_id ?? undefined;
|
|
347
|
+
}
|
|
348
|
+
const harness = stringOption(input, "harness") ?? packageHarness;
|
|
349
|
+
const values = { instance: url };
|
|
350
|
+
if (tenant)
|
|
351
|
+
values.tenant = tenant;
|
|
352
|
+
if (harness)
|
|
353
|
+
values.harness = harness;
|
|
354
|
+
const version = caps?.contracts?.package_versions?.current ?? schema?.["x-package-version"];
|
|
355
|
+
if (version)
|
|
356
|
+
values.package_version = version;
|
|
357
|
+
values.layout = defaultLayoutFor(schema);
|
|
358
|
+
await writeFileAtomic(path.join(root, PROJECT_FILE), solutionYaml(values));
|
|
359
|
+
actions.push({ file: PROJECT_FILE, action: "created" });
|
|
360
|
+
}
|
|
361
|
+
const project = parseProject(path.join(root, PROJECT_FILE), (await readTextFile(path.join(root, PROJECT_FILE))));
|
|
362
|
+
for (const dir of new Set([project.layout.package, "tests", ...Object.values(project.layout.items)])) {
|
|
363
|
+
actions.push(...(await folder(root, dir)));
|
|
364
|
+
}
|
|
365
|
+
actions.push(...(await folder(root, "seeds")));
|
|
366
|
+
const harness = stringOption(input, "harness") ?? project.harness ?? packageHarness;
|
|
367
|
+
actions.push(await ownFile(root, `${ENV_DIR}/test.yaml`, envYaml("test", harness)));
|
|
368
|
+
actions.push(await ownFile(root, `${ENV_DIR}/prod.yaml`, envYaml("prod", undefined)));
|
|
369
|
+
if (await ensureStateDir(root))
|
|
370
|
+
actions.push({ file: `${STATE_DIR}/`, action: "created" });
|
|
371
|
+
actions.push(await block(root, ".gitignore", GITIGNORE_BLOCK, "hash"));
|
|
372
|
+
actions.push(await block(root, "AGENTS.md", AGENTS_BLOCK, "html"));
|
|
373
|
+
const claude = await claudeImport(root, false);
|
|
374
|
+
if (claude)
|
|
375
|
+
actions.push(claude);
|
|
376
|
+
if (agents.length) {
|
|
377
|
+
actions.push(...(await writeSkills(root, SKILL_ROOTS)));
|
|
378
|
+
for (const agent of agents)
|
|
379
|
+
if (agent.mcp)
|
|
380
|
+
actions.push(await writeMcp(root, agent.mcp, false));
|
|
381
|
+
}
|
|
382
|
+
if (boolOption(input, "hook"))
|
|
383
|
+
actions.push(await installHook(root, false));
|
|
384
|
+
else
|
|
385
|
+
next.push("Catch an invalid package before each commit: cavelon init --hook");
|
|
386
|
+
let result;
|
|
387
|
+
if (imported && from) {
|
|
388
|
+
result = await importPackage(ctx, project, from, imported, boolOption(input, "force"));
|
|
389
|
+
if (packageHarness && !project.harness && !stringOption(input, "harness"))
|
|
390
|
+
await setProjectKey(project, "harness", packageHarness);
|
|
391
|
+
next.unshift("Check it offline: cavelon validate", `Preview it on the instance: cavelon apply${harness ? " --env test" : " --harness <slug>"}`);
|
|
392
|
+
}
|
|
393
|
+
else if (!(await hasPackageFiles(root, project.layout.package))) {
|
|
394
|
+
next.unshift(harness
|
|
395
|
+
? `Bring the solution into package/: cavelon pull`
|
|
396
|
+
: "Bring an existing solution into package/: cavelon pull --harness <slug> (or write package files, then cavelon validate)");
|
|
397
|
+
}
|
|
398
|
+
return { root, actions, next, imported: result };
|
|
399
|
+
}
|
|
400
|
+
export const init = {
|
|
401
|
+
name: "init",
|
|
402
|
+
summary: "Make this folder a Cavelon solution: cavelon.yaml, package/, tests/, env/ and .cavelon/.",
|
|
403
|
+
description: "Never overwrites a file it did not create. AGENTS.md, .gitignore and an existing CLAUDE.md get at most a block between\n" +
|
|
404
|
+
"cavelon:begin and cavelon:end markers. --agents also writes the skills to .agents/skills/ and .claude/skills/ and each\n" +
|
|
405
|
+
"named agent's `cavelon mcp` entry, for agents without the Cavelon plugin. --update changes only those marked blocks and\n" +
|
|
406
|
+
"the fallback files a previous init wrote. --from writes an existing package file (JSON or YAML export) into package/ and\n" +
|
|
407
|
+
"tests/ as `pull` writes an export, so validate and apply take it from there; it refuses to change or remove a package\n" +
|
|
408
|
+
"file that holds something else unless --force, and names the sections the instance's schema does not know.",
|
|
409
|
+
readOnly: false,
|
|
410
|
+
destructive: true,
|
|
411
|
+
idempotent: true,
|
|
412
|
+
mcpTool: "init",
|
|
413
|
+
options: {
|
|
414
|
+
harness: { type: "string", value: "<slug>", description: "The solution (harness) this folder holds; pull and apply use it." },
|
|
415
|
+
agents: {
|
|
416
|
+
type: "string",
|
|
417
|
+
value: "<list>",
|
|
418
|
+
multiple: true,
|
|
419
|
+
description: `Write the fallback for these agents: ${AGENTS.map((a) => a.name).join(", ")} or all (comma-separated).`,
|
|
420
|
+
},
|
|
421
|
+
hook: { type: "boolean", description: "Add a git pre-commit hook that runs `cavelon validate`." },
|
|
422
|
+
update: { type: "boolean", description: "Only bring the marked blocks and fallback files to this version." },
|
|
423
|
+
from: { type: "string", value: "<file>", description: "Write this package file (a JSON or YAML export) into package/ and tests/." },
|
|
424
|
+
force: { type: "boolean", description: "With --from: replace package files that hold something else." },
|
|
425
|
+
},
|
|
426
|
+
examples: [
|
|
427
|
+
"cavelon init --instance https://cavelon.example.com --tenant acme --harness support",
|
|
428
|
+
"cavelon init --agents codex,cursor --hook",
|
|
429
|
+
"cavelon init --update",
|
|
430
|
+
"cavelon init --instance https://cavelon.example.com --tenant acme --from ./blueprint.json",
|
|
431
|
+
],
|
|
432
|
+
async run(ctx, input) {
|
|
433
|
+
const { root, actions, next, imported } = await runInit(ctx, input);
|
|
434
|
+
const changed = actions.filter((a) => a.action !== "unchanged");
|
|
435
|
+
const skipped = actions.filter((a) => a.action === "skipped");
|
|
436
|
+
for (const s of skipped)
|
|
437
|
+
ctx.warn(`Left ${s.file} as it is: ${s.reason}.`);
|
|
438
|
+
const lines = changed.filter((a) => a.action !== "skipped").map((a) => `${a.action.padEnd(9)} ${a.file}`);
|
|
439
|
+
if (imported) {
|
|
440
|
+
lines.push(...imported.files.written.map((f) => `written ${f}`), ...imported.files.removed.map((f) => `removed ${f}`));
|
|
441
|
+
const same = imported.files.unchanged.length;
|
|
442
|
+
lines.push(`Wrote ${imported.from} into the solution${same ? ` (${same} file${same === 1 ? "" : "s"} already held it)` : ""}.`);
|
|
443
|
+
if (imported.ignored.length)
|
|
444
|
+
lines.push(`ignored ${imported.ignored.join(", ")} (not in this instance's package schema)`);
|
|
445
|
+
}
|
|
446
|
+
const text = [
|
|
447
|
+
lines.length ? lines.join("\n") : "Nothing to change.",
|
|
448
|
+
...(next.length ? ["", "Next:", ...next.map((n) => ` ${n}`)] : []),
|
|
449
|
+
].join("\n");
|
|
450
|
+
return { data: { solution: root, files: actions, ...(imported ? { imported } : {}), next }, text };
|
|
451
|
+
},
|
|
452
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { CavelonError } from "../errors.js";
|
|
2
|
+
import { table } from "../format.js";
|
|
3
|
+
import { callStable } from "../invoke.js";
|
|
4
|
+
import { STATE_DIR, writeState } from "../local-state.js";
|
|
5
|
+
const LISTINGS = [
|
|
6
|
+
{ label: "solutions", path: "/api/v1/harnesses" },
|
|
7
|
+
{ label: "knowledge bases", path: "/api/v1/knowledge-bases", query: { page_size: 100 } },
|
|
8
|
+
{ label: "tools", path: "/api/v1/tools" },
|
|
9
|
+
{ label: "test suites", path: "/api/v1/test-suites" },
|
|
10
|
+
{ label: "sandboxes", path: "/api/v1/sandboxes" },
|
|
11
|
+
];
|
|
12
|
+
const MAX_ROWS = 100;
|
|
13
|
+
const COLUMNS = ["slug", "name", "status", "id"];
|
|
14
|
+
function itemsOf(data) {
|
|
15
|
+
const list = Array.isArray(data) ? data : data && typeof data === "object" ? (data.items ?? data.tools) : undefined;
|
|
16
|
+
return Array.isArray(list) ? list.filter((x) => Boolean(x) && typeof x === "object") : [];
|
|
17
|
+
}
|
|
18
|
+
function row(item) {
|
|
19
|
+
const out = {};
|
|
20
|
+
out.slug = item.slug ?? item.key ?? null;
|
|
21
|
+
out.name = item.name ?? item.display_name ?? null;
|
|
22
|
+
out.status = item.status ?? item.lifecycle_state ?? item.scope ?? null;
|
|
23
|
+
out.id = item.id ?? null;
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
export async function writeInventory(ctx, root, now) {
|
|
27
|
+
const sections = [];
|
|
28
|
+
const counts = [];
|
|
29
|
+
for (const listing of LISTINGS) {
|
|
30
|
+
let body;
|
|
31
|
+
try {
|
|
32
|
+
const data = await callStable(ctx, "GET", listing.path, `listing ${listing.label}`, { query: listing.query });
|
|
33
|
+
const items = itemsOf(data);
|
|
34
|
+
counts.push({ label: listing.label, count: items.length });
|
|
35
|
+
const rows = items.slice(0, MAX_ROWS).map(row);
|
|
36
|
+
const columns = COLUMNS.filter((c) => rows.some((r) => r[c] !== null && r[c] !== undefined));
|
|
37
|
+
body = items.length
|
|
38
|
+
? `\`\`\`text\n${table(rows, columns, 50)}\n\`\`\`${items.length > MAX_ROWS ? `\n\n… and ${items.length - MAX_ROWS} more.` : ""}`
|
|
39
|
+
: "None.";
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
counts.push({ label: listing.label, count: null });
|
|
43
|
+
body = `Not readable here: ${error instanceof CavelonError ? error.message : String(error)}`;
|
|
44
|
+
}
|
|
45
|
+
sections.push(`## ${listing.label[0].toUpperCase()}${listing.label.slice(1)}\n\n${body}`);
|
|
46
|
+
}
|
|
47
|
+
const text = [
|
|
48
|
+
"# Tenant inventory",
|
|
49
|
+
"",
|
|
50
|
+
`Written by \`cavelon pull\` at ${now.toISOString()}; \`cavelon pull\` refreshes it. Local state, never committed.`,
|
|
51
|
+
"",
|
|
52
|
+
...sections.flatMap((s) => [s, ""]),
|
|
53
|
+
].join("\n");
|
|
54
|
+
await writeState(root, "inventory.md", text);
|
|
55
|
+
return { file: `${STATE_DIR}/inventory.md`, counts };
|
|
56
|
+
}
|