@cavelon/cli 0.2.10 → 0.2.12
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/dist/attached-documents.js +121 -0
- package/dist/commands/chat.js +172 -14
- package/dist/commands/engagement.js +153 -0
- package/dist/commands/index.js +2 -0
- package/dist/commands/init.js +2 -2
- package/dist/commands/publication.js +3 -2
- package/dist/commands/solution.js +104 -10
- package/dist/commands/tenants.js +3 -2
- package/dist/commands/work.js +34 -5
- package/dist/engagement.js +117 -0
- package/dist/kit-codes.js +2 -0
- package/dist/managed-fields.js +212 -0
- package/dist/native-assets/THIRD-PARTY-NOTICES +2 -2
- package/dist/native-assets/kilo-server.mjs +65 -8
- package/dist/native-assets/kilo-tui.mjs +53 -8
- package/dist/native-assets/manifest.json +15 -15
- package/dist/native-assets/omp-extension.mjs +224 -288
- package/dist/native-assets/opencode-server.mjs +65 -8
- package/dist/native-assets/opencode-tui.mjs +53 -8
- package/dist/native-assets/pi-extension.mjs +224 -288
- package/dist/package-check.js +65 -5
- package/dist/package-format.js +10 -1
- package/dist/project.js +34 -0
- package/dist/setup-agents.js +1 -0
- package/dist/skills/cavelon-authoring/SKILL.md +51 -0
- package/dist/skills/cavelon-authoring/references/canvas-entrypoints.md +83 -0
- package/dist/skills/cavelon-long-running/SKILL.md +6 -0
- package/dist/skills/cavelon-loop/SKILL.md +8 -1
- package/dist/skills/cavelon-testing/SKILL.md +53 -1
- package/package.json +3 -3
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { locate } from "./package-files.js";
|
|
2
|
+
import { branches } from "./package-references.js";
|
|
3
|
+
export const ATTACHED_IGNORED_CODE = "attached_documents_value_ignored";
|
|
4
|
+
export const ATTACHED_CLAMPED_CODE = "attached_documents_wait_clamped";
|
|
5
|
+
const SETTING = "attached_documents";
|
|
6
|
+
const UNTIL_READABLE = "wait_until_readable";
|
|
7
|
+
const SECONDS = "wait_seconds";
|
|
8
|
+
const ATTACHMENTS_DOCS = "/docs/concepts/attachments";
|
|
9
|
+
export const ATTACHED_DOCUMENTS_CODES = [
|
|
10
|
+
{
|
|
11
|
+
code: ATTACHED_IGNORED_CODE,
|
|
12
|
+
area: "package",
|
|
13
|
+
message: "A solution's settings.attached_documents holds a value the instance ignores; a chat turn then waits for its files as long as the platform default.",
|
|
14
|
+
hint: "Write wait_until_readable as true or false (only false turns the wait off) and wait_seconds as a whole number of seconds, or remove the value to keep the platform default. " +
|
|
15
|
+
"This setting is the solution's wait for a file a chat turn carries; the tenant's attached_documents context-source limit (how much of the files reaches the model) is a separate setting.",
|
|
16
|
+
docs: ATTACHMENTS_DOCS,
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
code: ATTACHED_CLAMPED_CODE,
|
|
20
|
+
area: "package",
|
|
21
|
+
message: "A solution's settings.attached_documents.wait_seconds is outside the bounds the instance publishes; it waits at the nearest bound instead.",
|
|
22
|
+
hint: "Set wait_seconds within the bounds the finding names; `cavelon schema harnesses.settings` shows them.",
|
|
23
|
+
docs: ATTACHMENTS_DOCS,
|
|
24
|
+
},
|
|
25
|
+
];
|
|
26
|
+
const asObject = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
|
|
27
|
+
const propertiesOf = (schema, node) => {
|
|
28
|
+
for (const branch of branches(schema, node)) {
|
|
29
|
+
const properties = asObject(branch.properties);
|
|
30
|
+
if (properties)
|
|
31
|
+
return properties;
|
|
32
|
+
}
|
|
33
|
+
return undefined;
|
|
34
|
+
};
|
|
35
|
+
function described(schema) {
|
|
36
|
+
const items = branches(schema, schema.properties?.harnesses).map((b) => b.items).find((i) => i !== undefined);
|
|
37
|
+
const settings = propertiesOf(schema, items)?.settings;
|
|
38
|
+
const setting = settings === undefined ? undefined : propertiesOf(schema, settings)?.[SETTING];
|
|
39
|
+
const fields = setting === undefined ? undefined : propertiesOf(schema, setting);
|
|
40
|
+
if (!fields)
|
|
41
|
+
return undefined;
|
|
42
|
+
const seconds = branches(schema, fields[SECONDS]).find((b) => b.type === "integer" || b.type === "number");
|
|
43
|
+
return {
|
|
44
|
+
fields: new Set(Object.keys(fields)),
|
|
45
|
+
minimum: typeof seconds?.minimum === "number" ? seconds.minimum : undefined,
|
|
46
|
+
maximum: typeof seconds?.maximum === "number" ? seconds.maximum : undefined,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export function inAttachedDocuments(schema, pointer) {
|
|
50
|
+
const parts = pointer.split("/");
|
|
51
|
+
return parts[1] === "harnesses" && parts[3] === "settings" && parts[4] === SETTING && described(schema) !== undefined;
|
|
52
|
+
}
|
|
53
|
+
function secondsOf(value) {
|
|
54
|
+
if (typeof value === "number")
|
|
55
|
+
return Number.isFinite(value) ? value : undefined;
|
|
56
|
+
if (typeof value !== "string")
|
|
57
|
+
return undefined;
|
|
58
|
+
const text = value.trim();
|
|
59
|
+
if (!text || /[xob]/i.test(text))
|
|
60
|
+
return undefined;
|
|
61
|
+
const parsed = Number(text);
|
|
62
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
63
|
+
}
|
|
64
|
+
export function checkAttachedDocuments(disk, schema) {
|
|
65
|
+
const known = described(schema);
|
|
66
|
+
const harnesses = disk.package.harnesses;
|
|
67
|
+
if (!known || !Array.isArray(harnesses))
|
|
68
|
+
return [];
|
|
69
|
+
const findings = [];
|
|
70
|
+
harnesses.forEach((raw, i) => {
|
|
71
|
+
const harness = asObject(raw);
|
|
72
|
+
const settings = asObject(harness?.settings);
|
|
73
|
+
if (!settings || settings[SETTING] === undefined || settings[SETTING] === null)
|
|
74
|
+
return;
|
|
75
|
+
const name = typeof harness.slug === "string" ? ` "${harness.slug}"` : "";
|
|
76
|
+
const at = `/harnesses/${i}/settings/${SETTING}`;
|
|
77
|
+
const setting = asObject(settings[SETTING]);
|
|
78
|
+
if (!setting) {
|
|
79
|
+
findings.push({
|
|
80
|
+
code: ATTACHED_IGNORED_CODE,
|
|
81
|
+
severity: "warning",
|
|
82
|
+
...locate(disk, at),
|
|
83
|
+
message: `The solution${name} sets ${SETTING} to ${JSON.stringify(settings[SETTING])}, not an object: the instance ignores it, and a chat turn waits for its files as long as the platform default.`,
|
|
84
|
+
});
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const until = setting[UNTIL_READABLE];
|
|
88
|
+
if (known.fields.has(UNTIL_READABLE) && until !== undefined && until !== null && typeof until !== "boolean") {
|
|
89
|
+
findings.push({
|
|
90
|
+
code: ATTACHED_IGNORED_CODE,
|
|
91
|
+
severity: "warning",
|
|
92
|
+
...locate(disk, `${at}/${UNTIL_READABLE}`),
|
|
93
|
+
message: `${UNTIL_READABLE} is ${JSON.stringify(until)}, not true or false: only false turns the wait off, so a chat turn of the solution${name} still waits for its files.`,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
const given = setting[SECONDS];
|
|
97
|
+
if (!known.fields.has(SECONDS) || given === undefined || given === null)
|
|
98
|
+
return;
|
|
99
|
+
const seconds = typeof given === "boolean" ? undefined : secondsOf(given);
|
|
100
|
+
if (seconds === undefined) {
|
|
101
|
+
findings.push({
|
|
102
|
+
code: ATTACHED_IGNORED_CODE,
|
|
103
|
+
severity: "warning",
|
|
104
|
+
...locate(disk, `${at}/${SECONDS}`),
|
|
105
|
+
message: `${SECONDS} is ${JSON.stringify(given)}, not a number of seconds: the instance ignores it, and a chat turn of the solution${name} waits as long as the platform default.`,
|
|
106
|
+
});
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const bound = known.minimum !== undefined && seconds < known.minimum ? known.minimum : known.maximum !== undefined && seconds > known.maximum ? known.maximum : undefined;
|
|
110
|
+
if (bound === undefined)
|
|
111
|
+
return;
|
|
112
|
+
const range = `${known.minimum ?? "…"}–${known.maximum ?? "…"}`;
|
|
113
|
+
findings.push({
|
|
114
|
+
code: ATTACHED_CLAMPED_CODE,
|
|
115
|
+
severity: "warning",
|
|
116
|
+
...locate(disk, `${at}/${SECONDS}`),
|
|
117
|
+
message: `${SECONDS} is ${JSON.stringify(given)}, outside ${range}: a chat turn of the solution${name} waits ${bound} seconds instead.`,
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
return findings;
|
|
121
|
+
}
|
package/dist/commands/chat.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { promises as fs } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { boolOption, listOption, parseDuration, positional, stringOption } from "../command.js";
|
|
2
5
|
import { confirmation, confirmTokenRequired, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
|
|
3
6
|
import { named, readDefaultRoute } from "../default-route.js";
|
|
4
7
|
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
@@ -9,6 +12,8 @@ import { cavelonCommand, fill } from "../printed.js";
|
|
|
9
12
|
import { MCP_MAX_WAIT_MS } from "./async.js";
|
|
10
13
|
import { accessFor, activationStep, mayActivate } from "../access.js";
|
|
11
14
|
import { AS_CHAT_USER_OPTION, chatUserReader, chatUserReaderError } from "../chat-reader.js";
|
|
15
|
+
import { deref, jsonBodySchema } from "../openapi.js";
|
|
16
|
+
import { confinedPath } from "../paths.js";
|
|
12
17
|
function harnessRef(session, input) {
|
|
13
18
|
const option = stringOption(input, "harness");
|
|
14
19
|
if (option)
|
|
@@ -32,6 +37,123 @@ const HARNESS_OPTION = {
|
|
|
32
37
|
};
|
|
33
38
|
const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant and solution." };
|
|
34
39
|
const DEFAULT_CHAT_TIMEOUT = "2m";
|
|
40
|
+
const CHAT_ROUTE = "/api/v1/chat";
|
|
41
|
+
const CHAT_FILES_ROUTE = "/api/v1/chat/files";
|
|
42
|
+
const CONVERSATIONS_ROUTE = "/api/v1/conversations";
|
|
43
|
+
const LOOKUP_MS = 5_000;
|
|
44
|
+
const unavailable = (message, hint) => new CavelonError(ExitCode.failure, { code: "operation_unavailable", message, hint, details: { sent: false } });
|
|
45
|
+
async function bodyFields(ctx, method, route, what, multipart = false) {
|
|
46
|
+
const { doc, op } = await workflowOperation(ctx, method, route, what);
|
|
47
|
+
if (!doc)
|
|
48
|
+
return undefined;
|
|
49
|
+
const schema = multipart ? op.requestBody?.content?.["multipart/form-data"]?.schema : jsonBodySchema(op);
|
|
50
|
+
const body = schema ? deref(doc, schema) : undefined;
|
|
51
|
+
return body?.properties ?? {};
|
|
52
|
+
}
|
|
53
|
+
async function checkDraft(ctx, fields) {
|
|
54
|
+
if (fields && !fields.preview_draft) {
|
|
55
|
+
throw unavailable("This instance does not publish preview_draft on chat, so --draft cannot try a draft's settings. Nothing was sent.", `The instance may be older than this feature; \`${cavelonCommand("status")}\` shows its version. A solution that is still a draft answers a person's token as a Playground run without --draft.`);
|
|
56
|
+
}
|
|
57
|
+
const access = await accessFor(await ctx.client());
|
|
58
|
+
if (access?.kind === "api_key" || (await ctx.session()).tokenKind === "api_key") {
|
|
59
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
60
|
+
code: "forbidden",
|
|
61
|
+
message: "A tenant API key cannot chat with a solution's draft. Nothing was sent.",
|
|
62
|
+
hint: "Use a personal access token whose role holds playground.use, or leave out --draft to chat with the published version.",
|
|
63
|
+
details: { sent: false, credential: "api_key" },
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
if (access?.permissions && !access.permissions.includes("playground.use")) {
|
|
67
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
68
|
+
code: "permission_missing",
|
|
69
|
+
message: "Chatting with a draft needs playground.use, which this credential does not hold. Nothing was sent.",
|
|
70
|
+
hint: "A person whose role holds playground.use uses a token with it, or leave out --draft to chat with the published version.",
|
|
71
|
+
details: { sent: false, missing_permissions: ["playground.use"] },
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function uploadFiles(ctx, files, sessionId, chatFields, deadline) {
|
|
76
|
+
if (!files.length)
|
|
77
|
+
return [];
|
|
78
|
+
if (chatFields && !chatFields.file_ids) {
|
|
79
|
+
throw unavailable("This instance's chat takes no file_ids, so --file cannot attach a file. Nothing was sent.", `The instance may be older than this feature; \`${cavelonCommand("status")}\` shows its version.`);
|
|
80
|
+
}
|
|
81
|
+
const resolved = [];
|
|
82
|
+
for (const raw of files) {
|
|
83
|
+
const file = await confinedPath(ctx, raw, "The file");
|
|
84
|
+
const stat = await fs.stat(file).catch(() => undefined);
|
|
85
|
+
if (!stat?.isFile())
|
|
86
|
+
throw usageError(`${raw} is not a file. Nothing was sent.`, "Name a file to attach with --file <path>.");
|
|
87
|
+
resolved.push(file);
|
|
88
|
+
}
|
|
89
|
+
const form = await bodyFields(ctx, "POST", CHAT_FILES_ROUTE, "attaching a file to a chat message", true);
|
|
90
|
+
if (form && (!form.scope || !form.session_id)) {
|
|
91
|
+
throw unavailable("This instance's chat file upload publishes no conversation scope or session, so --file cannot attach a file to this turn. Nothing was sent.", `The instance may be older than this feature; \`${cavelonCommand("status")}\` shows its version.`);
|
|
92
|
+
}
|
|
93
|
+
const uploaded = [];
|
|
94
|
+
for (const file of resolved) {
|
|
95
|
+
const result = await callStable(ctx, "POST", CHAT_FILES_ROUTE, "attaching a file to a chat message", {
|
|
96
|
+
body: { scope: "conversation", session_id: sessionId },
|
|
97
|
+
files: [{ field: "file", path: file }],
|
|
98
|
+
timeoutMs: Math.max(1_000, deadline - Date.now()),
|
|
99
|
+
}).catch((error) => {
|
|
100
|
+
throw uploadsOff(error) ?? error;
|
|
101
|
+
});
|
|
102
|
+
uploaded.push({ file_id: result.file_id, filename: result.filename ?? path.basename(file), processing_status: result.processing_status });
|
|
103
|
+
}
|
|
104
|
+
return uploaded;
|
|
105
|
+
}
|
|
106
|
+
function uploadsOff(error) {
|
|
107
|
+
if (!(error instanceof CavelonError) || error.status !== 403 || !/not enabled for this tenant/i.test(error.message))
|
|
108
|
+
return undefined;
|
|
109
|
+
return new CavelonError(ExitCode.unauthorized, {
|
|
110
|
+
code: "chat_uploads_off",
|
|
111
|
+
message: `${error.message} The message was not sent.`,
|
|
112
|
+
hint: "Files in a chat are a tenant setting: someone who manages the tenant's uploads turns on document uploads and their Chat/Run Context scope in the Admin (Settings › Documents). Leave out --file to send the message without it.",
|
|
113
|
+
status: 403,
|
|
114
|
+
details: { sent: false },
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async function conversationOf(ctx, sessionId, harness) {
|
|
118
|
+
try {
|
|
119
|
+
const list = await callStable(ctx, "GET", CONVERSATIONS_ROUTE, "listing conversations", {
|
|
120
|
+
query: { ...(harness ? { harness_id: harness.id } : {}) },
|
|
121
|
+
timeoutMs: LOOKUP_MS,
|
|
122
|
+
});
|
|
123
|
+
return (Array.isArray(list) ? list : []).find((c) => c.session_id === sessionId)?.id;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function turnTimedOut(ctx, waitedMs, sessionId, harness) {
|
|
130
|
+
const conversationId = await conversationOf(ctx, sessionId, harness);
|
|
131
|
+
const read = conversationId
|
|
132
|
+
? `Read it, with the answer once it is there: \`${cavelonCommand("api", "get_conversation", "--param", `conversation_id=${conversationId}`)}\` (GET ${CONVERSATIONS_ROUTE}/{conversation_id}); \`${cavelonCommand("trace", conversationId, "--kind", "conversation")}\` shows its traces.`
|
|
133
|
+
: `Find its conversation by session_id ${sessionId} in \`${cavelonCommand("api", "list_conversations", ...(harness ? ["--param", `harness_id=${harness.id}`] : []))}\`, then read it with \`${cavelonCommand("api", "get_conversation", "--param", "conversation_id=<conversation_id>")}\` (GET ${CONVERSATIONS_ROUTE}/{conversation_id}).`;
|
|
134
|
+
return new CavelonError(ExitCode.timeout, {
|
|
135
|
+
code: "chat_turn_timeout",
|
|
136
|
+
message: `No answer within ${Math.round(waitedMs / 1000)} s. The turn goes on on the instance, which stores its answer; sending the message again would run it twice.`,
|
|
137
|
+
hint: `${read} Continue the conversation with \`${cavelonCommand("chat", fill("message"), "--session", sessionId)}\`; a longer --timeout waits for the next turn's answer.`,
|
|
138
|
+
details: { sent: true, session_id: sessionId, ...(conversationId ? { conversation_id: conversationId } : {}), ...(harness ? { harness_id: harness.id } : {}) },
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function statusLine(answer, who) {
|
|
142
|
+
if (!("status" in answer) || answer.status === undefined)
|
|
143
|
+
return undefined;
|
|
144
|
+
const status = answer.status;
|
|
145
|
+
if (status === null)
|
|
146
|
+
return `${who} did not complete the turn (status null): it failed or was refused. The instance says:`;
|
|
147
|
+
if (status === "completed")
|
|
148
|
+
return undefined;
|
|
149
|
+
if (status === "cancelled")
|
|
150
|
+
return `${who} did not answer: the turn was cancelled. The message is stored, without an answer.`;
|
|
151
|
+
if (status === "waiting")
|
|
152
|
+
return `${who} is waiting (status waiting): the turn has not finished; its answer so far:`;
|
|
153
|
+
if (status === "blocked")
|
|
154
|
+
return `${who} blocked the turn (status blocked):`;
|
|
155
|
+
return `${who} ended the turn with status ${status}:`;
|
|
156
|
+
}
|
|
35
157
|
function chatError(error, harness, may = null) {
|
|
36
158
|
if (!(error instanceof CavelonError) || error.status !== 409)
|
|
37
159
|
return error;
|
|
@@ -49,10 +171,20 @@ export const chat = {
|
|
|
49
171
|
"not the default, or a draft, can be tried before it answers anyone. A draft answers a person's token as a Playground run\n" +
|
|
50
172
|
"(counted as testing), never a tenant API key. Without --harness: the env file's or cavelon.yaml's solution, else the\n" +
|
|
51
173
|
"tenant's default route. Each call is one turn; --session continues a conversation. Not streamed: waits for the whole\n" +
|
|
52
|
-
`answer, at most --timeout (default ${DEFAULT_CHAT_TIMEOUT}; ${MCP_MAX_WAIT_MS / 1000} s as an MCP tool
|
|
174
|
+
`answer, at most --timeout (default ${DEFAULT_CHAT_TIMEOUT}; ${(MCP_MAX_WAIT_MS - LOOKUP_MS) / 1000} s as an MCP tool, which then looks up\n` +
|
|
175
|
+
`a turn not answered in time within its ${MCP_MAX_WAIT_MS / 1000} s).\n` +
|
|
53
176
|
"--as-chat-user reads knowledge and binds database query identity as that Chat User, with a personal access token.\n" +
|
|
54
177
|
"Choose an id with `cavelon api list_chat_users -p tenant_id=<tenant_id>`; email_verified says whether an email-bound\n" +
|
|
55
|
-
"query can bind that address. Without the option, keeps the usual reader
|
|
178
|
+
"query can bind that address. Without the option, keeps the usual reader.\n" +
|
|
179
|
+
"--file uploads a file to the turn's conversation first (POST /api/v1/chat/files) and names it in file_ids, so the\n" +
|
|
180
|
+
"solution's wait for a file still being read (settings.attached_documents) can be tried. A personal access token whose\n" +
|
|
181
|
+
"role holds playground.use chats as the Playground does: an active solution answers with its unpublished draft where\n" +
|
|
182
|
+
"one is pending, with or without --draft. --draft (preview_draft) says so explicitly and is refused before sending where\n" +
|
|
183
|
+
"the draft cannot be reached. A tenant API key, and a token without playground.use, chat with the published version.\n" +
|
|
184
|
+
"The first turn carries a session_id the kit chose. A turn that is not answered in time goes on on the instance, which\n" +
|
|
185
|
+
"stores its answer: the error says how to read the conversation; sending the message again would run it twice. A\n" +
|
|
186
|
+
"status the instance reports (cancelled, waiting, blocked) is shown. A cancelled turn, and one a recent instance reports\n" +
|
|
187
|
+
"with status null (failed or refused, such as by a limit), exits 1; an older instance sends no status for an answered turn.",
|
|
56
188
|
readOnly: false,
|
|
57
189
|
mcpEffect: "Starts or continues a conversation with the solution and runs its agents (model usage, its tools' actions); changes no configuration.",
|
|
58
190
|
mcpTool: "chat",
|
|
@@ -63,30 +195,49 @@ export const chat = {
|
|
|
63
195
|
env: ENV_OPTION,
|
|
64
196
|
session: { type: "string", value: "<session_id>", description: "Continue this conversation (the session_id a previous chat printed)." },
|
|
65
197
|
"as-chat-user": AS_CHAT_USER_OPTION,
|
|
198
|
+
file: { type: "string", multiple: true, value: "<path>", description: "Attach this file to the message (uploaded to the conversation first)." },
|
|
199
|
+
draft: { type: "boolean", description: "Answer with the active solution's draft, as the Playground does; refused where it cannot (needs playground.use)." },
|
|
66
200
|
timeout: { type: "string", value: "<duration>", description: `Wait at most this long for the answer (90s, 5m; default ${DEFAULT_CHAT_TIMEOUT}).` },
|
|
67
201
|
},
|
|
68
|
-
examples: [
|
|
202
|
+
examples: [
|
|
203
|
+
'cavelon chat "When are you open?" --harness support-faq',
|
|
204
|
+
'cavelon chat "And on Saturdays?" --session <session_id>',
|
|
205
|
+
'cavelon chat "What does this invoice say?" --file invoice.pdf --draft',
|
|
206
|
+
'cavelon chat "Hello" --json',
|
|
207
|
+
],
|
|
69
208
|
async run(ctx, input) {
|
|
70
209
|
const message = positional(input, "message");
|
|
71
210
|
if (!message.trim())
|
|
72
211
|
throw usageError("The message is empty.");
|
|
73
212
|
const raw = stringOption(input, "timeout");
|
|
74
|
-
const
|
|
213
|
+
const started = Date.now();
|
|
214
|
+
const timeout = Math.min(parseDuration(raw ?? DEFAULT_CHAT_TIMEOUT), ctx.mode === "mcp" ? MCP_MAX_WAIT_MS - LOOKUP_MS : Number.MAX_SAFE_INTEGER);
|
|
215
|
+
const deadline = started + timeout;
|
|
75
216
|
const session = await ctx.session();
|
|
76
|
-
const reader = await chatUserReader(ctx, input,
|
|
217
|
+
const reader = await chatUserReader(ctx, input, CHAT_ROUTE);
|
|
77
218
|
const { ref, source } = harnessRef(session, input);
|
|
78
219
|
const harness = ref ? await findHarness(ctx, ref, source, (slug) => cavelonCommand("chat", fill("message"), "--harness", slug)) : undefined;
|
|
79
|
-
const
|
|
220
|
+
const draft = boolOption(input, "draft");
|
|
221
|
+
const files = listOption(input, "file");
|
|
222
|
+
const chatFields = draft || files.length ? await bodyFields(ctx, "POST", CHAT_ROUTE, "chatting with a solution") : undefined;
|
|
223
|
+
if (draft)
|
|
224
|
+
await checkDraft(ctx, chatFields);
|
|
225
|
+
const sessionId = stringOption(input, "session") ?? randomUUID();
|
|
226
|
+
const attached = await uploadFiles(ctx, files, sessionId, chatFields, deadline);
|
|
227
|
+
const body = { message, stream: false, ...reader, session_id: sessionId };
|
|
80
228
|
if (harness)
|
|
81
229
|
body.harness_id = harness.id;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
230
|
+
if (attached.length)
|
|
231
|
+
body.file_ids = attached.map((f) => f.file_id);
|
|
232
|
+
if (draft)
|
|
233
|
+
body.preview_draft = true;
|
|
85
234
|
let answer;
|
|
86
235
|
try {
|
|
87
|
-
answer = await callStable(ctx, "POST",
|
|
236
|
+
answer = await callStable(ctx, "POST", CHAT_ROUTE, "chatting with a solution", { body, timeoutMs: Math.max(1_000, deadline - Date.now()) });
|
|
88
237
|
}
|
|
89
238
|
catch (error) {
|
|
239
|
+
if (error instanceof CavelonError && error.code === "request_timeout")
|
|
240
|
+
throw await turnTimedOut(ctx, Date.now() - started, sessionId, harness);
|
|
90
241
|
throw chatUserReaderError(chatError(error, harness, error instanceof CavelonError && error.status === 409 ? mayActivate(await accessFor(await ctx.client())) : null), reader);
|
|
91
242
|
}
|
|
92
243
|
const target = harness ? { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } : null;
|
|
@@ -99,16 +250,23 @@ export const chat = {
|
|
|
99
250
|
const who = harness ? named(harness) : "The default route";
|
|
100
251
|
const directives = answer.ui_directives?.length ? `\n(${answer.ui_directives.length} UI directive${answer.ui_directives.length === 1 ? "" : "s"}, such as a form; --json shows them)` : "";
|
|
101
252
|
const limit = answer.limit_error ? `\nlimit: ${clip(JSON.stringify(answer.limit_error), 300)}` : "";
|
|
253
|
+
const ended = statusLine(answer, who);
|
|
254
|
+
const cancelled = answer.status === "cancelled";
|
|
255
|
+
const incomplete = "status" in answer && answer.status === null;
|
|
256
|
+
const said = cancelled ? (answer.response ? [answer.response] : []) : [`${answer.response || (incomplete ? "(no message)" : "(no text)")}${directives}${limit}`];
|
|
102
257
|
return {
|
|
103
|
-
data: { harness: target, ...answer, ...reader, next },
|
|
258
|
+
data: { harness: target, ...answer, ...reader, ...(attached.length ? { files: attached } : {}), ...(draft ? { draft: true } : {}), next },
|
|
104
259
|
text: [
|
|
105
260
|
...(reader ? [`Reading as Chat User ${reader.reader_chat_user_id}.`] : []),
|
|
106
|
-
|
|
107
|
-
|
|
261
|
+
...attached.map((f) => `Attached ${f.filename} (${f.file_id}${f.processing_status ? `, ${f.processing_status}` : ""}).`),
|
|
262
|
+
...(draft ? ["Answered with the draft (preview_draft), as the Playground does."] : []),
|
|
263
|
+
ended ?? `${who} answered:`,
|
|
264
|
+
...said,
|
|
108
265
|
"",
|
|
109
266
|
`session: ${answer.session_id} continue with: ${next.continue}`,
|
|
110
267
|
`conversation_id: ${answer.conversation_id} its traces: ${next.trace}`,
|
|
111
268
|
].join("\n"),
|
|
269
|
+
...(cancelled || incomplete ? { exitCode: ExitCode.failure } : {}),
|
|
112
270
|
};
|
|
113
271
|
},
|
|
114
272
|
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { boolOption, stringOption } from "../command.js";
|
|
2
|
+
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
3
|
+
import { clip, keyValues } from "../format.js";
|
|
4
|
+
import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
|
|
5
|
+
import { callStable, workflowOperation } from "../invoke.js";
|
|
6
|
+
import { packageToSend } from "../managed-fields.js";
|
|
7
|
+
import { readPackage } from "../package-files.js";
|
|
8
|
+
import { PERSONA_SECTION } from "../package-format.js";
|
|
9
|
+
import { cavelonCommand } from "../printed.js";
|
|
10
|
+
import { ruleFields } from "../engagement.js";
|
|
11
|
+
import { schemaFor } from "./solution.js";
|
|
12
|
+
const PREVIEW_ROUTE = "/api/v1/bot-persona/engagement/preview";
|
|
13
|
+
const WIDGET_DOCS = "/docs/channels/widget";
|
|
14
|
+
function harnessRef(session, input) {
|
|
15
|
+
const option = stringOption(input, "harness");
|
|
16
|
+
if (option)
|
|
17
|
+
return { ref: option, source: "option" };
|
|
18
|
+
if (session.envFile?.harness)
|
|
19
|
+
return { ref: session.envFile.harness, source: `env/${session.envFile.name}.yaml` };
|
|
20
|
+
if (session.project?.harness)
|
|
21
|
+
return { ref: session.project.harness, source: "cavelon.yaml" };
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
export function pageOf(value) {
|
|
25
|
+
const given = value?.trim();
|
|
26
|
+
if (!given)
|
|
27
|
+
return { page_path: "/" };
|
|
28
|
+
if (given.startsWith("/"))
|
|
29
|
+
return { page_path: given.split(/[?#]/)[0] || "/" };
|
|
30
|
+
let url;
|
|
31
|
+
try {
|
|
32
|
+
url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(given) ? given : `https://${given}`);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw usageError(`--page must be a page's URL or path, got "${given}".`, "For example --page https://www.example.at/tarife/winter or --page /tarife/winter.");
|
|
36
|
+
}
|
|
37
|
+
return { page_host: url.hostname, page_path: url.pathname || "/" };
|
|
38
|
+
}
|
|
39
|
+
function momentOf(value) {
|
|
40
|
+
const given = value?.trim();
|
|
41
|
+
if (!given)
|
|
42
|
+
return undefined;
|
|
43
|
+
if (Number.isNaN(Date.parse(given)))
|
|
44
|
+
throw usageError(`--at must be a date and time, got "${given}".`, "For example --at 2026-12-14T09:00:00+01:00.");
|
|
45
|
+
return given;
|
|
46
|
+
}
|
|
47
|
+
async function folderRules(ctx, session, harnessId) {
|
|
48
|
+
const project = session.project;
|
|
49
|
+
if (!project)
|
|
50
|
+
return { source: "the solution (no solution folder here)" };
|
|
51
|
+
const disk = await readPackage(project.root, project.layout);
|
|
52
|
+
const unreadable = disk.findings.find((f) => f.severity === "error" && f.file?.includes(PERSONA_SECTION));
|
|
53
|
+
if (unreadable)
|
|
54
|
+
throw new CavelonError(ExitCode.validation, { code: unreadable.code, message: `${unreadable.file}: ${unreadable.message}` });
|
|
55
|
+
const { schema } = await schemaFor(ctx, project.packageVersion, false);
|
|
56
|
+
const sent = packageToSend(disk.package, project.managed, schema);
|
|
57
|
+
const persona = sent.package[PERSONA_SECTION];
|
|
58
|
+
const field = ruleFields(schema)[0];
|
|
59
|
+
const list = field ? persona?.[field.field] : undefined;
|
|
60
|
+
if (!field || !Array.isArray(list))
|
|
61
|
+
return { source: `the solution (the folder's ${PERSONA_SECTION} sets no engagement rules)` };
|
|
62
|
+
const kinds = persona?.[`${field.field}_kinds`];
|
|
63
|
+
if (!Array.isArray(kinds))
|
|
64
|
+
return { rules: list, source: "the solution folder" };
|
|
65
|
+
const held = await callStable(ctx, "GET", "/api/v1/bot-persona", "reading the persona", { query: { harness_id: harnessId } });
|
|
66
|
+
const others = (Array.isArray(held?.[field.field]) ? held[field.field] : []).filter((rule) => {
|
|
67
|
+
const kind = rule && typeof rule === "object" ? rule[field.discriminator] : undefined;
|
|
68
|
+
return !kinds.includes(kind);
|
|
69
|
+
});
|
|
70
|
+
return { rules: [...others, ...list], source: `the solution folder (${kinds.join(", ")}) and the solution's other kinds` };
|
|
71
|
+
}
|
|
72
|
+
function previewText(page, at, source, p) {
|
|
73
|
+
const e = p.engagement ?? {};
|
|
74
|
+
const calendar = e.calendar;
|
|
75
|
+
const doors = calendar?.doors ?? [];
|
|
76
|
+
return keyValues([
|
|
77
|
+
["page", `${page.page_host ?? "(any host)"}${page.page_path}`],
|
|
78
|
+
["at", at ?? `now${e.server_now ? ` (${e.server_now})` : ""}`],
|
|
79
|
+
["rules", source],
|
|
80
|
+
[
|
|
81
|
+
"starters",
|
|
82
|
+
p.teaser_messages?.length
|
|
83
|
+
? `${e.starters_rule_id ? `rule ${e.starters_rule_id}` : "the persona's teasers"}${p.teaser_messages.map((t) => `\n - ${clip(t, 120)}`).join("")}`
|
|
84
|
+
: "none",
|
|
85
|
+
],
|
|
86
|
+
[
|
|
87
|
+
"calendar",
|
|
88
|
+
calendar
|
|
89
|
+
? `${calendar.rule_id} "${clip(calendar.title ?? "", 60)}": ${doors.length} open door${doors.length === 1 ? "" : "s"}` +
|
|
90
|
+
(calendar.today ? `, today door ${calendar.today}` : "") +
|
|
91
|
+
(calendar.next_unlock_at ? `, next opens ${calendar.next_unlock_at}` : "") +
|
|
92
|
+
doors.slice(-5).map((d) => `\n - door ${d.day}${d.title ? ` "${clip(d.title, 60)}"` : ""}${d.question ? ` asks: ${clip(d.question, 80)}` : ""}`).join("")
|
|
93
|
+
: "none",
|
|
94
|
+
],
|
|
95
|
+
["banners", e.banners?.length ? e.banners.map((b) => `\n - ${b.rule_id}${typeof b.display?.trigger === "string" ? ` (${b.display.trigger})` : ""}`).join("") : "none"],
|
|
96
|
+
[
|
|
97
|
+
"decoration",
|
|
98
|
+
e.decoration
|
|
99
|
+
? `${e.decoration.rule_id}: ${[e.decoration.effect, e.decoration.accessory, e.decoration.badge_emoji].filter((v) => v && v !== "none").join(", ")}${e.decoration.places?.length ? ` on ${e.decoration.places.join(", ")}` : ""}`
|
|
100
|
+
: "none",
|
|
101
|
+
],
|
|
102
|
+
]);
|
|
103
|
+
}
|
|
104
|
+
export const engagementPreview = {
|
|
105
|
+
name: "engagement preview",
|
|
106
|
+
summary: "Show what a visitor gets on a page at a moment: starters, open doors, banners, decoration. Stores and counts nothing.",
|
|
107
|
+
description: "Sends the solution folder's engagement rules (persona.engagement_rules) to the instance's preview for one page and one moment,\n" +
|
|
108
|
+
"and shows what the widget would offer there: the starter questions, the door calendar's open doors, the banners and the\n" +
|
|
109
|
+
"decoration. The instance matches the rules on its clock as it does for a visitor and checks them as a save would; nothing\n" +
|
|
110
|
+
"is stored, translated or counted. With managed_kinds in cavelon.yaml, the solution's rules of the other kinds join the folder's,\n" +
|
|
111
|
+
"as an import keeps them. Without a solution folder, or with --stored, the rules the solution holds are previewed.\n" +
|
|
112
|
+
"The instance must mark the preview read-only (x-cavelon-read-only); an older one is refused before anything is sent.",
|
|
113
|
+
readOnly: true,
|
|
114
|
+
idempotent: true,
|
|
115
|
+
mcpTool: "engagement_preview",
|
|
116
|
+
options: {
|
|
117
|
+
harness: { type: "string", value: "<harness>", description: "The solution: its name, slug or id; default: env file, then cavelon.yaml." },
|
|
118
|
+
env: { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant and solution." },
|
|
119
|
+
page: { type: "string", value: "<url|path>", description: "The page: its URL (https://www.example.at/tarife/winter) or a path (/tarife/winter); default /, on any host." },
|
|
120
|
+
at: { type: "string", value: "<time>", description: "The moment, as ISO 8601 with an offset (2026-12-14T09:00:00+01:00); without one, UTC. Default: now." },
|
|
121
|
+
stored: { type: "boolean", description: "Preview the rules the solution holds on the instance, not the folder's." },
|
|
122
|
+
},
|
|
123
|
+
examples: [
|
|
124
|
+
"cavelon engagement preview --page https://www.example.at/tarife/winter --at 2026-12-14T09:00:00+01:00",
|
|
125
|
+
"cavelon engagement preview --page /kontakt --stored --json",
|
|
126
|
+
],
|
|
127
|
+
async run(ctx, input) {
|
|
128
|
+
const session = await ctx.session();
|
|
129
|
+
const page = pageOf(stringOption(input, "page"));
|
|
130
|
+
const at = momentOf(stringOption(input, "at"));
|
|
131
|
+
const { ref, source } = harnessRef(session, input);
|
|
132
|
+
if (!ref)
|
|
133
|
+
throw usageError("Name the solution: --harness <name or slug>, or work in its folder (cavelon.yaml names it).");
|
|
134
|
+
const { harness, candidates } = await lookupHarness(ctx, ref);
|
|
135
|
+
if (!harness)
|
|
136
|
+
throw harnessNotFoundError(ref, candidates, source === "option" ? undefined : source);
|
|
137
|
+
const { doc, op } = await workflowOperation(ctx, "POST", PREVIEW_ROUTE, "previewing engagement rules");
|
|
138
|
+
if (doc && !op.readOnly) {
|
|
139
|
+
throw new CavelonError(ExitCode.failure, {
|
|
140
|
+
code: "operation_unavailable",
|
|
141
|
+
message: `This instance does not mark POST ${PREVIEW_ROUTE} read-only, so the kit does not send it as a read.`,
|
|
142
|
+
hint: `Preview the rules in the Admin (Persona and Engagement pages); a newer instance marks the route read-only. \`${cavelonCommand("status")}\` shows its version.`,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
const chosen = boolOption(input, "stored") ? { source: "the solution (--stored)" } : await folderRules(ctx, session, harness.id);
|
|
146
|
+
const body = { ...(chosen.rules ? { rules: chosen.rules } : {}), ...page, ...(at ? { at } : {}) };
|
|
147
|
+
const result = await callStable(ctx, "POST", PREVIEW_ROUTE, "previewing engagement rules", { query: { harness_id: harness.id }, body });
|
|
148
|
+
return {
|
|
149
|
+
data: { harness: { id: harness.id, slug: harness.slug }, page, at: at ?? null, rules_from: chosen.source, ...result, docs: WIDGET_DOCS },
|
|
150
|
+
text: previewText(page, at, chosen.source, result),
|
|
151
|
+
};
|
|
152
|
+
},
|
|
153
|
+
};
|
package/dist/commands/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { limitsSet } from "./limits-set.js";
|
|
|
12
12
|
import { modelsList, modelsSetLimit } from "./models.js";
|
|
13
13
|
import { activate, apply, explain, pull, validate } from "./solution.js";
|
|
14
14
|
import { schema } from "./schema.js";
|
|
15
|
+
import { engagementPreview } from "./engagement.js";
|
|
15
16
|
import { publication, publish, discardDraft, rollback } from "./publication.js";
|
|
16
17
|
import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
|
|
17
18
|
import { kbUpload, testRun, trace } from "./work.js";
|
|
@@ -97,6 +98,7 @@ export const COMMANDS = [
|
|
|
97
98
|
schema,
|
|
98
99
|
apply,
|
|
99
100
|
explain,
|
|
101
|
+
engagementPreview,
|
|
100
102
|
variablesList,
|
|
101
103
|
variablesGet,
|
|
102
104
|
variablesSet,
|
package/dist/commands/init.js
CHANGED
|
@@ -26,7 +26,7 @@ import { harnessNotFoundError, listHarnesses, lookupHarness, SLUG, slugFromName
|
|
|
26
26
|
import { isUuid, lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
|
|
27
27
|
import { cavelonCommand, fill, folderCommand } from "../printed.js";
|
|
28
28
|
import { chooseTenant, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
|
|
29
|
-
import { createHarness } from "./tenants.js";
|
|
29
|
+
import { createHarness, NEW_HARNESS_AUTHORING_HINT } from "./tenants.js";
|
|
30
30
|
import { schemaFor, setProjectKey } from "./solution.js";
|
|
31
31
|
const HOOK_LINES = (prefix) => [
|
|
32
32
|
"# Check the Cavelon package before each commit (`cavelon init --hook`).",
|
|
@@ -704,7 +704,7 @@ async function runInit(ctx, input) {
|
|
|
704
704
|
else if (!(await hasPackageFiles(root, project.layout.package))) {
|
|
705
705
|
const choices = chosenHarness?.choices ?? [];
|
|
706
706
|
if (chosenHarness?.created || chosenHarness?.missing) {
|
|
707
|
-
next.unshift(`Bring the draft into package/ (its manifest): ${folderCommand("pull")}`, `Write the package files in package/, then: ${folderCommand("validate")}`, `Preview it on the instance: ${folderCommand("apply", "--env", "test")}`);
|
|
707
|
+
next.unshift(`Bring the draft into package/ (its manifest): ${folderCommand("pull")}`, `Write the package files in package/, then: ${folderCommand("validate")}`, NEW_HARNESS_AUTHORING_HINT, `Preview it on the instance: ${folderCommand("apply", "--env", "test")}`);
|
|
708
708
|
}
|
|
709
709
|
else if (harness)
|
|
710
710
|
next.unshift(`Bring the solution into package/: ${folderCommand("pull")}`);
|
|
@@ -200,10 +200,11 @@ function changeCommand(action) {
|
|
|
200
200
|
export const publish = changeCommand("publish");
|
|
201
201
|
export const discardDraft = changeCommand("discard-draft");
|
|
202
202
|
export const rollback = changeCommand("rollback");
|
|
203
|
-
export function publicationNotice(value) {
|
|
203
|
+
export function publicationNotice(value, live = []) {
|
|
204
204
|
const p = value;
|
|
205
|
+
const except = live.length ? ` Except ${live.join(", ")}: persona widget fields reach visitors at once, without a publication.` : "";
|
|
205
206
|
if (p?.target === "draft")
|
|
206
|
-
return `Unpublished draft; live traffic stays on published v${typeof p.published_version === "number" ? p.published_version : "?"}
|
|
207
|
+
return `Unpublished draft; live traffic stays on published v${typeof p.published_version === "number" ? p.published_version : "?"}.${except} Review ${cavelonCommand("publish")} before putting ${live.length ? "the other" : "these"} edits live. Tenant-wide resources retain their existing behavior.`;
|
|
207
208
|
if (p?.target === "published")
|
|
208
209
|
return "Editable solution configuration; activation/publication follows the instance's lifecycle.";
|
|
209
210
|
return undefined;
|