@cavelon/cli 0.1.4 → 0.1.5
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 +43 -17
- package/dist/choose.js +8 -4
- package/dist/code-hints.js +74 -0
- package/dist/commands/api.js +44 -9
- package/dist/commands/async.js +26 -5
- package/dist/commands/docs.js +183 -37
- package/dist/commands/fmt.js +117 -0
- package/dist/commands/index.js +6 -1
- package/dist/commands/init.js +27 -5
- package/dist/commands/inventory.js +27 -5
- package/dist/commands/models.js +7 -1
- package/dist/commands/schema.js +193 -0
- package/dist/commands/session.js +69 -13
- package/dist/commands/solution.js +243 -34
- package/dist/commands/tenants.js +125 -15
- package/dist/commands/work.js +245 -24
- package/dist/contracts.js +3 -0
- package/dist/default-route.js +21 -0
- package/dist/errors.js +4 -0
- package/dist/git.js +14 -5
- package/dist/http.js +27 -4
- package/dist/invoke.js +8 -4
- package/dist/kit-codes.js +85 -0
- package/dist/limits.js +12 -1
- package/dist/local-state.js +9 -2
- package/dist/main.js +16 -3
- package/dist/mcp.js +13 -5
- package/dist/openapi.js +47 -21
- package/dist/operations.js +4 -3
- package/dist/package-check.js +193 -4
- package/dist/package-files.js +21 -10
- package/dist/package-format.js +149 -0
- package/dist/package-references.js +231 -0
- package/dist/preview-report.js +152 -0
- package/dist/skills/cavelon-authoring/SKILL.md +63 -7
- package/dist/skills/cavelon-long-running/SKILL.md +3 -1
- package/dist/skills/cavelon-loop/SKILL.md +57 -13
- package/dist/skills/cavelon-testing/SKILL.md +71 -4
- package/dist/tenant-choice.js +12 -5
- package/package.json +1 -1
package/dist/commands/tenants.js
CHANGED
|
@@ -4,10 +4,11 @@ import { keyValues, moreHint, table } from "../format.js";
|
|
|
4
4
|
import { callStable } from "../invoke.js";
|
|
5
5
|
import { formatQuota, limitError, limitsOrWarn, readQuotas } from "../limits.js";
|
|
6
6
|
import { containing } from "../choose.js";
|
|
7
|
-
import { readTenantless } from "../principal.js";
|
|
7
|
+
import { readPrincipal, readTenantless } from "../principal.js";
|
|
8
8
|
import { requireInstance } from "../session.js";
|
|
9
9
|
import { listsTenants, searchTenants } from "../tenant-choice.js";
|
|
10
|
-
import { resolveHarnessId } from "../harness-ref.js";
|
|
10
|
+
import { harnessNotFoundError, lookupHarness, resolveHarnessId } from "../harness-ref.js";
|
|
11
|
+
import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
|
|
11
12
|
import { cavelonCommand } from "../shell.js";
|
|
12
13
|
import { rememberTenant } from "./session.js";
|
|
13
14
|
function idempotency(key) {
|
|
@@ -18,17 +19,61 @@ const IDEMPOTENCY_OPTION = {
|
|
|
18
19
|
value: "<key>",
|
|
19
20
|
description: "Send an Idempotency-Key, so a retry does not create a second one.",
|
|
20
21
|
};
|
|
22
|
+
const TENANTS_MANAGE = "tenants.manage";
|
|
23
|
+
const CREATE_TENANT_REMEDY = "Create a personal access token with Allow Platform mode and a platform ceiling on /account/access-tokens " +
|
|
24
|
+
`(its owner needs ${TENANTS_MANAGE}) and run \`cavelon login\` with it, or create the tenant in the Admin (Platform › Tenants).`;
|
|
25
|
+
function checkCanCreateTenant(principal) {
|
|
26
|
+
const token = principal?.token;
|
|
27
|
+
if (!token)
|
|
28
|
+
return;
|
|
29
|
+
const ceiling = token.ceiling_role ? ` (ceiling ${token.ceiling_role})` : "";
|
|
30
|
+
if (token.platform_mode_allowed === false) {
|
|
31
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
32
|
+
code: "platform_mode_not_allowed",
|
|
33
|
+
message: `The personal access token "${token.name}" may not enter Platform mode${ceiling}, and creating a tenant needs Platform mode ` +
|
|
34
|
+
`with ${TENANTS_MANAGE}, so nothing was sent.`,
|
|
35
|
+
hint: CREATE_TENANT_REMEDY,
|
|
36
|
+
details: { platform_mode_allowed: false, ceiling_role: token.ceiling_role ?? null, sent: false },
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
if (principal.mode === "platform" && principal.permissions && !principal.permissions.includes(TENANTS_MANAGE)) {
|
|
40
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
41
|
+
code: "permission_missing",
|
|
42
|
+
message: `The personal access token "${token.name}" enters Platform mode${ceiling}, but without ${TENANTS_MANAGE}, so it cannot create a tenant; nothing was sent.`,
|
|
43
|
+
hint: `A token whose ceiling and owner's global role grant ${TENANTS_MANAGE} can; or create the tenant in the Admin (Platform › Tenants).`,
|
|
44
|
+
details: { permission: TENANTS_MANAGE, ceiling_role: token.ceiling_role ?? null, sent: false },
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function entersTenant(client, tenantId) {
|
|
49
|
+
const before = client.target.tenantId;
|
|
50
|
+
client.target.tenantId = tenantId;
|
|
51
|
+
try {
|
|
52
|
+
const response = await client.get("/api/v1/meta/principal", { allow: [400, 403, 404, 405] });
|
|
53
|
+
if (response.status === 404 || response.status === 405)
|
|
54
|
+
return undefined;
|
|
55
|
+
if (response.status === 200)
|
|
56
|
+
return { ok: response.data?.tenant_id === undefined || response.data.tenant_id === tenantId };
|
|
57
|
+
const detail = response.data?.detail;
|
|
58
|
+
return { ok: false, said: typeof detail === "string" && detail ? detail : `${response.status}` };
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
client.target.tenantId = before;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
21
64
|
export const tenantCreate = {
|
|
22
65
|
name: "tenant create",
|
|
23
66
|
summary: "Create a tenant (personal access token in Platform mode with tenants.manage).",
|
|
24
|
-
description: "A tenant API key never can.
|
|
67
|
+
description: "A tenant API key never can. Before sending, the token is checked: one that may not enter Platform mode, or enters it\n" +
|
|
68
|
+
"without tenants.manage, is refused with exit 7 and nothing is sent. With --use, the new tenant is chosen only once the\n" +
|
|
69
|
+
"instance confirms the token acts in it. Inviting people and assigning roles stay in the Admin.",
|
|
25
70
|
readOnly: false,
|
|
26
71
|
mcpTool: "tenant_create",
|
|
27
72
|
positionals: [{ name: "slug", description: "Lower-case letters, digits and dashes.", required: true }],
|
|
28
73
|
options: {
|
|
29
74
|
name: { type: "string", value: "<name>", description: "Display name (default: the slug)." },
|
|
30
75
|
plan: { type: "string", value: "<plan>", description: "Licence plan, when the instance knows several." },
|
|
31
|
-
use: { type: "boolean", description: "Switch to the new tenant afterwards (`cavelon use`)." },
|
|
76
|
+
use: { type: "boolean", description: "Switch to the new tenant afterwards (`cavelon use`), once the token is known to act in it." },
|
|
32
77
|
"idempotency-key": IDEMPOTENCY_OPTION,
|
|
33
78
|
},
|
|
34
79
|
async run(ctx, input) {
|
|
@@ -40,6 +85,8 @@ export const tenantCreate = {
|
|
|
40
85
|
hint: "Use a personal access token that allows Platform mode, owned by someone with tenants.manage.",
|
|
41
86
|
});
|
|
42
87
|
}
|
|
88
|
+
const client = await ctx.client({ tenant: false });
|
|
89
|
+
checkCanCreateTenant(await readPrincipal(client, { sendTenant: false }));
|
|
43
90
|
const slug = positional(input, "slug");
|
|
44
91
|
const body = { slug, name: stringOption(input, "name") ?? slug };
|
|
45
92
|
const plan = stringOption(input, "plan");
|
|
@@ -50,12 +97,18 @@ export const tenantCreate = {
|
|
|
50
97
|
sendTenant: false,
|
|
51
98
|
headers: idempotency(stringOption(input, "idempotency-key")),
|
|
52
99
|
});
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
100
|
+
const created = `Created tenant ${tenant.name} (${tenant.slug}, ${tenant.id}).`;
|
|
101
|
+
if (!boolOption(input, "use"))
|
|
102
|
+
return { data: tenant, text: `${created} Switch with: ${cavelonCommand("use", tenant.slug)}` };
|
|
103
|
+
const enters = await entersTenant(client, tenant.id);
|
|
104
|
+
if (enters && !enters.ok) {
|
|
105
|
+
ctx.warn(`This token does not act in the new tenant${enters.said ? ` (the instance said: ${enters.said})` : ""}, so the tenant chosen before stays. ` +
|
|
106
|
+
"A token that reaches the new tenant (an operator's token that reaches every tenant, or one that lists it) can switch with " +
|
|
107
|
+
`\`${cavelonCommand("use", tenant.slug)}\`.`);
|
|
108
|
+
return { data: { ...tenant, used: false }, text: `${created} Not switched: this token does not act in it.` };
|
|
109
|
+
}
|
|
110
|
+
await rememberTenant(ctx, requireInstance(session), { ref: tenant.slug, id: tenant.id, name: tenant.name });
|
|
111
|
+
return { data: { ...tenant, used: true }, text: `${created} Now using it.` };
|
|
59
112
|
},
|
|
60
113
|
};
|
|
61
114
|
export const tenantList = {
|
|
@@ -105,7 +158,11 @@ export const tenantList = {
|
|
|
105
158
|
const all = found.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: t.role, is_default: t.is_default }));
|
|
106
159
|
page = { ...pageOf(all, limit, cursor), source: "token", reaches_all_tenants: reach.reachesAll };
|
|
107
160
|
if (reach.reachesAll && !search) {
|
|
108
|
-
|
|
161
|
+
page.listed = "own_memberships";
|
|
162
|
+
page.note = "This token reaches every tenant; items and total count only your own memberships. Find any tenant with --search <part of the name>.";
|
|
163
|
+
note = all.length
|
|
164
|
+
? `\nThese are your own memberships; this token reaches every tenant on ${client.url}. Find any other: cavelon tenant list --search <part of the name>`
|
|
165
|
+
: `No memberships of your own; this token reaches every tenant on ${client.url}. Find any tenant with: cavelon tenant list --search <part of the name>`;
|
|
109
166
|
}
|
|
110
167
|
}
|
|
111
168
|
else {
|
|
@@ -127,7 +184,9 @@ export const tenantList = {
|
|
|
127
184
|
};
|
|
128
185
|
export const harnessList = {
|
|
129
186
|
name: "harness list",
|
|
130
|
-
summary: "List the tenant's solutions (harnesses).",
|
|
187
|
+
summary: "List the tenant's solutions (harnesses), marking the default route.",
|
|
188
|
+
description: "DEFAULT marks the tenant's default route: the solution that answers where a conversation names none (the tenant's chat\n" +
|
|
189
|
+
"and widget). An instance that does not say which one it is leaves the column out; `is_default` in --json is null then.",
|
|
131
190
|
readOnly: true,
|
|
132
191
|
idempotent: true,
|
|
133
192
|
mcpTool: "harness_list",
|
|
@@ -141,18 +200,69 @@ export const harnessList = {
|
|
|
141
200
|
query: { include_readiness: boolOption(input, "readiness") ? true : undefined },
|
|
142
201
|
});
|
|
143
202
|
const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
|
|
203
|
+
const marksDefault = harnesses.some((h) => typeof h.is_default === "boolean");
|
|
144
204
|
const page = pageOf(harnesses.map((h) => ({
|
|
145
205
|
id: h.id,
|
|
146
206
|
slug: h.slug,
|
|
147
207
|
name: h.name,
|
|
148
208
|
status: h.status,
|
|
149
|
-
is_default: h.is_default
|
|
209
|
+
is_default: marksDefault ? h.is_default === true : null,
|
|
150
210
|
...(h.readiness ? { ready_to_activate: h.readiness.ready_to_activate ?? null } : {}),
|
|
151
211
|
})), limit, stringOption(input, "cursor"));
|
|
152
|
-
const
|
|
212
|
+
const rows = page.items.map((h) => ({ ...h, default: h.is_default ? "yes" : "" }));
|
|
213
|
+
const columns = ["slug", "name", "status", ...(marksDefault ? ["default"] : []), ...(boolOption(input, "readiness") ? ["ready_to_activate"] : []), "id"];
|
|
153
214
|
return {
|
|
154
215
|
data: page,
|
|
155
|
-
text: (table(
|
|
216
|
+
text: (table(rows, columns) || "No solutions yet. Create one: cavelon harness new <slug>") + moreHint(page.next_cursor, "cavelon harness list"),
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
export const harnessDefault = {
|
|
221
|
+
name: "harness default",
|
|
222
|
+
summary: "Make a solution the tenant's default route; previews first, --confirm changes it.",
|
|
223
|
+
description: "The default route is the solution that answers where a conversation names none: the tenant's chat and widget. A new\n" +
|
|
224
|
+
"tenant's default is an empty `default` solution, so a solution built beside it answers nobody there until it becomes the\n" +
|
|
225
|
+
"default. Without --confirm nothing changes: the preview names the current default and the one that would replace it.\n" +
|
|
226
|
+
"This changes live traffic, so show the preview to a person and confirm only with their yes. `is_default` in\n" +
|
|
227
|
+
"harnesses.yaml is not applied by `apply`; this is the way to set it.",
|
|
228
|
+
readOnly: false,
|
|
229
|
+
idempotent: true,
|
|
230
|
+
mcpTool: "harness_default",
|
|
231
|
+
positionals: [{ name: "solution", description: "Name, slug or id of the solution; default: cavelon.yaml's harness." }],
|
|
232
|
+
options: {
|
|
233
|
+
confirm: { type: "boolean", description: "Change the default route (after a person saw the preview)." },
|
|
234
|
+
},
|
|
235
|
+
examples: ["cavelon harness default support", "cavelon harness default support --confirm"],
|
|
236
|
+
async run(ctx, input) {
|
|
237
|
+
const session = await ctx.session();
|
|
238
|
+
const ref = positional(input, "solution") ?? session.envFile?.harness ?? session.project?.harness;
|
|
239
|
+
if (!ref)
|
|
240
|
+
throw usageError("Which solution?", "Pass its name or slug (`cavelon harness list` shows them), or run it in a folder whose cavelon.yaml names one.");
|
|
241
|
+
const { harness, candidates } = await lookupHarness(ctx, ref);
|
|
242
|
+
if (!harness)
|
|
243
|
+
throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug));
|
|
244
|
+
const route = await readDefaultRoute(ctx);
|
|
245
|
+
const target = { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status };
|
|
246
|
+
const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
|
|
247
|
+
if (route.current?.id === harness.id) {
|
|
248
|
+
return { data: { changed: false, already_default: true, harness: target, default_route: current }, text: `${named(harness)} is already the tenant's default route.` };
|
|
249
|
+
}
|
|
250
|
+
const commands = defaultCommands(harness.slug);
|
|
251
|
+
const draft = harness.status !== "active" ? `${named(harness)} is ${harness.status}; activate it first (\`cavelon activate --harness ${harness.slug}\`), or the instance may refuse.` : undefined;
|
|
252
|
+
if (!boolOption(input, "confirm")) {
|
|
253
|
+
return {
|
|
254
|
+
data: { changed: false, harness: target, default_route: current, default_known: route.known, confirm: commands.confirm, ...(draft ? { note: draft } : {}) },
|
|
255
|
+
text: [
|
|
256
|
+
defaultChangeLine(harness, route),
|
|
257
|
+
...(draft ? [draft] : []),
|
|
258
|
+
`Show this to a person; with their yes: ${commands.confirm}`,
|
|
259
|
+
].join("\n"),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const updated = await setDefaultRoute(ctx, harness.id);
|
|
263
|
+
return {
|
|
264
|
+
data: { changed: true, harness: { ...target, status: updated?.status ?? target.status }, previous_default: current },
|
|
265
|
+
text: `Default route: ${named(harness)}${current ? ` (was ${named(current)})` : ""}.`,
|
|
156
266
|
};
|
|
157
267
|
},
|
|
158
268
|
};
|
package/dist/commands/work.js
CHANGED
|
@@ -5,7 +5,8 @@ import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../cap
|
|
|
5
5
|
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
6
6
|
import { confinedPath } from "../paths.js";
|
|
7
7
|
import { clip, keyValues, moreHint, table } from "../format.js";
|
|
8
|
-
import { callStable } from "../invoke.js";
|
|
8
|
+
import { callStable, workflowOperation } from "../invoke.js";
|
|
9
|
+
import { deref } from "../openapi.js";
|
|
9
10
|
import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
|
|
10
11
|
import { getOperation } from "../operations.js";
|
|
11
12
|
import { caseCounts, caseLabel, countsText, failedCase, NOT_PASSED, runVerdict } from "../results.js";
|
|
@@ -16,6 +17,115 @@ import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
|
|
|
16
17
|
import { stageErrors, stageErrorText } from "./loops.js";
|
|
17
18
|
import { resolveHarnessId } from "../harness-ref.js";
|
|
18
19
|
const WAIT_OPTION = { type: "boolean", description: "Wait for the work to finish (see `cavelon wait`).", cliOnly: true };
|
|
20
|
+
const UPLOAD_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/upload";
|
|
21
|
+
const DOCUMENTS_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents";
|
|
22
|
+
const ACTIVE_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/active";
|
|
23
|
+
function replaceSupport(doc, op) {
|
|
24
|
+
const schema = op.requestBody?.content?.["multipart/form-data"]?.schema;
|
|
25
|
+
const properties = doc && schema ? deref(doc, schema)?.properties : undefined;
|
|
26
|
+
return { byIds: Boolean(properties?.replace_doc_ids), byName: Boolean(properties?.replace_existing) };
|
|
27
|
+
}
|
|
28
|
+
const shortId = (id) => `${id.slice(0, 8)}…`;
|
|
29
|
+
async function existingDocuments(ctx, kbId) {
|
|
30
|
+
try {
|
|
31
|
+
const list = await callStable(ctx, "GET", DOCUMENTS_ROUTE, "listing a knowledge base's documents", { params: { kb_id: [kbId] } });
|
|
32
|
+
return (Array.isArray(list) ? list : []).filter((d) => d.is_active !== false && typeof d.filename === "string");
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (!(error instanceof CavelonError))
|
|
36
|
+
throw error;
|
|
37
|
+
ctx.warn(`Could not list the knowledge base's documents (${error.message}); files named like an existing document are not reported.`);
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function nameMatches(files, cwd, existing, mode, support) {
|
|
42
|
+
const matches = [];
|
|
43
|
+
const mapped = new Set();
|
|
44
|
+
for (const file of files) {
|
|
45
|
+
const filename = path.basename(file);
|
|
46
|
+
const same = existing.filter((d) => d.filename === filename).sort((a, b) => (b.created_at ?? "").localeCompare(a.created_at ?? ""));
|
|
47
|
+
same.forEach((document, index) => {
|
|
48
|
+
let plan = "stays_active";
|
|
49
|
+
if (mode === "default" && support.byName)
|
|
50
|
+
plan = "replaced_by_name";
|
|
51
|
+
if (mode === "replace")
|
|
52
|
+
plan = index === 0 && support.byIds && !mapped.has(filename) ? "replace_by_id" : "deactivate";
|
|
53
|
+
matches.push({ file: path.relative(cwd, file) || file, filename, document_id: document.id, plan });
|
|
54
|
+
});
|
|
55
|
+
mapped.add(filename);
|
|
56
|
+
}
|
|
57
|
+
return matches;
|
|
58
|
+
}
|
|
59
|
+
function plannedLine(match) {
|
|
60
|
+
const head = `${match.filename} exists (${shortId(match.document_id)})`;
|
|
61
|
+
switch (match.plan) {
|
|
62
|
+
case "stays_active":
|
|
63
|
+
return `${head} and stays active`;
|
|
64
|
+
case "replaced_by_name":
|
|
65
|
+
return `${head} and is replaced by the upload (--keep-both keeps it)`;
|
|
66
|
+
case "replace_by_id":
|
|
67
|
+
return `${head} and is replaced once the new file is verified`;
|
|
68
|
+
case "deactivate":
|
|
69
|
+
return `${head} and is deactivated after the upload`;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function outcomeLine(match) {
|
|
73
|
+
const head = `${match.filename} exists (${shortId(match.document_id)})`;
|
|
74
|
+
switch (match.outcome) {
|
|
75
|
+
case "replaced":
|
|
76
|
+
return `${head}: replaced`;
|
|
77
|
+
case "replace_requested":
|
|
78
|
+
return `${head}: replaced once the new file is verified`;
|
|
79
|
+
case "deactivated":
|
|
80
|
+
return `${head}: deactivated`;
|
|
81
|
+
case "not_uploaded":
|
|
82
|
+
return `${head} and stays active: its new version was not uploaded`;
|
|
83
|
+
default:
|
|
84
|
+
return `${head} and stays active`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function staysActiveHint(matches, mode) {
|
|
88
|
+
return mode === "default" && matches.some((m) => (m.outcome ?? m.plan) === "stays_active")
|
|
89
|
+
? "Both versions answer. --replace replaces the existing document; --keep-both keeps both without this note."
|
|
90
|
+
: "";
|
|
91
|
+
}
|
|
92
|
+
function settleMatches(matches, uploaded, uploadedFiles) {
|
|
93
|
+
const reported = uploaded.some((d) => Array.isArray(d.replaced_document_ids));
|
|
94
|
+
const replaced = new Set(uploaded.flatMap((d) => (Array.isArray(d.replaced_document_ids) ? d.replaced_document_ids : [])));
|
|
95
|
+
for (const match of matches) {
|
|
96
|
+
if (!uploadedFiles.has(match.file))
|
|
97
|
+
match.outcome = "not_uploaded";
|
|
98
|
+
else if (replaced.has(match.document_id))
|
|
99
|
+
match.outcome = "replaced";
|
|
100
|
+
else if (match.plan === "replace_by_id" && !reported)
|
|
101
|
+
match.outcome = "replace_requested";
|
|
102
|
+
else if (match.plan === "deactivate")
|
|
103
|
+
match.outcome = undefined;
|
|
104
|
+
else
|
|
105
|
+
match.outcome = "stays_active";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function deactivate(ctx, kbId, matches) {
|
|
109
|
+
const due = matches.filter((m) => m.plan === "deactivate" && m.outcome === undefined);
|
|
110
|
+
if (!due.length)
|
|
111
|
+
return undefined;
|
|
112
|
+
try {
|
|
113
|
+
await callStable(ctx, "PATCH", ACTIVE_ROUTE, "deactivating a document", {
|
|
114
|
+
params: { kb_id: [kbId] },
|
|
115
|
+
body: { updates: due.map((m) => ({ id: m.document_id, is_active: false })) },
|
|
116
|
+
});
|
|
117
|
+
for (const m of due)
|
|
118
|
+
m.outcome = "deactivated";
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (!(error instanceof CavelonError))
|
|
123
|
+
throw error;
|
|
124
|
+
for (const m of due)
|
|
125
|
+
m.outcome = "stays_active";
|
|
126
|
+
return error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
19
129
|
async function resolveKbId(ctx, ref) {
|
|
20
130
|
if (isUuid(ref))
|
|
21
131
|
return { id: ref };
|
|
@@ -240,7 +350,11 @@ export const kbUpload = {
|
|
|
240
350
|
summary: "Upload a folder's documents into a knowledge base; returns operation ids.",
|
|
241
351
|
description: "Hidden files are skipped. Ingestion runs on the instance; `cavelon wait` follows it.\n" +
|
|
242
352
|
"Files are checked against the instance's published upload limits first. A .zip goes only to a tenant that expands\n" +
|
|
243
|
-
"archives, and only within its caps on file count, unpacked size and compression ratio
|
|
353
|
+
"archives, and only within its caps on file count, unpacked size and compression ratio.\n" +
|
|
354
|
+
"A file named like an active document of the knowledge base is listed, with what happens to that document. An\n" +
|
|
355
|
+
"instance that replaces same-named documents on upload does so (--keep-both keeps both); elsewhere the old one stays\n" +
|
|
356
|
+
"active. --replace replaces it: through the instance's own replacement where its upload offers one, else the kit\n" +
|
|
357
|
+
"deactivates the old document after the upload (after the wait with --wait), and then only with --confirm.",
|
|
244
358
|
readOnly: false,
|
|
245
359
|
mcpTool: "kb_upload",
|
|
246
360
|
positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
|
|
@@ -248,16 +362,27 @@ export const kbUpload = {
|
|
|
248
362
|
kb: { type: "string", value: "<kb>", description: "Knowledge base name or id (required)." },
|
|
249
363
|
recursive: { type: "boolean", short: "r", description: "Include subfolders." },
|
|
250
364
|
ext: { type: "string", multiple: true, value: "<ext>", description: "Only these file extensions (pdf, md, …)." },
|
|
251
|
-
|
|
365
|
+
replace: { type: "boolean", description: "Replace active documents with the same file name." },
|
|
366
|
+
"keep-both": { type: "boolean", description: "Keep active documents with the same file name next to the new ones." },
|
|
367
|
+
confirm: { type: "boolean", description: "With --replace, deactivate the old documents the instance does not replace itself; without it nothing is sent." },
|
|
368
|
+
"dry-run": { type: "boolean", description: "List what would be uploaded and replaced, upload nothing." },
|
|
252
369
|
wait: WAIT_OPTION,
|
|
253
370
|
timeout: TIMEOUT_OPTION,
|
|
254
371
|
},
|
|
255
|
-
examples: [
|
|
372
|
+
examples: [
|
|
373
|
+
"cavelon kb upload ./docs --kb FAQ",
|
|
374
|
+
"cavelon kb upload ./docs/bergbahn-faq.md --kb FAQ --replace --dry-run",
|
|
375
|
+
"cavelon kb upload ./manuals --kb FAQ -r --ext pdf --wait --timeout 5m",
|
|
376
|
+
],
|
|
256
377
|
async run(ctx, input) {
|
|
257
|
-
const
|
|
378
|
+
const dirArg = positional(input, "dir");
|
|
379
|
+
const dir = await confinedPath(ctx, dirArg, "The folder");
|
|
258
380
|
const kbRef = stringOption(input, "kb");
|
|
259
381
|
if (!kbRef)
|
|
260
382
|
throw usageError("Which knowledge base?", "Pass --kb <name-or-id>.");
|
|
383
|
+
const mode = boolOption(input, "replace") ? "replace" : boolOption(input, "keep-both") ? "keep-both" : "default";
|
|
384
|
+
if (mode === "replace" && boolOption(input, "keep-both"))
|
|
385
|
+
throw usageError("--replace and --keep-both exclude each other.");
|
|
261
386
|
const extensions = listOption(input, "ext").flatMap((e) => e.split(",")).map((e) => e.replace(/^\./, "").toLowerCase()).filter(Boolean);
|
|
262
387
|
let stat;
|
|
263
388
|
try {
|
|
@@ -275,11 +400,38 @@ export const kbUpload = {
|
|
|
275
400
|
if (found.refusals.length)
|
|
276
401
|
throw refusalError(found, files.length);
|
|
277
402
|
}
|
|
403
|
+
const kb = await resolveKbId(ctx, kbRef);
|
|
404
|
+
const { doc, op } = await workflowOperation(ctx, "POST", UPLOAD_ROUTE, "document upload");
|
|
405
|
+
const support = replaceSupport(doc, op);
|
|
406
|
+
const existing = await existingDocuments(ctx, kb.id);
|
|
407
|
+
const matches = existing ? nameMatches(files, ctx.io.cwd, existing, mode, support) : [];
|
|
408
|
+
const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
|
|
409
|
+
const planned = matches.map(({ outcome: _outcome, ...m }) => m);
|
|
410
|
+
const hint = staysActiveHint(matches, mode);
|
|
411
|
+
const deactivations = matches.filter((m) => m.plan === "deactivate");
|
|
278
412
|
if (boolOption(input, "dry-run")) {
|
|
279
|
-
|
|
280
|
-
|
|
413
|
+
return {
|
|
414
|
+
data: { kb: kbRef, files: rel, count: rel.length, dry_run: true, existing: planned },
|
|
415
|
+
text: [
|
|
416
|
+
`Would upload ${rel.length} files:`,
|
|
417
|
+
...rel,
|
|
418
|
+
...matches.map(plannedLine),
|
|
419
|
+
...(hint ? [hint] : []),
|
|
420
|
+
...(deactivations.length ? [`The kit deactivates ${deactivations.length === 1 ? "that document" : "those documents"} only with --replace --confirm.`] : []),
|
|
421
|
+
].join("\n"),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
if (deactivations.length && !boolOption(input, "confirm")) {
|
|
425
|
+
const confirm = cavelonCommand("kb", "upload", dirArg, "--kb", kbRef, ...(boolOption(input, "recursive") ? ["-r"] : []), ...extensions.flatMap((e) => ["--ext", e]), "--replace", "--confirm");
|
|
426
|
+
return {
|
|
427
|
+
data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm },
|
|
428
|
+
text: [
|
|
429
|
+
`--replace uploads ${rel.length} files and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
|
|
430
|
+
...matches.map(plannedLine),
|
|
431
|
+
`Nothing was sent. Upload and deactivate with: ${confirm}`,
|
|
432
|
+
].join("\n"),
|
|
433
|
+
};
|
|
281
434
|
}
|
|
282
|
-
const kb = await resolveKbId(ctx, kbRef);
|
|
283
435
|
const batches = [];
|
|
284
436
|
let current = [];
|
|
285
437
|
let bytes = 0;
|
|
@@ -296,15 +448,26 @@ export const kbUpload = {
|
|
|
296
448
|
if (current.length)
|
|
297
449
|
batches.push(current);
|
|
298
450
|
const documents = [];
|
|
451
|
+
const uploadedFiles = new Set();
|
|
299
452
|
let failure;
|
|
300
453
|
for (const [index, batch] of batches.entries()) {
|
|
454
|
+
const names = new Set(batch.map((f) => path.basename(f)));
|
|
455
|
+
const replaceIds = Object.fromEntries(matches.filter((m) => m.plan === "replace_by_id" && names.has(m.filename)).map((m) => [m.filename, m.document_id]));
|
|
456
|
+
const fields = {};
|
|
457
|
+
if (Object.keys(replaceIds).length)
|
|
458
|
+
fields.replace_doc_ids = JSON.stringify(replaceIds);
|
|
459
|
+
if (mode === "keep-both" && support.byName)
|
|
460
|
+
fields.replace_existing = false;
|
|
301
461
|
try {
|
|
302
|
-
const uploaded = await callStable(ctx, "POST",
|
|
462
|
+
const uploaded = await callStable(ctx, "POST", UPLOAD_ROUTE, "document upload", {
|
|
303
463
|
params: { kb_id: [kb.id] },
|
|
464
|
+
body: Object.keys(fields).length ? fields : undefined,
|
|
304
465
|
files: batch.map((f) => ({ field: "files", path: f })),
|
|
305
466
|
timeoutMs: 300_000,
|
|
306
467
|
});
|
|
307
468
|
documents.push(...uploaded);
|
|
469
|
+
for (const f of batch)
|
|
470
|
+
uploadedFiles.add(path.relative(ctx.io.cwd, f) || f);
|
|
308
471
|
}
|
|
309
472
|
catch (error) {
|
|
310
473
|
if (!(error instanceof CavelonError) || documents.length === 0)
|
|
@@ -313,31 +476,67 @@ export const kbUpload = {
|
|
|
313
476
|
break;
|
|
314
477
|
}
|
|
315
478
|
}
|
|
479
|
+
settleMatches(matches, documents, uploadedFiles);
|
|
316
480
|
const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
|
|
317
|
-
const summary = {
|
|
481
|
+
const summary = () => ({
|
|
318
482
|
kb: { id: kb.id, name: kb.name ?? null },
|
|
319
|
-
documents: documents.map((d) => ({
|
|
483
|
+
documents: documents.map((d) => ({
|
|
484
|
+
id: d.id,
|
|
485
|
+
filename: d.filename,
|
|
486
|
+
status: d.status,
|
|
487
|
+
operation_id: d.operation_id ?? null,
|
|
488
|
+
...(Array.isArray(d.replaced_document_ids) ? { replaced_document_ids: d.replaced_document_ids } : {}),
|
|
489
|
+
})),
|
|
320
490
|
operation_ids: operationIds,
|
|
491
|
+
existing: matches,
|
|
492
|
+
});
|
|
493
|
+
const matchLines = () => {
|
|
494
|
+
const note = staysActiveHint(matches, mode);
|
|
495
|
+
return [...matches.map(outcomeLine), ...(note ? [note] : [])];
|
|
321
496
|
};
|
|
322
497
|
if (operationIds.length < documents.length)
|
|
323
498
|
ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
|
|
324
499
|
if (failure) {
|
|
500
|
+
const refused = await deactivate(ctx, kb.id, matches);
|
|
501
|
+
if (refused)
|
|
502
|
+
ctx.warn(`The old documents stay active: ${refused.message}`);
|
|
325
503
|
return {
|
|
326
|
-
data: { ...summary, error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
|
|
327
|
-
text:
|
|
328
|
-
`
|
|
329
|
-
|
|
504
|
+
data: { ...summary(), error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
|
|
505
|
+
text: [
|
|
506
|
+
`Uploaded ${documents.length} files, then: ${failure.error.message}`,
|
|
507
|
+
`Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}`,
|
|
508
|
+
...matchLines(),
|
|
509
|
+
...(operationIds.length ? [`Wait for the uploaded ones with: cavelon wait ${operationIds.join(" ")}`] : []),
|
|
510
|
+
].join("\n"),
|
|
330
511
|
exitCode: failure.error.exitCode,
|
|
331
512
|
};
|
|
332
513
|
}
|
|
333
514
|
if (boolOption(input, "wait") && ctx.mode === "cli" && operationIds.length) {
|
|
334
515
|
const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, stringOption(input, "timeout")));
|
|
335
|
-
|
|
516
|
+
const refused = waited.exitCode === ExitCode.ok ? await deactivate(ctx, kb.id, matches) : undefined;
|
|
517
|
+
if (waited.exitCode !== ExitCode.ok)
|
|
518
|
+
for (const m of matches)
|
|
519
|
+
if (m.outcome === undefined)
|
|
520
|
+
m.outcome = "stays_active";
|
|
521
|
+
if (refused)
|
|
522
|
+
ctx.warn(`The old documents stay active: ${refused.message}`);
|
|
523
|
+
return {
|
|
524
|
+
data: { ...summary(), ...waited.data },
|
|
525
|
+
text: [`Uploaded ${documents.length} files.`, ...matchLines(), waited.text].join("\n"),
|
|
526
|
+
exitCode: refused && waited.exitCode === ExitCode.ok ? refused.exitCode : waited.exitCode,
|
|
527
|
+
};
|
|
336
528
|
}
|
|
529
|
+
const refused = await deactivate(ctx, kb.id, matches);
|
|
530
|
+
if (refused)
|
|
531
|
+
ctx.warn(`The old documents stay active: ${refused.message}`);
|
|
337
532
|
return {
|
|
338
|
-
data: summary,
|
|
339
|
-
text:
|
|
340
|
-
|
|
533
|
+
data: summary(),
|
|
534
|
+
text: [
|
|
535
|
+
`Uploaded ${documents.length} files to ${kb.name ?? kb.id}.`,
|
|
536
|
+
...matchLines(),
|
|
537
|
+
...(operationIds.length ? [`Operations: ${operationIds.length}`, `Wait with: cavelon wait ${operationIds.join(" ")}`] : []),
|
|
538
|
+
].join("\n"),
|
|
539
|
+
exitCode: refused?.exitCode,
|
|
341
540
|
};
|
|
342
541
|
},
|
|
343
542
|
};
|
|
@@ -495,7 +694,24 @@ function summarizeTrace(t) {
|
|
|
495
694
|
conversation_id: t.conversation_id ?? null,
|
|
496
695
|
};
|
|
497
696
|
}
|
|
498
|
-
function
|
|
697
|
+
function outcomeOf(s) {
|
|
698
|
+
const attributes = s.attributes_json;
|
|
699
|
+
const outcome = attributes && typeof attributes === "object" ? attributes.knowledge_outcome : undefined;
|
|
700
|
+
return typeof outcome === "string" && outcome ? outcome : null;
|
|
701
|
+
}
|
|
702
|
+
function knowledgeOutcomes(spans) {
|
|
703
|
+
const out = new Map();
|
|
704
|
+
for (const s of spans) {
|
|
705
|
+
const outcome = outcomeOf(s);
|
|
706
|
+
if (!outcome)
|
|
707
|
+
continue;
|
|
708
|
+
out.set(s.id, outcome);
|
|
709
|
+
if (s.span_type === "retrieval" && s.parent_span_id && !out.has(s.parent_span_id))
|
|
710
|
+
out.set(s.parent_span_id, outcome);
|
|
711
|
+
}
|
|
712
|
+
return out;
|
|
713
|
+
}
|
|
714
|
+
function summarizeSpan(s, outcomes) {
|
|
499
715
|
const error = s.error_json ? clip(typeof s.error_json === "string" ? s.error_json : JSON.stringify(s.error_json), 200) : null;
|
|
500
716
|
return {
|
|
501
717
|
span_id: s.id,
|
|
@@ -505,6 +721,7 @@ function summarizeSpan(s) {
|
|
|
505
721
|
agent: s.agent_slug ?? null,
|
|
506
722
|
status: s.status ?? null,
|
|
507
723
|
duration_ms: s.duration_ms ?? null,
|
|
724
|
+
knowledge_outcome: outcomeOf(s) ?? outcomes?.get(s.id) ?? null,
|
|
508
725
|
error,
|
|
509
726
|
};
|
|
510
727
|
}
|
|
@@ -561,6 +778,8 @@ function notPassedLines(r, max) {
|
|
|
561
778
|
lines.push(` ${c.reason}`);
|
|
562
779
|
if (r.llm_judge_reasoning && r.llm_judge_reasoning !== r.error_message)
|
|
563
780
|
lines.push(` Judge: ${clip(r.llm_judge_reasoning, max)}`);
|
|
781
|
+
if (r.agent_slug)
|
|
782
|
+
lines.push(` Answered by: ${r.agent_slug}`);
|
|
564
783
|
const open = caseTraceCommand(r);
|
|
565
784
|
if (open)
|
|
566
785
|
lines.push(` Its traces (${open.label}): ${open.command}`);
|
|
@@ -578,6 +797,7 @@ async function testRunView(ctx, id, results, options) {
|
|
|
578
797
|
step: r.step_order ?? null,
|
|
579
798
|
status: r.status,
|
|
580
799
|
score: r.llm_judge_score ?? null,
|
|
800
|
+
agent: r.agent_slug ?? null,
|
|
581
801
|
conversation_id: r.conversation_id ?? null,
|
|
582
802
|
run_id: r.agent_run_id ?? null,
|
|
583
803
|
error: r.error_message ? clip(r.error_message, 200) : null,
|
|
@@ -595,7 +815,7 @@ async function testRunView(ctx, id, results, options) {
|
|
|
595
815
|
].filter(Boolean);
|
|
596
816
|
return {
|
|
597
817
|
data: { kind: "test", run_id: id, results: { ...page, items } },
|
|
598
|
-
text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
|
|
818
|
+
text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.agent) ? ["agent"] : []), ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
|
|
599
819
|
moreHint(page.next_cursor, cavelonCommand("trace", id, "--kind", "test")) +
|
|
600
820
|
(notPassed.length ? `\n\nDid not pass:\n${notPassed.flatMap((r) => notPassedLines(r, max)).join("\n")}` : "") +
|
|
601
821
|
(judged.length ? `\n\nJudge's reasoning:\n${judged.flatMap((r) => judgedLines(r, options.full ? max : 300)).join("\n")}` : "") +
|
|
@@ -673,13 +893,14 @@ export const trace = {
|
|
|
673
893
|
}
|
|
674
894
|
}
|
|
675
895
|
const spans = (detail.spans ?? []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
|
|
896
|
+
const outcomes = knowledgeOutcomes(spans);
|
|
676
897
|
if (spanId) {
|
|
677
898
|
const span = spans.find((s) => s.id === spanId);
|
|
678
899
|
if (!span)
|
|
679
900
|
throw new CavelonError(ExitCode.failure, { code: "span_not_found", message: `No span ${spanId} in trace ${traceId}.` });
|
|
680
901
|
const full = boolOption(input, "full");
|
|
681
902
|
const data = {
|
|
682
|
-
...summarizeSpan(span),
|
|
903
|
+
...summarizeSpan(span, outcomes),
|
|
683
904
|
model: span.model ?? null,
|
|
684
905
|
parent_span_id: span.parent_span_id ?? null,
|
|
685
906
|
input: detailOf(span.input_json, full),
|
|
@@ -690,12 +911,12 @@ export const trace = {
|
|
|
690
911
|
};
|
|
691
912
|
return { data, text: JSON.stringify(data, null, 2) };
|
|
692
913
|
}
|
|
693
|
-
const page = pageOf(spans.map(summarizeSpan), limit, cursor);
|
|
914
|
+
const page = pageOf(spans.map((s) => summarizeSpan(s, outcomes)), limit, cursor);
|
|
694
915
|
const base = cavelonCommand("trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId);
|
|
695
916
|
return {
|
|
696
917
|
data: { trace: summarizeTrace(detail), spans: page },
|
|
697
918
|
text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
|
|
698
|
-
table(page.items, ["seq", "type", "name", "status", "duration_ms", "span_id"]) +
|
|
919
|
+
table(page.items, ["seq", "type", "name", "status", ...(outcomes.size ? ["knowledge_outcome"] : []), "duration_ms", "span_id"]) +
|
|
699
920
|
moreHint(page.next_cursor, base) +
|
|
700
921
|
(page.items.length ? `\n\nOne span in full, by the span_id in its row: ${base} --span ${shellWord(page.items[0].span_id)}` : ""),
|
|
701
922
|
};
|
package/dist/contracts.js
CHANGED
|
@@ -17,6 +17,7 @@ export class Contracts {
|
|
|
17
17
|
live = false;
|
|
18
18
|
versionValue;
|
|
19
19
|
needsTenant = false;
|
|
20
|
+
cachedAt;
|
|
20
21
|
constructor(client, env, now) {
|
|
21
22
|
this.client = client;
|
|
22
23
|
this.env = env;
|
|
@@ -52,11 +53,13 @@ export class Contracts {
|
|
|
52
53
|
if (cached) {
|
|
53
54
|
this.caps = cached;
|
|
54
55
|
this.versionValue = state.version;
|
|
56
|
+
this.cachedAt = state.checked_at;
|
|
55
57
|
return cached;
|
|
56
58
|
}
|
|
57
59
|
}
|
|
58
60
|
const response = await this.client.get("/api/v1/meta/capabilities", { allow: [400, 404] });
|
|
59
61
|
this.live = true;
|
|
62
|
+
this.cachedAt = undefined;
|
|
60
63
|
if (response.status === 400) {
|
|
61
64
|
this.needsTenant = true;
|
|
62
65
|
this.caps = null;
|