@cavelon/cli 0.2.11 → 0.2.13

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.
@@ -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
+ }
@@ -1,4 +1,7 @@
1
- import { parseDuration, positional, stringOption } from "../command.js";
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, schemaErrors } 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,140 @@ 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 bodySchema(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 { doc, fields: body?.properties ?? {} };
52
+ }
53
+ async function bodyFields(ctx, method, route, what, multipart = false) {
54
+ return (await bodySchema(ctx, method, route, what, multipart))?.fields;
55
+ }
56
+ function takesApiSource(body) {
57
+ if (!body)
58
+ return true;
59
+ const field = body.fields.source;
60
+ if (!field || typeof field !== "object")
61
+ return false;
62
+ return schemaErrors(body.doc, field, "api").length === 0;
63
+ }
64
+ async function answeringStatus(ctx, harness) {
65
+ if (harness)
66
+ return harness.status;
67
+ const route = await readDefaultRoute(ctx).catch(() => undefined);
68
+ return route?.current?.status;
69
+ }
70
+ async function checkDraft(ctx, fields) {
71
+ if (fields && !fields.preview_draft) {
72
+ 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.`);
73
+ }
74
+ const access = await accessFor(await ctx.client());
75
+ if (access?.kind === "api_key" || (await ctx.session()).tokenKind === "api_key") {
76
+ throw new CavelonError(ExitCode.unauthorized, {
77
+ code: "forbidden",
78
+ message: "A tenant API key cannot chat with a solution's draft. Nothing was sent.",
79
+ hint: "Use a personal access token whose role holds playground.use, or leave out --draft to chat with the published version.",
80
+ details: { sent: false, credential: "api_key" },
81
+ });
82
+ }
83
+ if (access?.permissions && !access.permissions.includes("playground.use")) {
84
+ throw new CavelonError(ExitCode.unauthorized, {
85
+ code: "permission_missing",
86
+ message: "Chatting with a draft needs playground.use, which this credential does not hold. Nothing was sent.",
87
+ hint: "A person whose role holds playground.use uses a token with it, or leave out --draft to chat with the published version.",
88
+ details: { sent: false, missing_permissions: ["playground.use"] },
89
+ });
90
+ }
91
+ }
92
+ async function uploadFiles(ctx, files, sessionId, chatFields, deadline) {
93
+ if (!files.length)
94
+ return [];
95
+ if (chatFields && !chatFields.file_ids) {
96
+ 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.`);
97
+ }
98
+ const resolved = [];
99
+ for (const raw of files) {
100
+ const file = await confinedPath(ctx, raw, "The file");
101
+ const stat = await fs.stat(file).catch(() => undefined);
102
+ if (!stat?.isFile())
103
+ throw usageError(`${raw} is not a file. Nothing was sent.`, "Name a file to attach with --file <path>.");
104
+ resolved.push(file);
105
+ }
106
+ const form = await bodyFields(ctx, "POST", CHAT_FILES_ROUTE, "attaching a file to a chat message", true);
107
+ if (form && (!form.scope || !form.session_id)) {
108
+ 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.`);
109
+ }
110
+ const uploaded = [];
111
+ for (const file of resolved) {
112
+ const result = await callStable(ctx, "POST", CHAT_FILES_ROUTE, "attaching a file to a chat message", {
113
+ body: { scope: "conversation", session_id: sessionId },
114
+ files: [{ field: "file", path: file }],
115
+ timeoutMs: Math.max(1_000, deadline - Date.now()),
116
+ }).catch((error) => {
117
+ throw uploadsOff(error) ?? error;
118
+ });
119
+ uploaded.push({ file_id: result.file_id, filename: result.filename ?? path.basename(file), processing_status: result.processing_status });
120
+ }
121
+ return uploaded;
122
+ }
123
+ function uploadsOff(error) {
124
+ if (!(error instanceof CavelonError) || error.status !== 403 || !/not enabled for this tenant/i.test(error.message))
125
+ return undefined;
126
+ return new CavelonError(ExitCode.unauthorized, {
127
+ code: "chat_uploads_off",
128
+ message: `${error.message} The message was not sent.`,
129
+ 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.",
130
+ status: 403,
131
+ details: { sent: false },
132
+ });
133
+ }
134
+ async function conversationOf(ctx, sessionId, harness) {
135
+ try {
136
+ const list = await callStable(ctx, "GET", CONVERSATIONS_ROUTE, "listing conversations", {
137
+ query: { ...(harness ? { harness_id: harness.id } : {}) },
138
+ timeoutMs: LOOKUP_MS,
139
+ });
140
+ return (Array.isArray(list) ? list : []).find((c) => c.session_id === sessionId)?.id;
141
+ }
142
+ catch {
143
+ return undefined;
144
+ }
145
+ }
146
+ async function turnTimedOut(ctx, waitedMs, sessionId, harness) {
147
+ const conversationId = await conversationOf(ctx, sessionId, harness);
148
+ const read = conversationId
149
+ ? `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.`
150
+ : `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}).`;
151
+ return new CavelonError(ExitCode.timeout, {
152
+ code: "chat_turn_timeout",
153
+ 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.`,
154
+ hint: `${read} Continue the conversation with \`${cavelonCommand("chat", fill("message"), "--session", sessionId)}\`; a longer --timeout waits for the next turn's answer.`,
155
+ details: { sent: true, session_id: sessionId, ...(conversationId ? { conversation_id: conversationId } : {}), ...(harness ? { harness_id: harness.id } : {}) },
156
+ });
157
+ }
158
+ function statusLine(answer, who) {
159
+ if (!("status" in answer) || answer.status === undefined)
160
+ return undefined;
161
+ const status = answer.status;
162
+ if (status === null)
163
+ return `${who} did not complete the turn (status null): it failed or was refused. The instance says:`;
164
+ if (status === "completed")
165
+ return undefined;
166
+ if (status === "cancelled")
167
+ return `${who} did not answer: the turn was cancelled. The message is stored, without an answer.`;
168
+ if (status === "waiting")
169
+ return `${who} is waiting (status waiting): the turn has not finished; its answer so far:`;
170
+ if (status === "blocked")
171
+ return `${who} blocked the turn (status blocked):`;
172
+ return `${who} ended the turn with status ${status}:`;
173
+ }
35
174
  function chatError(error, harness, may = null) {
36
175
  if (!(error instanceof CavelonError) || error.status !== 409)
37
176
  return error;
@@ -49,10 +188,23 @@ export const chat = {
49
188
  "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
189
  "(counted as testing), never a tenant API key. Without --harness: the env file's or cavelon.yaml's solution, else the\n" +
51
190
  "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).\n` +
191
+ `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` +
192
+ `a turn not answered in time within its ${MCP_MAX_WAIT_MS / 1000} s).\n` +
53
193
  "--as-chat-user reads knowledge and binds database query identity as that Chat User, with a personal access token.\n" +
54
194
  "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.",
195
+ "query can bind that address. Without the option, keeps the usual reader.\n" +
196
+ "--file uploads a file to the turn's conversation first (POST /api/v1/chat/files) and names it in file_ids, so the\n" +
197
+ "solution's wait for a file still being read (settings.attached_documents) can be tried. An active solution answers\n" +
198
+ "with its published version, as visitors get it: the kit sends source api, so the turn counts as API traffic (the\n" +
199
+ "tenant's API limits and processing-step cap apply), with a personal access token too. --draft (preview_draft) answers\n" +
200
+ "with the active solution's pending draft as a Playground run instead (counted as testing; needs playground.use, never\n" +
201
+ "a tenant API key) and is refused before sending where the draft cannot be reached. A solution that is not active has no\n" +
202
+ "published version and answers a person's token as a Playground run. An instance that does not publish source on chat\n" +
203
+ "takes a person's chat as a Playground run, which answers with a pending draft; the kit warns about that.\n" +
204
+ "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" +
205
+ "stores its answer: the error says how to read the conversation; sending the message again would run it twice. A\n" +
206
+ "status the instance reports (cancelled, waiting, blocked) is shown. A cancelled turn, and one a recent instance reports\n" +
207
+ "with status null (failed or refused, such as by a limit), exits 1; an older instance sends no status for an answered turn.",
56
208
  readOnly: false,
57
209
  mcpEffect: "Starts or continues a conversation with the solution and runs its agents (model usage, its tools' actions); changes no configuration.",
58
210
  mcpTool: "chat",
@@ -63,30 +215,58 @@ export const chat = {
63
215
  env: ENV_OPTION,
64
216
  session: { type: "string", value: "<session_id>", description: "Continue this conversation (the session_id a previous chat printed)." },
65
217
  "as-chat-user": AS_CHAT_USER_OPTION,
218
+ file: { type: "string", multiple: true, value: "<path>", description: "Attach this file to the message (uploaded to the conversation first)." },
219
+ draft: { type: "boolean", description: "Answer with the active solution's pending draft as a Playground run, not the published version; needs playground.use." },
66
220
  timeout: { type: "string", value: "<duration>", description: `Wait at most this long for the answer (90s, 5m; default ${DEFAULT_CHAT_TIMEOUT}).` },
67
221
  },
68
- examples: ['cavelon chat "When are you open?" --harness support-faq', 'cavelon chat "And on Saturdays?" --session <session_id>', 'cavelon chat "Hello" --json'],
222
+ examples: [
223
+ 'cavelon chat "When are you open?" --harness support-faq',
224
+ 'cavelon chat "And on Saturdays?" --session <session_id>',
225
+ 'cavelon chat "What does this invoice say?" --file invoice.pdf --draft',
226
+ 'cavelon chat "Hello" --json',
227
+ ],
69
228
  async run(ctx, input) {
70
229
  const message = positional(input, "message");
71
230
  if (!message.trim())
72
231
  throw usageError("The message is empty.");
73
232
  const raw = stringOption(input, "timeout");
74
- const timeout = Math.min(parseDuration(raw ?? DEFAULT_CHAT_TIMEOUT), ctx.mode === "mcp" ? MCP_MAX_WAIT_MS : Number.MAX_SAFE_INTEGER);
233
+ const started = Date.now();
234
+ const timeout = Math.min(parseDuration(raw ?? DEFAULT_CHAT_TIMEOUT), ctx.mode === "mcp" ? MCP_MAX_WAIT_MS - LOOKUP_MS : Number.MAX_SAFE_INTEGER);
235
+ const deadline = started + timeout;
75
236
  const session = await ctx.session();
76
- const reader = await chatUserReader(ctx, input, "/api/v1/chat");
237
+ const reader = await chatUserReader(ctx, input, CHAT_ROUTE);
77
238
  const { ref, source } = harnessRef(session, input);
78
239
  const harness = ref ? await findHarness(ctx, ref, source, (slug) => cavelonCommand("chat", fill("message"), "--harness", slug)) : undefined;
79
- const body = { message, stream: false, ...reader };
240
+ const draft = boolOption(input, "draft");
241
+ const files = listOption(input, "file");
242
+ const chatBody = await bodySchema(ctx, "POST", CHAT_ROUTE, "chatting with a solution");
243
+ const chatFields = chatBody?.fields;
244
+ if (draft)
245
+ await checkDraft(ctx, chatFields);
246
+ const status = draft ? undefined : await answeringStatus(ctx, harness);
247
+ const published = !draft && (status === undefined || status === "active");
248
+ const apiSource = published && takesApiSource(chatBody);
249
+ if (published && !apiSource && session.tokenKind !== "api_key" && (await accessFor(await ctx.client()))?.kind !== "api_key") {
250
+ ctx.warn("This instance does not publish source on chat, so it takes a personal access token's chat as a Playground run: an active solution answers with its pending draft where there is one. A tenant API key chats with the published version.");
251
+ }
252
+ const sessionId = stringOption(input, "session") ?? randomUUID();
253
+ const attached = await uploadFiles(ctx, files, sessionId, chatFields, deadline);
254
+ const body = { message, stream: false, ...reader, session_id: sessionId };
80
255
  if (harness)
81
256
  body.harness_id = harness.id;
82
- const sessionId = stringOption(input, "session");
83
- if (sessionId)
84
- body.session_id = sessionId;
257
+ if (attached.length)
258
+ body.file_ids = attached.map((f) => f.file_id);
259
+ if (draft)
260
+ body.preview_draft = true;
261
+ if (apiSource)
262
+ body.source = "api";
85
263
  let answer;
86
264
  try {
87
- answer = await callStable(ctx, "POST", "/api/v1/chat", "chatting with a solution", { body, timeoutMs: timeout });
265
+ answer = await callStable(ctx, "POST", CHAT_ROUTE, "chatting with a solution", { body, timeoutMs: Math.max(1_000, deadline - Date.now()) });
88
266
  }
89
267
  catch (error) {
268
+ if (error instanceof CavelonError && error.code === "request_timeout")
269
+ throw await turnTimedOut(ctx, Date.now() - started, sessionId, harness);
90
270
  throw chatUserReaderError(chatError(error, harness, error instanceof CavelonError && error.status === 409 ? mayActivate(await accessFor(await ctx.client())) : null), reader);
91
271
  }
92
272
  const target = harness ? { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } : null;
@@ -99,16 +279,23 @@ export const chat = {
99
279
  const who = harness ? named(harness) : "The default route";
100
280
  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
281
  const limit = answer.limit_error ? `\nlimit: ${clip(JSON.stringify(answer.limit_error), 300)}` : "";
282
+ const ended = statusLine(answer, who);
283
+ const cancelled = answer.status === "cancelled";
284
+ const incomplete = "status" in answer && answer.status === null;
285
+ const said = cancelled ? (answer.response ? [answer.response] : []) : [`${answer.response || (incomplete ? "(no message)" : "(no text)")}${directives}${limit}`];
102
286
  return {
103
- data: { harness: target, ...answer, ...reader, next },
287
+ data: { harness: target, ...answer, ...reader, ...(attached.length ? { files: attached } : {}), ...(draft ? { draft: true } : {}), ...(apiSource ? { source: "api" } : {}), next },
104
288
  text: [
105
289
  ...(reader ? [`Reading as Chat User ${reader.reader_chat_user_id}.`] : []),
106
- `${who} answered:`,
107
- `${answer.response || "(no text)"}${directives}${limit}`,
290
+ ...attached.map((f) => `Attached ${f.filename} (${f.file_id}${f.processing_status ? `, ${f.processing_status}` : ""}).`),
291
+ ...(draft ? ["Answered with the draft (preview_draft), as the Playground does."] : []),
292
+ ended ?? `${who} answered:`,
293
+ ...said,
108
294
  "",
109
295
  `session: ${answer.session_id} continue with: ${next.continue}`,
110
296
  `conversation_id: ${answer.conversation_id} its traces: ${next.trace}`,
111
297
  ].join("\n"),
298
+ ...(cancelled || incomplete ? { exitCode: ExitCode.failure } : {}),
112
299
  };
113
300
  },
114
301
  };
@@ -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
+ };
@@ -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,
@@ -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 : "?"}. Review ${cavelonCommand("publish")} before putting these edits live. Tenant-wide resources retain their existing behavior.`;
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;