@vatio-ai/cli 0.125.0 → 0.126.0

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 CHANGED
@@ -36,12 +36,15 @@ is the same thing without installing anything.
36
36
  ## If you are a coding agent
37
37
 
38
38
  ```bash
39
- vatio docs --save # the whole developer contract as markdown, live from Vatio
39
+ vatio docs --save # the whole developer contract as markdown, live from Vatio
40
+ vatio docs tools # one page of it
41
+ vatio docs search TERM # the sections that mention TERM, with their page
40
42
  ```
41
43
 
42
44
  `vatio docs` prints the same contract that
43
45
  [vatio.ai/docs/docs.md](https://vatio.ai/docs/docs.md) serves, and
44
- `vatio docs --save` writes it next to the workspace.
46
+ `vatio docs --save` writes it next to the workspace. `vatio docs PAGE` and
47
+ `vatio docs search TERM` print only the part you need.
45
48
 
46
49
  Don't guess `vatio.yml` keys. Unknown root keys fail validation, and the rules
47
50
  that judge a workspace live on the server — so the printed contract is the
@@ -40,8 +40,9 @@ export class ApiClient extends HttpClient {
40
40
  return this.patch("/whatsapp/live", { active });
41
41
  }
42
42
 
43
- checkWhatsapp() {
44
- return this.post("/whatsapp/health_check", {});
43
+ // pin: the number's two-step verification PIN, to register it again.
44
+ checkWhatsapp(pin = null) {
45
+ return this.post("/whatsapp/health_check", pin ? { pin } : {});
45
46
  }
46
47
 
47
48
  disconnectWhatsapp() {
@@ -100,6 +101,7 @@ export class ApiClient extends HttpClient {
100
101
  manifest,
101
102
  gitSha = null,
102
103
  gitBranch = null,
104
+ gitDirty = null,
103
105
  createdBy = null,
104
106
  environment = null,
105
107
  force = false,
@@ -108,6 +110,7 @@ export class ApiClient extends HttpClient {
108
110
  const body = { manifest };
109
111
  if (gitSha) body.git_sha = gitSha;
110
112
  if (gitBranch) body.git_branch = gitBranch;
113
+ if (typeof gitDirty === "boolean") body.git_dirty = gitDirty;
111
114
  if (createdBy) body.created_by = createdBy;
112
115
  if (environment) body.environment = environment;
113
116
  if (force) body.force = true;
@@ -367,8 +370,15 @@ export class ApiClient extends HttpClient {
367
370
  return this.get(`/chats/${encode(chatId)}/messages`, params);
368
371
  }
369
372
 
370
- sendChatMessage({ chatId, content }) {
371
- return this.post(`/chats/${encode(chatId)}/messages`, { content });
373
+ // `files` are `{ name, bytes }`, sent as the public API takes a visitor's
374
+ // (multipart `files[]`), so the agent reads them as it would on the web.
375
+ sendChatMessage({ chatId, content, files = [] }) {
376
+ if (files.length === 0) return this.post(`/chats/${encode(chatId)}/messages`, { content });
377
+
378
+ const form = new FormData();
379
+ if (content) form.set("content", content);
380
+ for (const file of files) form.append("files[]", new Blob([file.bytes]), file.name);
381
+ return this.post(`/chats/${encode(chatId)}/messages`, form);
372
382
  }
373
383
 
374
384
  exportChats({ from, to = null, environment = null, channel = null, after = null }) {
@@ -13,7 +13,7 @@ import { ask, fail, paint, takeFlag, takeValue } from "../support.mjs";
13
13
 
14
14
  const WHATSAPP_USAGE = [
15
15
  "Usage: vatio whatsapp [status] [--json]",
16
- " vatio whatsapp connect | live on|off | check | disconnect [--yes] | team",
16
+ " vatio whatsapp connect | live on|off | check [--pin PIN] | disconnect [--yes] | team",
17
17
  " vatio whatsapp invite EMAIL [--code CODE | --recovery-code CODE]",
18
18
  " vatio whatsapp phones [list] | add | rm PHONE | move PHONE [--json]",
19
19
  " vatio whatsapp templates [list] | create NAME ... | rm NAME | sync",
@@ -47,8 +47,18 @@ export async function whatsapp(config, args = []) {
47
47
  if (!["on", "off"].includes(value) || args.length) fail(WHATSAPP_USAGE);
48
48
  return printNumber(await client().setWhatsappLive(value === "on"), { json });
49
49
  }
50
- case "check":
51
- return printNumber(await client().checkWhatsapp(), { json });
50
+ case "check": {
51
+ // The number's two-step verification PIN registers it on the Cloud API
52
+ // again first: the fix for 133010, not registered.
53
+ const pin = takeValue(args, "--pin");
54
+ if (args.length) fail(WHATSAPP_USAGE);
55
+ if (pin !== null && !/^\d{6}$/.test(pin)) fail("--pin is the number's two-step verification PIN: 6 digits.");
56
+ const number = await client().checkWhatsapp(pin);
57
+ printNumber(number, { json, checked: true });
58
+ // A check that leaves Meta refusing every send did not pass.
59
+ if (number.issue) process.exitCode = 1;
60
+ return;
61
+ }
52
62
  case "disconnect":
53
63
  return disconnect(client(), args, { json });
54
64
  case "invite":
@@ -98,12 +108,16 @@ async function status(config, client, { json }) {
98
108
  if (error?.body?.error?.code !== "whatsapp_not_connected") throw error;
99
109
  }
100
110
  if (json) return console.log(JSON.stringify(number ?? { connected: false }, null, 2));
111
+ // A number Meta refuses every send from comes before anything else.
112
+ if (number?.issue) printNumber(number);
101
113
  await inInbox(config, { name: "WhatsApp", key: "whatsapp", own: "number", test: "phone" });
102
114
  // A server that predates the route answers 404; the link above is enough.
103
- await printPhones(await client.testPhones()).catch((error) => {
115
+ const phones = await client.testPhones().catch((error) => {
104
116
  if (error?.status !== 404 && error?.body?.error?.code !== "not_found") throw error;
117
+ return null;
105
118
  });
106
- if (number) printNumber(number);
119
+ if (phones) printPhones(phones);
120
+ if (number && !number.issue) printNumber(number);
107
121
  }
108
122
 
109
123
  async function phones(config, client, args, { json }) {
@@ -184,12 +198,30 @@ function printTeam({ members = [] }, { json }) {
184
198
  for (const member of members) console.log(` ${member.role.padEnd(11)} ${member.number} ${member.name}`);
185
199
  }
186
200
 
187
- function printNumber(number, { json = false } = {}) {
201
+ function printNumber(number, { json = false, checked = false } = {}) {
188
202
  if (json) return console.log(JSON.stringify(number, null, 2));
189
- const live = number.live
190
- ? paint("green", "live: the agent answers everyone who writes")
191
- : paint("cyan", "paused: vatio whatsapp live on to answer");
192
- console.log(`\n${number.number ?? "Your number"}: ${live}`);
193
- if (number.last_health_error) console.log(` ${paint("red", "problem:")} ${number.last_health_error} (vatio whatsapp check)`);
203
+ const name = number.number ?? "Your number";
204
+ if (number.issue) {
205
+ printIssue(name, number.issue);
206
+ } else {
207
+ const live = number.live
208
+ ? paint("green", "live: the agent answers everyone who writes")
209
+ : paint("cyan", "paused: vatio whatsapp live on to answer");
210
+ console.log(`\n${name}: ${live}`);
211
+ if (checked && number.state !== "error") console.log(" Meta answered the check: the number can send.");
212
+ }
213
+ if (number.last_health_error && number.last_health_error !== number.issue?.message) {
214
+ console.log(` ${paint("red", "problem:")} ${number.last_health_error} (vatio whatsapp check)`);
215
+ }
194
216
  if (number.failed_deliveries) console.log(` ${number.failed_deliveries} failed deliveries: vatio whatsapp failed`);
195
217
  }
218
+
219
+ // Meta refuses every send from the number, and the server API refuses your
220
+ // backend's messages with 409 whatsapp_number_unhealthy until a check passes.
221
+ function printIssue(name, issue) {
222
+ const code = issue.code ? ` (Meta ${issue.code})` : "";
223
+ console.log(`\n${name}: ${paint("red", `NOT SENDING since ${issue.since}${code}`)}`);
224
+ if (issue.message) console.log(` Meta: ${issue.message}`);
225
+ console.log(` Fix: ${issue.fix}`);
226
+ console.log(" Until a check passes, POST /messages answers 409 whatsapp_number_unhealthy and the agent's replies do not go out.");
227
+ }
@@ -13,11 +13,12 @@
13
13
  // does the widget's and WhatsApp's, so this gives you nothing you did not
14
14
  // already hold (lib/visitor-identity.mjs, Vatio::Preview::Tester).
15
15
 
16
- import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
17
- import { join } from "node:path";
16
+ import { randomBytes } from "node:crypto";
17
+ import { appendFileSync, existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { basename, dirname, join } from "node:path";
18
19
 
19
20
  import { ApiClient } from "../api-client.mjs";
20
- import { fail, sleep, takeEnv, takeFlag, takeValue } from "../support.mjs";
21
+ import { fail, sleep, takeAll, takeEnv, takeFlag, takeValue } from "../support.mjs";
21
22
  import { IDENTITY_FLAGS_USAGE, takeIdentity, tokenFor } from "../visitor-identity.mjs";
22
23
 
23
24
  export const STATE_FILE = ".vatio-chat.json";
@@ -35,6 +36,10 @@ const RETIRED = {
35
36
  // someone meant to say to their agent, and sending them starts a chat.
36
37
  const NOT_SUBCOMMANDS = new Set(["list", "ls", "search", "find", "get", "read", "view", "open", "history", "status", "new", "start"]);
37
38
  const REMOVED_FLAGS = ["--channel", "--from", "--as", "--sandbox-url"];
39
+ // What a visitor may attach to one message (Vatio::PublicApi::VisitorUploads):
40
+ // checked here too, so a file that would be refused is never uploaded.
41
+ const MAX_FILES = 4;
42
+ const MAX_FILE_BYTES = 8 * 1024 * 1024;
38
43
 
39
44
  export async function chat(config, args) {
40
45
  // Not a conversation of your own, so none of what follows applies to it,
@@ -53,18 +58,30 @@ export async function chat(config, args) {
53
58
  }
54
59
 
55
60
  const environment = takeEnv(args, { fallback: "preview" });
56
- const timeout = Number(takeValue(args, "--timeout") ?? 120);
61
+ const files = readFiles(takeAll(args, "--file"));
62
+ // A PDF is read before the agent answers, which can take minutes.
63
+ const timeout = Number(takeValue(args, "--timeout") ?? (files.length > 0 ? 300 : 120));
57
64
  const lastValue = takeValue(args, "--last");
58
65
  const last = Number(lastValue ?? 10);
59
66
  const json = takeFlag(args, "--json");
60
67
  const fresh = takeFlag(args, "--new");
68
+ // One chat by id, whatever the state file says: parallel sessions each keep
69
+ // their own this way, where the file holds one chat per environment.
70
+ const chatId = takeValue(args, "--chat");
61
71
  const apiUrl = takeValue(args, "--api-url");
62
72
  const token = takeValue(args, "--token");
63
73
  const asPhone = takeValue(args, "--as-phone");
64
74
 
65
75
  const identity = takeIdentity(args, config);
66
76
 
67
- const options = { environment, timeout, last, lastGiven: lastValue != null, json, apiUrl, token, asPhone, identity };
77
+ if (chatId != null) {
78
+ if (!/^\d+$/.test(chatId)) fail(`--chat takes a chat id, the number \`vatio chat --new\` prints (got ${JSON.stringify(chatId)}).`);
79
+ if (fresh || asPhone) fail("--chat continues a chat that is already open: drop --new and --as-phone, or drop --chat.");
80
+ }
81
+
82
+ const options = {
83
+ environment, timeout, last, lastGiven: lastValue != null, json, apiUrl, token, asPhone, identity, chatId, files
84
+ };
68
85
  if (args.length === 1 && RETIRED[args[0]]) fail(RETIRED[args[0]]);
69
86
  if (args.length === 1 && NOT_SUBCOMMANDS.has(args[0].toLowerCase())) {
70
87
  fail(
@@ -76,33 +93,46 @@ export async function chat(config, args) {
76
93
  const sub = SUBCOMMANDS.has(args[0]) ? args.shift() : null;
77
94
 
78
95
  if (sub === "help") return console.log(chatHelp());
96
+ if (sub && files.length > 0) fail("--file goes with a message: vatio chat \"message\" --file PATH");
79
97
  if (sub === "show") return await showChat(config, options, args);
80
98
 
81
99
  // A phone is fixed when a chat opens, so naming one opens one. A signed-in
82
100
  // visitor opens one only when it is someone else (ensureChat).
83
101
  const opening = fresh || Boolean(asPhone);
84
- if (opening) await startOver(config, options);
102
+ // The message goes to the chat this command opened, never to whatever the
103
+ // state file says by the time it is sent: another `vatio chat --new` running
104
+ // alongside may have written its own there in between.
105
+ const opened = opening ? await startOver(config, options) : null;
85
106
  const message = args.join(" ").trim();
86
- if (message === "") return opening ? undefined : console.log(chatHelp());
107
+ if (message === "" && files.length === 0) return opening ? undefined : console.log(chatHelp());
87
108
 
88
- return await converse(config, options, message);
109
+ return await converse(config, options, message, opened);
89
110
  }
90
111
 
91
112
  export function chatHelp() {
92
113
  return `Usage:
93
- vatio chat "message" [--env NAME] [--new] [--timeout N] [--as-phone me|PHONE] ${IDENTITY_FLAGS_USAGE}
114
+ vatio chat "message" [--file PATH]... [--env NAME] [--new] [--timeout N] [--as-phone me|PHONE] ${IDENTITY_FLAGS_USAGE}
115
+ vatio chat --chat CHAT_ID "message" [--file PATH]...
94
116
  vatio chat show [CHAT_ID] [--env NAME] [--last N] [--json]
95
117
  ${EXPORT_USAGE}
96
118
 
97
- --env picks the deployment that answers: preview (default), live, or a preview
98
- name like pr-42. A chat against live is a real conversation and shows up in
99
- your inbox.
119
+ --env picks the deployment that answers: preview (default) or live. A chat
120
+ against live is a real conversation and shows up in your inbox.
121
+
122
+ --file PATH attaches a file to the message, as a visitor would from the web:
123
+ up to four, 8 MB each, images, PDFs, text files or audio. The message may be
124
+ empty with one. A PDF is read before the agent answers (the timeout defaults
125
+ to 300 seconds then), and a [file] line says how much of it the agent got.
100
126
 
101
127
  \`show\` prints the chat you are in, with every tool call the agent made. Give
102
128
  it an id to read any chat in the workspace -- one a visitor had on the web,
103
129
  WhatsApp or Instagram -- with the environment and deployment that answered it.
104
130
  Each message carries its id (#4821), the one \`vatio test add --message\` takes.
105
- A [your backend] line under a tool call is how your backend answered it.
131
+ A [file] line is a file the visitor sent: for a PDF, how many characters the
132
+ agent was given, "truncated at N" when it got only that many, or
133
+ "unreadable" and why. A [your backend] line under a tool call is how your
134
+ backend answered it, or that the tool's request.cache answered without
135
+ calling it.
106
136
  A [safeguard] line says which of Vatio's checks discarded or rewrote a draft,
107
137
  and a [vatio] line marks a reply Vatio wrote because the agent's turn produced
108
138
  none: why, and whether anything in your workspace caused it.
@@ -117,7 +147,9 @@ A chat as someone else starts over; the same person continues it.
117
147
 
118
148
  The open chat per deployment is remembered in ${STATE_FILE}, so a second
119
149
  \`vatio chat\` continues the first. \`--new\` starts over as a visitor the
120
- workspace has never met.
150
+ workspace has never met, sends the message to that new chat and prints its id.
151
+ \`--chat CHAT_ID\` continues that chat, whatever ${STATE_FILE} says: for
152
+ conversations running side by side, each command names its own.
121
153
 
122
154
  \`--as-phone\` opens a preview chat that speaks as a phone, for tools that
123
155
  need $contact.phone_number or a team role (access: supervisor and up): \`me\`
@@ -231,7 +263,31 @@ function subjectsFor(config, apiUrl) {
231
263
  function rememberChat(config, { apiUrl, environment, chatId, subject = null }) {
232
264
  const chats = { ...chatsFor(config, apiUrl), [environment]: chatId };
233
265
  const subjects = { ...subjectsFor(config, apiUrl), [environment]: subject };
234
- writeFileSync(statePath(config), `${JSON.stringify({ api_url: apiUrl, chats, subjects }, null, 2)}\n`);
266
+ writeAtomically(statePath(config), `${JSON.stringify({ api_url: apiUrl, chats, subjects }, null, 2)}\n`);
267
+ }
268
+
269
+ // Written whole or not at all, so a command reading it while another writes
270
+ // never gets half a file. The temporary name starts with a dot, which keeps
271
+ // it out of a push.
272
+ function writeAtomically(path, content) {
273
+ const temporary = join(dirname(path), `.${basename(path)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
274
+ writeFileSync(temporary, content);
275
+ try {
276
+ renameSync(temporary, path);
277
+ } catch (error) {
278
+ rmSync(temporary, { force: true });
279
+ throw error;
280
+ }
281
+ }
282
+
283
+ // --chat's, as is: it is not remembered, so it moves no other command off
284
+ // the chat it is in.
285
+ async function chatToContinue(config, options) {
286
+ if (options.chatId == null) return await ensureChat(config, options);
287
+
288
+ const chatId = Number(options.chatId);
289
+ if (options.identity) await refreshIdentity(config, options, chatId);
290
+ return chatId;
235
291
  }
236
292
 
237
293
  async function ensureChat(config, options) {
@@ -302,18 +358,72 @@ function speaker(payload) {
302
358
  return ` as ${phone}${payload.team_role ? ` (${payload.team_role})` : ""}`;
303
359
  }
304
360
 
305
- async function converse(config, options, message) {
361
+ // `opened` is the chat this command just opened, if it opened one.
362
+ async function converse(config, options, message, opened = null) {
306
363
  const api = client(config, options);
307
- const chatId = await ensureChat(config, options);
308
- const sent = await api.sendChatMessage({ chatId, content: message });
364
+ const chatId = opened ?? (await chatToContinue(config, options));
365
+ const sent = await api.sendChatMessage({ chatId, content: message, files: options.files ?? [] });
309
366
  const assistant = await waitForAssistant(api, {
310
367
  chatId,
311
368
  after: sent.user_message_id,
312
369
  timeout: options.timeout
313
370
  });
371
+ if (options.files?.length > 0) await printSentFiles(api, chatId, sent.user_message_id);
314
372
  console.log(formatVisitor(assistant));
315
373
  }
316
374
 
375
+ function readFiles(paths) {
376
+ if (paths.length > MAX_FILES) fail(`At most ${MAX_FILES} files per message, as for a visitor (got ${paths.length}).`);
377
+ return paths.map((path) => {
378
+ let stats;
379
+ try {
380
+ stats = statSync(path);
381
+ } catch {
382
+ fail(`--file ${path}: no such file.`);
383
+ }
384
+ if (!stats.isFile()) fail(`--file ${path}: not a file.`);
385
+ if (stats.size > MAX_FILE_BYTES) {
386
+ fail(`${basename(path)} is ${humanBytes(stats.size)}; the limit is 8 MB per file, as for a visitor.`);
387
+ }
388
+ return { name: basename(path), bytes: readFileSync(path) };
389
+ });
390
+ }
391
+
392
+ // The message as stored, by the id the send returned: what was read of each
393
+ // file by the time the agent answered.
394
+ async function printSentFiles(api, chatId, messageId) {
395
+ const payload = await api.chatMessages({ chatId, after: messageId - 1 });
396
+ const stored = (Array.isArray(payload.data) ? payload.data : []).find((entry) => entry.id === messageId);
397
+ for (const attachment of stored?.attachments ?? []) console.log(attachmentLine(attachment));
398
+ }
399
+
400
+ // One file a message carried, and what the agent was given of it: a PDF's
401
+ // reading (Vatio::Runtime::MediaPolicy.document_reading), or a video's
402
+ // description.
403
+ function attachmentLine(attachment) {
404
+ const about = [attachment.content_type, humanBytes(attachment.byte_size)].filter(Boolean).join(", ");
405
+ const head = `[file] ${attachment.filename} (${about})`;
406
+ const reading = attachment.reading;
407
+ if (!reading) return attachment.description ? `${head}: described in ${attachment.description.length} characters` : head;
408
+
409
+ const pages = reading.pages ? `${reading.pages} pages, ` : "";
410
+ if (reading.status === "read") return `${head}: ${pages}${reading.chars} characters read`;
411
+ if (reading.status === "unreadable") return `${head}: ${pages}unreadable: ${reading.error_message ?? reading.error}`;
412
+ if (reading.status !== "truncated") return `${head}: ${pages}not read yet`;
413
+
414
+ const why =
415
+ reading.truncated === "characters"
416
+ ? `of ${reading.total_chars} read; the rest was left out`
417
+ : "the reading stopped before the end of the document";
418
+ return `${head}: ${pages}${reading.chars} characters read, truncated at ${reading.truncated_at} (${why})`;
419
+ }
420
+
421
+ function humanBytes(bytes) {
422
+ if (!Number.isFinite(bytes)) return null;
423
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
424
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
425
+ }
426
+
317
427
  // What a visitor would have seen in a row the developer API always sends in
318
428
  // full -- the same three questions the server used to answer behind
319
429
  // `view=visitor`: not deleted, said by a person or the agent, and actually
@@ -354,7 +464,7 @@ async function allMessages(api, chatId) {
354
464
  }
355
465
 
356
466
  async function showChat(config, options, args) {
357
- let chatId = args.shift();
467
+ let chatId = args.shift() ?? options.chatId ?? undefined;
358
468
  if (chatId !== undefined && !/^\d+$/.test(chatId)) fail("Usage: vatio chat show [CHAT_ID] [--last N] [--json]");
359
469
  if (chatId === undefined) {
360
470
  const apiUrl = config.resolveApiUrl({ explicit: options.apiUrl });
@@ -401,6 +511,10 @@ async function showChat(config, options, args) {
401
511
  : " (discarded)"
402
512
  : "";
403
513
  if (content !== "" || flags) console.log(`[${message.role} #${message.id}]${flags} ${content}`);
514
+ for (const attachment of Array.isArray(message.attachments) ? message.attachments : []) {
515
+ console.log(` ${attachmentLine(attachment)}`);
516
+ }
517
+ for (const line of buttonLines(message)) console.log(` ${line}`);
404
518
  for (const call of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
405
519
  console.log(` -> ${call.name}(${truncate(JSON.stringify(call.arguments ?? {}), 400)})`);
406
520
  if (call.backend) console.log(` [your backend] ${backendLine(call.backend)}`);
@@ -416,6 +530,7 @@ async function showChat(config, options, args) {
416
530
  function backendLine(backend) {
417
531
  const request = [backend.method, backend.url].filter(Boolean).join(" ");
418
532
  const status = [backend.http_status && `HTTP ${backend.http_status}`, backend.outcome].filter(Boolean).join(" · ");
533
+ if (backend.cached) return `${request} → ${status} from the tool's request.cache; your backend was not called`;
419
534
  const failed = backend.outcome && backend.outcome !== "ok" ? " — failed in your backend, not in the agent" : "";
420
535
  return `${request} → ${status} in ${backend.duration_ms ?? "?"} ms${failed}`;
421
536
  }
@@ -495,11 +610,19 @@ async function startOver(config, options) {
495
610
  apiUrl,
496
611
  chatId: chatsFor(config, apiUrl)[options.environment] ?? null
497
612
  });
498
- console.log(`New ${options.environment} chat ${payload.chat_id}`);
613
+ console.log(`New ${options.environment} chat ${payload.chat_id} (\`vatio chat --chat ${payload.chat_id} "…"\` continues it)`);
614
+ return Number(payload.chat_id);
499
615
  }
500
616
 
501
617
  function formatVisitor(message) {
502
618
  if (!message) return "";
503
619
  const role = message.role === "assistant" ? "agent" : "you";
504
- return `[${role}] ${String(message.content ?? "").trim()}`;
620
+ return [`[${role}] ${String(message.content ?? "").trim()}`, ...buttonLines(message).map((line) => ` ${line}`)].join("\n");
621
+ }
622
+
623
+ // A link the reply sends as a button: on WhatsApp and Instagram the visitor
624
+ // sees the text without it and this button under it.
625
+ function buttonLines(message) {
626
+ const buttons = Array.isArray(message.buttons) ? message.buttons : [];
627
+ return buttons.map((button) => `[button] ${button.title} → ${button.url}`);
505
628
  }
@@ -81,12 +81,13 @@ export async function checkWorkspace(config, workspace, { environment = null } =
81
81
  const IGNORED_BLOCK = /^vatio\.yml: `[^`]+` is ignored/;
82
82
 
83
83
  // Returns the ignored-block lines it held back, for a caller that prints them
84
- // last (`vatio push`); otherwise they follow the other warnings.
85
- export function printDiagnostics(payload, { holdIgnored = false } = {}) {
86
- for (const row of asArray(payload.errors)) console.error(`error: ${diagnosticLine(row)}`);
84
+ // last (`vatio push`); otherwise they follow the other warnings. Each line is
85
+ // printed once per command: `seen` carries what was already said, for a
86
+ // command that gets warnings from more than one response.
87
+ export function printDiagnostics(payload, { holdIgnored = false, seen = new Set() } = {}) {
88
+ for (const line of unseen(asArray(payload.errors).map(diagnosticLine), seen)) console.error(`error: ${line}`);
87
89
  const ignored = [];
88
- for (const row of asArray(payload.warnings)) {
89
- const line = diagnosticLine(row);
90
+ for (const line of unseen(asArray(payload.warnings).map(diagnosticLine), seen)) {
90
91
  if (IGNORED_BLOCK.test(line)) ignored.push(line);
91
92
  else console.error(`warning: ${line}`);
92
93
  }
@@ -94,6 +95,14 @@ export function printDiagnostics(payload, { holdIgnored = false } = {}) {
94
95
  return ignored;
95
96
  }
96
97
 
98
+ function unseen(lines, seen) {
99
+ return lines.filter((line) => {
100
+ if (seen.has(line)) return false;
101
+ seen.add(line);
102
+ return true;
103
+ });
104
+ }
105
+
97
106
  function printIgnored(lines) {
98
107
  if (lines.length === 0) return;
99
108
  const one = lines.length === 1;
@@ -143,7 +152,8 @@ export async function push(config, args) {
143
152
  }
144
153
 
145
154
  const check = await checkWorkspace(config, workspace, { environment });
146
- const ignored = printDiagnostics(check, { holdIgnored: true });
155
+ const seen = new Set();
156
+ const ignored = printDiagnostics(check, { holdIgnored: true, seen });
147
157
  if (!check.ok) {
148
158
  printIgnored(ignored);
149
159
  fail(`push aborted: check failed (${asArray(check.errors).length} error(s))`);
@@ -151,12 +161,18 @@ export async function push(config, args) {
151
161
 
152
162
  const client = deployClient(config, workspace);
153
163
  const baseUrl = config.resolveBaseUrl();
164
+ const root = config.workspaceRootRequired();
165
+ const gitBranch = detectGitBranch(root);
166
+ // Uncommitted changes under the workspace directory, which is what a push
167
+ // sends: then git_sha alone does not say what was pushed.
168
+ const changes = gitChanges(root, ["."]);
154
169
  let payload;
155
170
  try {
156
171
  payload = await client.pushPreview({
157
172
  manifest: check.manifest,
158
- gitSha: detectGitSha(config.workspaceRootRequired()),
159
- gitBranch: detectGitBranch(config.workspaceRootRequired()),
173
+ gitSha: detectGitSha(root),
174
+ gitBranch,
175
+ gitDirty: changes === null ? null : changes.length > 0,
160
176
  createdBy: process.env.USER ?? null,
161
177
  environment,
162
178
  force,
@@ -164,6 +180,9 @@ export async function push(config, args) {
164
180
  });
165
181
  } catch (error) {
166
182
  if (error instanceof ConflictError && error.errorKey === "preview_edited_outside") fail(editedOutsideMessage(error));
183
+ if (error instanceof UnprocessableError && error.errorKey === "preview_has_unpublished_push") {
184
+ fail(unpublishedPushMessage(error, gitBranch));
185
+ }
167
186
  throw error;
168
187
  }
169
188
  // What the files match now, so the next push is built on it.
@@ -184,9 +203,11 @@ export async function push(config, args) {
184
203
  for (const line of consequenceLines(payload)) console.log(line);
185
204
  // Where to try it: the inbox's Try the agent panel for that environment.
186
205
  if (payload.share_url) console.log(`Try it: ${payload.share_url}`);
187
- for (const warning of asArray(payload.warnings)) {
188
- if (!IGNORED_BLOCK.test(String(warning))) console.log(` warning: ${warning}`);
189
- else if (!ignored.includes(String(warning))) ignored.push(String(warning));
206
+ // Mostly what the check already said: the platform loads the manifest again
207
+ // to apply it.
208
+ for (const warning of unseen(asArray(payload.warnings).map(diagnosticLine), seen)) {
209
+ if (IGNORED_BLOCK.test(warning)) ignored.push(warning);
210
+ else console.log(` warning: ${warning}`);
190
211
  }
191
212
  if (payload.preview_url) console.log(`Preview: ${payload.preview_url}`);
192
213
 
@@ -269,6 +290,42 @@ function editedOutsideMessage(error) {
269
290
  return lines.join("\n");
270
291
  }
271
292
 
293
+ // Refused because preview holds a push from another branch nobody published:
294
+ // whose, so the session that hit it can tell whether that work is done
295
+ // without asking around. A platform older than `held` sends its own sentence.
296
+ function unpublishedPushMessage(error, branch) {
297
+ const held = error.body.held;
298
+ if (!held || typeof held !== "object") return error.message;
299
+
300
+ const yours = branch ? ` Yours is from branch ${branch}.` : "";
301
+ return [
302
+ "Preview holds a push from another branch that is not published:",
303
+ ` ${heldLine(held)}`,
304
+ "",
305
+ `A push would replace it.${yours} Publish what preview holds first (\`vatio publish\`), or`,
306
+ "`vatio push --force` to replace it. `vatio status` shows what preview holds at any time."
307
+ ].join("\n");
308
+ }
309
+
310
+ // `#42 from branch feat/x, a1b2c3d plus uncommitted changes, pushed by ivan on
311
+ // 2026-10-28T14:02:00Z`. Fields as AgentDeployment#held_payload and
312
+ // #status_payload name them; the id is `deployment_id` in one and `id` in the
313
+ // other.
314
+ function heldLine(deployment) {
315
+ const id = deployment.deployment_id ?? deployment.id;
316
+ const parts = [`#${id}`];
317
+ if (deployment.git_branch) parts[0] += ` from branch ${deployment.git_branch}`;
318
+ if (deployment.source === "edit") {
319
+ parts.push(`an edit made outside your files${deployment.change_summary ? ` (${deployment.change_summary})` : ""}`);
320
+ }
321
+ const sha = deployment.git_sha ? String(deployment.git_sha).slice(0, 7) : null;
322
+ if (deployment.git_dirty === true) parts.push(`${sha ?? "no commit"} plus uncommitted changes`);
323
+ else if (sha) parts.push(deployment.git_dirty === false ? `${sha}, committed` : sha);
324
+ const by = deployment.created_by ? ` by ${deployment.created_by}` : "";
325
+ parts.push(`${deployment.source === "edit" ? "made" : "pushed"}${by} on ${deployment.created_at}`);
326
+ return parts.join(", ");
327
+ }
328
+
272
329
  // `#42 by ivan@x.cl via Claude, 2026-10-16T12:00:00Z: instructions, tool my_orders`
273
330
  function editLine(edit) {
274
331
  const who = edit?.created_by ? ` by ${edit.created_by}` : "";
@@ -417,6 +474,11 @@ export async function status(config) {
417
474
  const workspace = config.resolveWorkspaceRequired();
418
475
  const payload = await deployClient(config, workspace).deployStatus();
419
476
  console.log(JSON.stringify(payload, null, 2));
477
+ printWhatsappIssue(payload.whatsapp);
478
+
479
+ // There is one preview, so a session about to push wants to know whose work
480
+ // is on it, and whether that work has gone live, without reading the JSON.
481
+ printPreviewHolds(payload);
420
482
 
421
483
  // A base with content that no deployed agent reads is knowledge the agent
422
484
  // cannot reach, and nothing else says so -- it just answers without it. On
@@ -442,6 +504,30 @@ export async function status(config) {
442
504
  printImpact(payload.impact);
443
505
  }
444
506
 
507
+ function printPreviewHolds(payload) {
508
+ const preview = payload.preview;
509
+ if (!preview || typeof preview !== "object") return;
510
+
511
+ const live = payload.live;
512
+ const published = preview.current_live
513
+ ? "live runs it"
514
+ : live?.id
515
+ ? `not published: live runs #${live.id}`
516
+ : "not published";
517
+ console.error(`Preview holds ${heldLine(preview)}; ${published}.`);
518
+ }
519
+
520
+ // A number that looks connected while Meta refuses every send from it: first
521
+ // on stderr, because every message the backend sends meanwhile is refused.
522
+ function printWhatsappIssue(whatsapp) {
523
+ const issue = whatsapp?.issue;
524
+ if (!issue) return;
525
+ const code = issue.code ? ` (Meta ${issue.code})` : "";
526
+ console.error(`WhatsApp ${whatsapp.number ?? "number"} is NOT SENDING since ${issue.since}${code}: ${issue.message ?? ""}`);
527
+ console.error(` Fix: ${issue.fix}`);
528
+ console.error(" Until a check passes (vatio whatsapp check), POST /messages answers 409 whatsapp_number_unhealthy.");
529
+ }
530
+
445
531
  // What Vatio did for this workspace in the last 30 days, in one line a
446
532
  // coding agent can repeat to the person: on stderr like the rest, and only
447
533
  // when there is something to count.
@@ -25,7 +25,8 @@ export async function messages(config, args) {
25
25
 
26
26
  console.log(`${page.messages.length} failed messages on ${workspace} (${environment}):`);
27
27
  for (const row of page.messages) {
28
- console.log(` #${row.id} ${row.created_at} ${row.mode} ${row.error_code || "?"} ${row.error_message || ""}`);
28
+ const ref = row.external_ref ? ` ${row.external_ref}` : "";
29
+ console.log(` #${row.id}${ref} ${row.created_at} ${row.mode} ${row.error_code || "?"} ${row.error_message || ""}`);
29
30
  }
30
31
  if (page.next_before) console.log(`More may match. Continue with --before ${page.next_before}.`);
31
32
  }
@@ -176,7 +176,8 @@ const AGENTS_NOTE = [
176
176
  "",
177
177
  "This directory is a Vatio workspace (`vatio.yml`). `vatio docs` prints the",
178
178
  "contract for the manifest, tools, knowledge and the CLI; read it before",
179
- "changing anything here.",
179
+ "changing anything here. `vatio docs search TERM` finds one thing in it, and",
180
+ "`vatio docs PAGE` prints one page (`vatio docs tools`).",
180
181
  "",
181
182
  "To fix what supervisors reported and the tests that fail, take them all in",
182
183
  "one session: `vatio test list` (follow the instructions at the top of its",
@@ -9,6 +9,7 @@ import { gzipSync } from "node:zlib";
9
9
  import * as claudeSessions from "../claude-session.mjs";
10
10
  import * as codexSessions from "../codex-session.mjs";
11
11
  import { configHome } from "../config.mjs";
12
+ import { pageArgument, sectionsOf } from "../docs-sections.mjs";
12
13
  import { ask, fail, takeFlag, takeValue } from "../support.mjs";
13
14
  import { chosenHeaders, clientHeaders, sendFeedback, telemetryEnabled } from "../telemetry.mjs";
14
15
  import { ensureAuthorized } from "./deploy.mjs";
@@ -17,22 +18,18 @@ import { DOCS_URL } from "./misc.mjs";
17
18
  // The whole developer contract as markdown, live from the platform. Fetched
18
19
  // rather than bundled: the docs describe the deploy you are talking to, and a
19
20
  // copy shipped inside this package would start lying the day either moves.
21
+ //
22
+ // The whole of it is thousands of lines. `vatio docs PAGE` prints one page,
23
+ // and `vatio docs search TERM` the sections that mention something.
20
24
  export async function docs(config, args) {
21
- const save = takeFlag(args, "--save");
22
- const savePath = takeValue(args, "--save-to") ?? (save ? args.shift() ?? null : null);
25
+ const saveTo = takeValue(args, "--save-to");
26
+ const save = takeFlag(args, "--save") || saveTo != null;
27
+ const savePath = saveTo ?? (save ? args.shift() ?? null : null);
28
+ if (!save && args[0] === "search") return await searchDocs(config, args.slice(1));
29
+ if (!save && args.length > 0) return await docsPage(config, args);
23
30
 
24
31
  const baseUrl = config.resolveBaseUrl();
25
- let markdown;
26
- try {
27
- const response = await fetch(`${baseUrl}/docs.md`, {
28
- headers: { ...clientHeaders(), Accept: "text/markdown, text/plain" },
29
- signal: AbortSignal.timeout(30_000)
30
- });
31
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
32
- markdown = await response.text();
33
- } catch (error) {
34
- fail(`Could not fetch the docs: ${error.message}\nRead them at ${DOCS_URL} instead.`);
35
- }
32
+ const markdown = await fetchContract(config);
36
33
 
37
34
  if (!save) {
38
35
  process.stdout.write(markdown);
@@ -46,6 +43,164 @@ export async function docs(config, args) {
46
43
  console.log("Point your coding agent at it, and re-run `vatio docs --save` to refresh.");
47
44
  }
48
45
 
46
+ const DOCS_SEARCH_USAGE = "vatio docs search TERM [--all]";
47
+ // Sections `vatio docs search` prints unless --all, and matches per section.
48
+ const SEARCH_SECTIONS = 20;
49
+ const SEARCH_MATCHES = 3;
50
+ const SEARCH_CONTEXT = 2;
51
+
52
+ async function fetchMarkdown(url, { method = "GET" } = {}) {
53
+ const response = await fetch(url, {
54
+ method,
55
+ headers: { ...clientHeaders(), Accept: "text/markdown, text/plain" },
56
+ signal: AbortSignal.timeout(30_000)
57
+ });
58
+ return { ok: response.ok, status: response.status, url: response.url, text: method === "HEAD" ? "" : await response.text() };
59
+ }
60
+
61
+ // docs.md, by way of the base URL, which redirects to where the docs live.
62
+ async function fetchContract(config) {
63
+ try {
64
+ const response = await fetchMarkdown(`${config.resolveBaseUrl()}/docs.md`);
65
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
66
+ return response.text;
67
+ } catch (error) {
68
+ fail(`Could not fetch the docs: ${error.message}\nRead them at ${DOCS_URL} instead.`);
69
+ }
70
+ }
71
+
72
+ // Where the pages' Markdown twins are: beside the docs.md the base URL leads
73
+ // to, https://vatio.ai/docs/ unless that says otherwise.
74
+ async function docsRoot(config) {
75
+ try {
76
+ const { ok, url } = await fetchMarkdown(`${config.resolveBaseUrl()}/docs.md`, { method: "HEAD" });
77
+ if (ok && url.endsWith("/docs.md")) return url.slice(0, -"docs.md".length);
78
+ } catch {
79
+ // The page fetch says what went wrong, if anything does.
80
+ }
81
+ return `${DOCS_URL}/`;
82
+ }
83
+
84
+ // One page as Markdown, by its path under /docs: `tools`, `cli/chat`, `cli`
85
+ // for cli/, a pasted https://vatio.ai/docs/tools#anchor too.
86
+ async function docsPage(config, args) {
87
+ if (args.length > 1) fail(`vatio docs takes one page (\`vatio docs tools\`), or \`${DOCS_SEARCH_USAGE}\`.`);
88
+ const page = args[0]
89
+ .trim()
90
+ .replace(/^https?:\/\/[^/]+/, "")
91
+ .replace(/[#?].*$/, "")
92
+ .replace(/^\/+/, "")
93
+ .replace(/^docs(\/|$)/, "")
94
+ .replace(/\.md$/, "");
95
+ const root = await docsRoot(config);
96
+ const candidates = page === "" || page === "index" ? ["index.md"] : page.endsWith("/") ? [`${page}index.md`] : [`${page}.md`, `${page}/index.md`];
97
+
98
+ for (const candidate of candidates) {
99
+ let response;
100
+ try {
101
+ response = await fetchMarkdown(`${root}${candidate}`);
102
+ } catch (error) {
103
+ fail(`Could not fetch ${root}${candidate}: ${error.message}`);
104
+ }
105
+ if (response.ok) {
106
+ process.stdout.write(response.text.endsWith("\n") ? response.text : `${response.text}\n`);
107
+ return;
108
+ }
109
+ if (response.status !== 404) fail(`Could not fetch ${root}${candidate}: HTTP ${response.status}`);
110
+ }
111
+
112
+ fail(await noSuchPage(root, page));
113
+ }
114
+
115
+ // The pages llms.txt lists whose path or title has the word in it, or all of
116
+ // them: the reader needs a name to pass, not a 404.
117
+ async function noSuchPage(root, page) {
118
+ let pages = [];
119
+ try {
120
+ const response = await fetchMarkdown(`${root}llms.txt`);
121
+ if (response.ok) {
122
+ pages = [...response.text.matchAll(/^- \[([^\]]+)\]\((https?:\/\/[^)]+)\.md\)/gm)].map(([, title, url]) => ({
123
+ title,
124
+ name: pageArgument(`${url.replace(/(^|\/)index$/, "$1")}`)
125
+ }));
126
+ }
127
+ } catch {
128
+ // Said below without the list.
129
+ }
130
+ const words = page.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
131
+ const close = pages.filter(({ title, name }) => words.some((word) => `${name} ${title}`.toLowerCase().includes(word)));
132
+ const listed = close.length > 0 ? close : pages;
133
+ const width = Math.max(0, ...listed.map(({ name }) => name.length));
134
+ return [
135
+ `No docs page ${JSON.stringify(page)}. \`${DOCS_SEARCH_USAGE}\` looks inside the pages.`,
136
+ ...(listed.length > 0 ? ["", close.length > 0 ? "Pages like it:" : "The pages:"] : []),
137
+ ...listed.map(({ title, name }) => ` vatio docs ${name.padEnd(width)} ${title}`)
138
+ ].join("\n");
139
+ }
140
+
141
+ // The sections of the reference that mention TERM, case-insensitively: each
142
+ // with its heading path, its URL and the lines around each match, numbered as
143
+ // in docs.md (`vatio docs --save`).
144
+ async function searchDocs(config, args) {
145
+ const all = takeFlag(args, "--all");
146
+ const term = args.join(" ").trim();
147
+ if (term === "") fail(`Say what to look for: ${DOCS_SEARCH_USAGE}`);
148
+
149
+ const markdown = await fetchContract(config);
150
+ const needle = term.toLowerCase();
151
+ const hits = sectionsOf(markdown)
152
+ .map((section) => ({ ...section, matches: section.lines.filter((line) => line.text.toLowerCase().includes(needle)) }))
153
+ .filter((section) => section.matches.length > 0);
154
+
155
+ if (hits.length === 0) {
156
+ console.log(
157
+ `Nothing in the reference mentions ${JSON.stringify(term)}. Try another word, or \`vatio docs PAGE\` for a page; ` +
158
+ "the guides are not in the reference, and `vatio docs guides/NAME` prints one."
159
+ );
160
+ return;
161
+ }
162
+
163
+ const shown = all ? hits : hits.slice(0, SEARCH_SECTIONS);
164
+ const count = hits.length === 1 ? "1 section" : `${hits.length} sections`;
165
+ console.log(`${count} of the reference mention ${JSON.stringify(term)}${shown.length < hits.length ? `; the first ${shown.length}` : ""}.`);
166
+
167
+ for (const section of shown) {
168
+ console.log("");
169
+ console.log(section.path.join(" › "));
170
+ console.log(`${section.url} (vatio docs ${pageArgument(section.url)})`);
171
+ for (const line of excerpt(section)) console.log(line);
172
+ }
173
+
174
+ if (shown.length < hits.length) {
175
+ console.log("");
176
+ const quoted = /\s/.test(term) ? JSON.stringify(term) : term;
177
+ console.log(`${hits.length - shown.length} more: \`vatio docs search ${quoted} --all\`, or a narrower term.`);
178
+ }
179
+ }
180
+
181
+ // grep -n -C2 style: `288:` a matching line, `287-` one around it, `--`
182
+ // between runs that do not touch.
183
+ function excerpt(section) {
184
+ const { lines, matches } = section;
185
+ const wanted = new Set();
186
+ for (const match of matches.slice(0, SEARCH_MATCHES)) {
187
+ const at = lines.indexOf(match);
188
+ for (let i = Math.max(0, at - SEARCH_CONTEXT); i <= Math.min(lines.length - 1, at + SEARCH_CONTEXT); i++) wanted.add(i);
189
+ }
190
+ const hit = new Set(matches);
191
+ const out = [];
192
+ let previous = null;
193
+ for (const index of [...wanted].sort((a, b) => a - b)) {
194
+ if (previous !== null && index > previous + 1) out.push("--");
195
+ const line = lines[index];
196
+ out.push(`${line.number}${hit.has(line) ? ":" : "-"} ${line.text}`);
197
+ previous = index;
198
+ }
199
+ const more = matches.length - SEARCH_MATCHES;
200
+ if (more > 0) out.push(`(${more} more in this section)`);
201
+ return out;
202
+ }
203
+
49
204
  // What got in the way, in the words of whoever hit it -- usually a coding agent
50
205
  // that just spent ten commands on something the docs should have said. It goes
51
206
  // to the Vatio team with the commands that came before it in this session.
@@ -0,0 +1,113 @@
1
+ // docs.md, the whole reference as one file, cut back into the sections it was
2
+ // made of, for `vatio docs search`. site/src/docs/contract.mjs writes it:
3
+ //
4
+ // ## Tab (Documentation, CLI, SDK, API Reference)
5
+ // ### Page title
6
+ // `https://vatio.ai/docs/page`
7
+ // #### A heading of the page (its ##, demoted by two), and so on down
8
+ //
9
+ // A section runs from one heading to the next, and knows its heading path and
10
+ // the URL of the page it is on, with the heading's anchor.
11
+
12
+ const FENCE = /^\s*(```|~~~)/;
13
+ const HEADING = /^(#{2,6})\s+(.*?)\s*$/;
14
+ const PAGE_URL = /^`(https?:\/\/[^`\s]+)`$/;
15
+ const CUSTOM_ID = /\s*\{#([\w-]+)\}\s*$/;
16
+
17
+ export function sectionsOf(markdown) {
18
+ const lines = markdown.split("\n");
19
+ const sections = [];
20
+ let tab = null;
21
+ let page = null;
22
+ let trail = [];
23
+ let section = null;
24
+ let fenced = false;
25
+
26
+ const open = (headings, anchor) => {
27
+ section = {
28
+ path: [tab, page?.title, ...headings].filter(Boolean),
29
+ url: page ? (anchor ? `${page.url}#${anchor}` : page.url) : null,
30
+ lines: []
31
+ };
32
+ sections.push(section);
33
+ };
34
+
35
+ lines.forEach((text, index) => {
36
+ const number = index + 1;
37
+ if (FENCE.test(text)) fenced = !fenced;
38
+ const heading = fenced ? null : HEADING.exec(text);
39
+
40
+ if (heading) {
41
+ const level = heading[1].length;
42
+ const title = heading[2].replace(CUSTOM_ID, "");
43
+ if (level === 2) {
44
+ tab = title;
45
+ page = null;
46
+ trail = [];
47
+ open([], null);
48
+ } else if (level === 3) {
49
+ page = { title, url: null, used: new Set([slugify(plain(title))]) };
50
+ trail = [];
51
+ open([], null);
52
+ } else {
53
+ // A page's own ## is #### here.
54
+ const depth = level - 4;
55
+ trail = [...trail.slice(0, depth), plain(title)];
56
+ open(trail, page ? anchorFor(heading[2], page.used) : null);
57
+ }
58
+ section.lines.push({ number, text });
59
+ return;
60
+ }
61
+
62
+ if (page && page.url === null && PAGE_URL.test(text.trim())) {
63
+ page.url = PAGE_URL.exec(text.trim())[1];
64
+ section.url = page.url;
65
+ return;
66
+ }
67
+ section?.lines.push({ number, text });
68
+ });
69
+
70
+ return sections.filter((row) => row.url !== null);
71
+ }
72
+
73
+ // What `vatio docs PAGE` takes for a page URL: "tools", "cli/chat", "cli" for
74
+ // cli/, "index" for the introduction.
75
+ export function pageArgument(url) {
76
+ const path = String(url).replace(/#.*$/, "").replace(/^.*?\/docs\//, "");
77
+ if (path === "") return "index";
78
+ return path.replace(/\/$/, "");
79
+ }
80
+
81
+ // The heading ids the site gives (site/src/plugins/rehype-docs.mjs): an
82
+ // explicit {#id}, or the text lowercased with accents folded and every run of
83
+ // anything else as one hyphen, -1, -2 on a repeat.
84
+ function anchorFor(raw, used) {
85
+ const custom = CUSTOM_ID.exec(raw);
86
+ if (custom) {
87
+ used.add(custom[1]);
88
+ return custom[1];
89
+ }
90
+ const slug = slugify(plain(raw));
91
+ let id = slug;
92
+ for (let i = 1; used.has(id); i++) id = `${slug}-${i}`;
93
+ used.add(id);
94
+ return id;
95
+ }
96
+
97
+ // A heading's text as the page shows it: no backticks, emphasis or link
98
+ // targets.
99
+ function plain(heading) {
100
+ return heading
101
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
102
+ .replace(/[`*]/g, "")
103
+ .trim();
104
+ }
105
+
106
+ function slugify(value) {
107
+ return value
108
+ .normalize("NFKD")
109
+ .replace(/[̀-ͯ]/g, "")
110
+ .toLowerCase()
111
+ .replace(/[^a-z0-9]+/g, "-")
112
+ .replace(/^-+|-+$/g, "");
113
+ }
package/lib/help.mjs CHANGED
@@ -32,6 +32,9 @@ the two you are in. Commands default as listed.
32
32
  updating; this only tells you). --full prints each
33
33
  entry whole instead of its headlines
34
34
  docs [--save [PATH]] The whole developer contract, live from Vatio
35
+ docs PAGE One page of it: tools, cli/chat, guides/NAME...
36
+ docs search TERM [--all] The sections that mention TERM, with their page
37
+ and the lines around each match
35
38
  feedback "TEXT" Tell the Vatio team what got in the way
36
39
  share-session ["FEEDBACK"] Send this Claude Code or Codex session to the
37
40
  Vatio team, after showing what goes; feedback optional
@@ -60,8 +63,11 @@ the two you are in. Commands default as listed.
60
63
  tested preview's version, and while it fails a
61
64
  report live passes; --force publishes anyway
62
65
  rollback Put live back to the previous snapshot: config and knowledge
63
- status Preview and live deployment state, and the replies
64
- Vatio wrote for the agent, and why
66
+ status Preview and live deployment state: which one
67
+ preview holds (branch, commit, uncommitted
68
+ changes, who pushed it and when, published or
69
+ not), the replies Vatio wrote for the agent, and
70
+ your WhatsApp number when Meta refuses its sends
65
71
  env [preview|live] An environment: token, widget snippet, link,
66
72
  knowledge changes and conflicts (default: preview)
67
73
  env list Both environments and what each runs
@@ -70,16 +76,23 @@ the two you are in. Commands default as listed.
70
76
  diff --stat|--name-only|--format json|--full
71
77
 
72
78
  Talk to your agent (as yourself by default — the token is the identity):
73
- chat "message" [--env NAME] [--new] [--as-phone me|PHONE]
79
+ chat "message" [--file PATH]... [--env NAME] [--new] [--as-phone me|PHONE]
74
80
  [--as-subject ID | --visitor-token JWT]
75
81
  preview by default; --env live is real; --new
76
- starts over as a visitor the agent never met.
82
+ starts over as a visitor the agent never met,
83
+ in a new chat whose id it prints.
84
+ --file attaches an image, PDF, text or audio file
85
+ as a visitor would (up to 4, 8 MB each).
77
86
  --as-phone speaks as your verified WhatsApp or a
78
87
  test phone; --as-subject signs a visitor in with
79
88
  your identity key, so \`access: private\` tools run
89
+ chat --chat CHAT_ID "message"
90
+ Continue that chat, whatever .vatio-chat.json
91
+ says: for chats running side by side
80
92
  chat show [CHAT_ID] [--json] [--last N]
81
93
  The chat you are in, or any chat in the workspace
82
- (web, WhatsApp, ...): messages, tool calls, channel
94
+ (web, WhatsApp, ...): messages, tool calls, channel,
95
+ and what was read of each file (truncated, unreadable)
83
96
  chat export --from DATE [--to DATE] [--env NAME] [--channel NAME] [--out FILE]
84
97
  What people said and were answered between two
85
98
  dates, redacted by Vatio, one conversation per
@@ -189,12 +202,16 @@ the two you are in. Commands default as listed.
189
202
  to type the ID; without a terminal, needs --yes
190
203
 
191
204
  WhatsApp (everything on the inbox's WhatsApp page; --json on each):
192
- whatsapp [status] Your number, whether it is live, its problems,
205
+ whatsapp [status] Your number, whether it is live, its problems
206
+ (first: a Meta error that fails every send),
193
207
  and the test phones
194
208
  whatsapp connect Where to connect your number (Meta's consent
195
209
  screen only opens in the inbox)
196
210
  whatsapp live on|off Answer everyone who writes, or nobody
197
- whatsapp check Check the number with Meta and re-subscribe it
211
+ whatsapp check [--pin PIN] Check the number with Meta and re-subscribe it;
212
+ a pass clears its problem. --pin (its 6-digit
213
+ two-step verification PIN) registers it on the
214
+ Cloud API again first: the fix for 133010
198
215
  whatsapp disconnect [--yes]
199
216
  whatsapp invite EMAIL [--code CODE]
200
217
  Email whoever holds the number the link that
@@ -214,7 +231,8 @@ the two you are in. Commands default as listed.
214
231
  Delete one at Meta; pull back ones made elsewhere
215
232
  whatsapp failed [--since DATE] [--until DATE] [--error-code CODE]
216
233
  [--error-contains TEXT] [--before ID]
217
- Messages Vatio gave up retrying (default: live)
234
+ Messages Vatio gave up retrying, with your
235
+ external_ref (default: live)
218
236
 
219
237
  Channels:
220
238
  instagram The same, for Instagram
package/lib/http.mjs CHANGED
@@ -124,7 +124,10 @@ export class HttpClient {
124
124
  Accept: "application/json"
125
125
  };
126
126
  const init = { method, headers, signal: AbortSignal.timeout(READ_TIMEOUT_MS) };
127
- if (body !== undefined) {
127
+ // Files go as multipart, whose boundary fetch() writes into the header.
128
+ if (body instanceof FormData) {
129
+ init.body = body;
130
+ } else if (body !== undefined) {
128
131
  headers["Content-Type"] = "application/json";
129
132
  init.body = JSON.stringify(body);
130
133
  }
package/lib/pull.mjs CHANGED
@@ -192,6 +192,7 @@ function linkEntry(raw) {
192
192
  const when = String(row.when ?? "").trim();
193
193
  if (when !== "") entry.when = when;
194
194
  if (isPlainObject(row.values) && Object.keys(row.values).length > 0) entry.values = row.values;
195
+ if (row.button === true) entry.button = true;
195
196
  return entry;
196
197
  }
197
198
 
package/lib/suggest.mjs CHANGED
@@ -88,6 +88,7 @@ const SUBCOMMAND_OF = {
88
88
  revoke: ["keys"],
89
89
  rm: ["env", "kb", "secrets", "webhooks", "test"],
90
90
  "rm-entry": ["kb"],
91
+ search: ["docs"],
91
92
  set: ["business", "quiet-hours", "secrets", "config"],
92
93
  show: ["chat", "kb", "business", "quiet-hours", "config"],
93
94
  phones: ["whatsapp"],
package/lib/support.mjs CHANGED
@@ -72,6 +72,13 @@ export function takeValue(args, name) {
72
72
  return null;
73
73
  }
74
74
 
75
+ // A repeatable flag: `--file a.pdf --file b.png`.
76
+ export function takeAll(args, name) {
77
+ const values = [];
78
+ for (let value = takeValue(args, name); value !== null; value = takeValue(args, name)) values.push(value);
79
+ return values;
80
+ }
81
+
75
82
  // Stamped on a deployment so a revision can be traced back to a commit. Absent
76
83
  // outside a repository, which is fine -- a workspace does not have to be in one.
77
84
  export function detectGitSha(cwd) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vatio-ai/cli",
3
- "version": "0.125.0",
3
+ "version": "0.126.0",
4
4
  "description": "Vatio CLI — deploy and manage Vatio agent workspaces",
5
5
  "keywords": [
6
6
  "vatio",