@vatio-ai/cli 0.125.0 → 0.127.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() {
@@ -56,28 +57,10 @@ export class ApiClient extends HttpClient {
56
57
  return this.get("/whatsapp/team");
57
58
  }
58
59
 
59
- moveTestPhone(phoneNumber) {
60
- return this.post(`/test_phones/${encode(phoneNumber)}/move`, {});
61
- }
62
-
63
60
  syncTemplates() {
64
61
  return this.post("/templates/sync", {});
65
62
  }
66
63
 
67
- // The phones verified in Try the agent.
68
- testPhones() {
69
- return this.get("/test_phones");
70
- }
71
-
72
- // The code a phone sends to Vatio's shared number to join; it adds nothing by itself.
73
- testPhoneCode() {
74
- return this.post("/test_phones", {});
75
- }
76
-
77
- removeTestPhone(phoneNumber) {
78
- return this.delete(`/test_phones/${encode(phoneNumber)}`);
79
- }
80
-
81
64
  deployedManifest({ environment = "live" } = {}) {
82
65
  return this.get("/manifest", { environment });
83
66
  }
@@ -100,6 +83,7 @@ export class ApiClient extends HttpClient {
100
83
  manifest,
101
84
  gitSha = null,
102
85
  gitBranch = null,
86
+ gitDirty = null,
103
87
  createdBy = null,
104
88
  environment = null,
105
89
  force = false,
@@ -108,6 +92,7 @@ export class ApiClient extends HttpClient {
108
92
  const body = { manifest };
109
93
  if (gitSha) body.git_sha = gitSha;
110
94
  if (gitBranch) body.git_branch = gitBranch;
95
+ if (typeof gitDirty === "boolean") body.git_dirty = gitDirty;
111
96
  if (createdBy) body.created_by = createdBy;
112
97
  if (environment) body.environment = environment;
113
98
  if (force) body.force = true;
@@ -367,8 +352,15 @@ export class ApiClient extends HttpClient {
367
352
  return this.get(`/chats/${encode(chatId)}/messages`, params);
368
353
  }
369
354
 
370
- sendChatMessage({ chatId, content }) {
371
- return this.post(`/chats/${encode(chatId)}/messages`, { content });
355
+ // `files` are `{ name, bytes }`, sent as the public API takes a visitor's
356
+ // (multipart `files[]`), so the agent reads them as it would on the web.
357
+ sendChatMessage({ chatId, content, files = [] }) {
358
+ if (files.length === 0) return this.post(`/chats/${encode(chatId)}/messages`, { content });
359
+
360
+ const form = new FormData();
361
+ if (content) form.set("content", content);
362
+ for (const file of files) form.append("files[]", new Blob([file.bytes]), file.name);
363
+ return this.post(`/chats/${encode(chatId)}/messages`, form);
372
364
  }
373
365
 
374
366
  exportChats({ from, to = null, environment = null, channel = null, after = null }) {
@@ -13,9 +13,8 @@ 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
- " vatio whatsapp phones [list] | add | rm PHONE | move PHONE [--json]",
19
18
  " vatio whatsapp templates [list] | create NAME ... | rm NAME | sync",
20
19
  " vatio whatsapp failed [--since DATE] [--until DATE] [--error-code CODE] ...",
21
20
  ].join("\n");
@@ -29,9 +28,16 @@ const MINE_REMOVED =
29
28
  "`vatio whatsapp mine` was removed: the team's numbers are the ones each member verified on their account " +
30
29
  "(Account in the inbox): vatio whatsapp team. A tool declares which role may use it with " +
31
30
  "`access: supervisor`, `developer` or `owner`.";
31
+ // Test phones went the same way: the team reaches the agent on Vatio's number
32
+ // from the WhatsApp each verified on their account, and what is left, a
33
+ // customer's phone, is added in the inbox.
34
+ const phonesRemoved = (name) =>
35
+ `\`vatio whatsapp ${name}\` was removed: everyone on the team reaches the agent on Vatio's number from the ` +
36
+ "WhatsApp they verified on their account (vatio whatsapp team lists them). To try it as a customer, add a " +
37
+ "customer phone in the inbox: Conversations → Try the agent → WhatsApp.";
32
38
 
33
39
  // One noun per thing on the inbox's WhatsApp page, each with the same verbs:
34
- // the number itself, its test phones, its templates and its failed messages.
40
+ // the number itself, the team on it, its templates and its failed messages.
35
41
  export async function whatsapp(config, args = []) {
36
42
  const json = takeFlag(args, "--json");
37
43
  const sub = args.shift();
@@ -41,22 +47,30 @@ export async function whatsapp(config, args = []) {
41
47
  case "status":
42
48
  return status(config, client(), { json });
43
49
  case "connect":
44
- return inInbox(config, { name: "WhatsApp", key: "whatsapp", own: "number", test: "phone" });
50
+ return inInbox(config, WHATSAPP);
45
51
  case "live": {
46
52
  const value = args.shift();
47
53
  if (!["on", "off"].includes(value) || args.length) fail(WHATSAPP_USAGE);
48
54
  return printNumber(await client().setWhatsappLive(value === "on"), { json });
49
55
  }
50
- case "check":
51
- return printNumber(await client().checkWhatsapp(), { json });
56
+ case "check": {
57
+ // The number's two-step verification PIN registers it on the Cloud API
58
+ // again first: the fix for 133010, not registered.
59
+ const pin = takeValue(args, "--pin");
60
+ if (args.length) fail(WHATSAPP_USAGE);
61
+ if (pin !== null && !/^\d{6}$/.test(pin)) fail("--pin is the number's two-step verification PIN: 6 digits.");
62
+ const number = await client().checkWhatsapp(pin);
63
+ printNumber(number, { json, checked: true });
64
+ // A check that leaves Meta refusing every send did not pass.
65
+ if (number.issue) process.exitCode = 1;
66
+ return;
67
+ }
52
68
  case "disconnect":
53
69
  return disconnect(client(), args, { json });
54
70
  case "invite":
55
71
  return invite(client(), args, { json });
56
72
  case "team":
57
73
  return printTeam(await client().whatsappTeam(), { json });
58
- case "phones":
59
- return phones(config, client(), args, { json });
60
74
  case "templates":
61
75
  return templates(config, json ? [...args, "--json"] : args);
62
76
  case "failed":
@@ -66,15 +80,27 @@ export async function whatsapp(config, args = []) {
66
80
  return fail(AGENT_NUMBERS_REMOVED);
67
81
  case "mine":
68
82
  return fail(MINE_REMOVED);
83
+ case "phones":
69
84
  case "test-phones":
70
- return fail("`vatio whatsapp test-phones` is `vatio whatsapp phones` now.");
85
+ return fail(phonesRemoved(sub));
71
86
  default:
72
87
  return fail(WHATSAPP_USAGE);
73
88
  }
74
89
  }
75
90
 
76
- export const instagram = (config) =>
77
- inInbox(config, { name: "Instagram", key: "instagram", own: "account", test: "account" });
91
+ const WHATSAPP = {
92
+ key: "whatsapp",
93
+ published: "Connect your own number in the inbox, on the WhatsApp page:",
94
+ draft: "Talk to your agent on WhatsApp with Try the agent in the inbox: verify your phone there once, and it " +
95
+ "reaches your agent on Vatio's number."
96
+ };
97
+ const INSTAGRAM = {
98
+ key: "instagram",
99
+ published: "Connect your own account and manage test accounts in the inbox, under Channels:",
100
+ draft: "Test Instagram with Try the agent in the inbox: verify your account there and talk to your agent."
101
+ };
102
+
103
+ export const instagram = (config) => inInbox(config, INSTAGRAM);
78
104
 
79
105
  async function inInbox(config, channel) {
80
106
  const status = await deployClient(config, config.resolveWorkspaceRequired()).deployStatus();
@@ -82,11 +108,7 @@ async function inInbox(config, channel) {
82
108
  // An older server sends no `published`; a live deployment means the same.
83
109
  const published = status.published ?? Boolean(status.live);
84
110
 
85
- if (published) {
86
- console.log(`Connect your own ${channel.own} and manage test ${channel.test}s in the inbox, under Channels:`);
87
- } else {
88
- console.log(`Test ${channel.name} with Try the agent in the inbox: verify your ${channel.test} there and talk to your agent.`);
89
- }
111
+ console.log(published ? channel.published : channel.draft);
90
112
  console.log(` ${published ? url : (status.try_url ?? url)}`);
91
113
  }
92
114
 
@@ -98,57 +120,10 @@ async function status(config, client, { json }) {
98
120
  if (error?.body?.error?.code !== "whatsapp_not_connected") throw error;
99
121
  }
100
122
  if (json) return console.log(JSON.stringify(number ?? { connected: false }, null, 2));
101
- await inInbox(config, { name: "WhatsApp", key: "whatsapp", own: "number", test: "phone" });
102
- // A server that predates the route answers 404; the link above is enough.
103
- await printPhones(await client.testPhones()).catch((error) => {
104
- if (error?.status !== 404 && error?.body?.error?.code !== "not_found") throw error;
105
- });
106
- if (number) printNumber(number);
107
- }
108
-
109
- async function phones(config, client, args, { json }) {
110
- const action = args.shift() ?? "list";
111
- const phone = args.shift();
112
- if (args.length) fail(WHATSAPP_USAGE);
113
- if (action === "list" && !phone) {
114
- const list = await client.testPhones();
115
- return json ? console.log(JSON.stringify(list, null, 2)) : printPhones(list);
116
- }
117
- if (action === "add" && !phone) return printJoin(await client.testPhoneCode(), { json });
118
- if (action === "rm" && phone) {
119
- await client.removeTestPhone(phone);
120
- return json ? console.log(JSON.stringify({ removed: phone })) : console.log(`Removed ${phone} from the test phones.`);
121
- }
122
- if (action === "move" && phone) {
123
- const { data } = await client.moveTestPhone(phone);
124
- return json ? console.log(JSON.stringify(data)) : console.log(`${data.phone_number} now tests this workspace.`);
125
- }
126
- fail(WHATSAPP_USAGE);
127
- }
128
-
129
- // The phones that joined by sending Try the agent's code: the ones a preview
130
- // message can go to.
131
- function printPhones({ data = [], max, elsewhere = [] }) {
132
- if (data.length === 0) {
133
- console.log("\nNo test phones yet. Add yours: vatio whatsapp phones add");
134
- } else {
135
- console.log(`\nTest phones (${data.length} of ${max}):`);
136
- for (const phone of data) console.log(` ${phone.phone_number}`);
137
- }
138
- if (elsewhere.length) {
139
- console.log("Verified on your other workspaces (vatio whatsapp phones move PHONE brings one here):");
140
- for (const phone of elsewhere) console.log(` ${phone.phone_number} ${phone.workspace}`);
141
- }
142
- }
143
-
144
- // The same code Try the agent shows: the phone joins when it sends it, so the
145
- // message is the proof that whoever added it holds the phone.
146
- function printJoin(join, { json }) {
147
- if (json) return console.log(JSON.stringify(join, null, 2));
148
- console.log(`From the phone to add, send this to ${join.send_to ?? "Vatio's test number"} on WhatsApp:`);
149
- console.log(` ${join.message}`);
150
- if (join.link_url) console.log(`Or open this on the phone, it writes the message:\n ${join.link_url}`);
151
- console.log(`The code works for ${Math.round((join.expires_in ?? 900) / 60)} minutes. Check with: vatio whatsapp phones`);
123
+ // A number Meta refuses every send from comes before anything else.
124
+ if (number?.issue) printNumber(number);
125
+ await inInbox(config, WHATSAPP);
126
+ if (number && !number.issue) printNumber(number);
152
127
  }
153
128
 
154
129
  async function disconnect(client, args, { json }) {
@@ -164,9 +139,9 @@ async function disconnect(client, args, { json }) {
164
139
  console.log("Disconnected. Connect a number again with: vatio whatsapp connect");
165
140
  }
166
141
 
167
- // The owner's: whoever holds the number (often a client) gets the link that
168
- // connects it, and joins as a supervisor. Confirmed with a second factor, as
169
- // `vatio team invite` is.
142
+ // The owner's: whoever manages the number (often a client) gets the link that
143
+ // connects it from their own Facebook account, and joins as a supervisor.
144
+ // Confirmed with a second factor, as `vatio team invite` is.
170
145
  async function invite(client, args, { json }) {
171
146
  const code = takeValue(args, "--code");
172
147
  const recoveryCode = takeValue(args, "--recovery-code");
@@ -175,21 +150,48 @@ async function invite(client, args, { json }) {
175
150
  const answer = await withSecondFactor((body) => client.inviteWhatsappConnector(body),
176
151
  { email, code, recovery_code: recoveryCode });
177
152
  if (json) return console.log(JSON.stringify(answer, null, 2));
178
- console.log(`Emailed ${answer.invited} the link that connects your number (${answer.role} on the team).`);
153
+ console.log(`Emailed ${answer.invited} the link that connects the number (${answer.role} on the team).`);
154
+ console.log("Once they connect it, it arrives paused: vatio whatsapp live on turns it live.");
179
155
  }
180
156
 
157
+ // Everyone on the team who talks to the agent, and the last digits of the
158
+ // WhatsApp each verified on their account: from it the agent knows them, and on
159
+ // Vatio's number it reaches this workspace. `number` is null until they do.
181
160
  function printTeam({ members = [] }, { json }) {
182
161
  if (json) return console.log(JSON.stringify(members, null, 2));
183
- if (members.length === 0) return console.log("No one on the team has verified their WhatsApp yet (Account, in the inbox).");
184
- for (const member of members) console.log(` ${member.role.padEnd(11)} ${member.number} ${member.name}`);
162
+ for (const member of members) {
163
+ const number = member.number ?? paint("cyan", "not verified");
164
+ console.log(` ${member.role.padEnd(11)} ${member.number ? number.padEnd(12) : number} ${member.name}`);
165
+ }
166
+ if (members.some((member) => !member.number)) {
167
+ console.log("Each person verifies their WhatsApp in the inbox, under Account.");
168
+ }
185
169
  }
186
170
 
187
- function printNumber(number, { json = false } = {}) {
171
+ function printNumber(number, { json = false, checked = false } = {}) {
188
172
  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)`);
173
+ const name = number.number ?? "Your number";
174
+ if (number.issue) {
175
+ printIssue(name, number.issue);
176
+ } else {
177
+ const live = number.live
178
+ ? paint("green", "live: the agent answers everyone who writes")
179
+ : paint("cyan", "paused: vatio whatsapp live on to answer");
180
+ console.log(`\n${name}: ${live}`);
181
+ if (checked && number.state !== "error") console.log(" Meta answered the check: the number can send.");
182
+ }
183
+ if (number.last_health_error && number.last_health_error !== number.issue?.message) {
184
+ console.log(` ${paint("red", "problem:")} ${number.last_health_error} (vatio whatsapp check)`);
185
+ }
194
186
  if (number.failed_deliveries) console.log(` ${number.failed_deliveries} failed deliveries: vatio whatsapp failed`);
195
187
  }
188
+
189
+ // Meta refuses every send from the number, and the server API refuses your
190
+ // backend's messages with 409 whatsapp_number_unhealthy until a check passes.
191
+ function printIssue(name, issue) {
192
+ const code = issue.code ? ` (Meta ${issue.code})` : "";
193
+ console.log(`\n${name}: ${paint("red", `NOT SENDING since ${issue.since}${code}`)}`);
194
+ if (issue.message) console.log(` Meta: ${issue.message}`);
195
+ console.log(` Fix: ${issue.fix}`);
196
+ console.log(" Until a check passes, POST /messages answers 409 whatsapp_number_unhealthy and the agent's replies do not go out.");
197
+ }
@@ -7,17 +7,18 @@
7
7
  // ever a second answer to keep in step with the true one.
8
8
  //
9
9
  // What you can be is someone who already proved who they are: `--as-phone`
10
- // speaks as a phone verified on WhatsApp (yours, or a test phone), and
10
+ // speaks as a phone verified on WhatsApp (yours, or a customer phone), and
11
11
  // `--as-subject` signs the token your backend would, with your identity key,
12
12
  // or `--visitor-token` brings one you have. Vatio only verifies them, as it
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,
@@ -45,7 +50,7 @@ export async function chat(config, args) {
45
50
  if (REMOVED_FLAGS.some((flag) => arg === flag || arg.startsWith(`${flag}=`))) {
46
51
  fail(
47
52
  `\`${arg}\` was removed. A CLI chat is you, the developer holding the token, unless you say who: ` +
48
- "--as-phone speaks as your verified WhatsApp (me) or a test phone, --as-subject ID signs a visitor in " +
53
+ "--as-phone speaks as your verified WhatsApp (me) or a customer phone, --as-subject ID signs a visitor in " +
49
54
  "with your identity key, and --visitor-token brings a token you have; " +
50
55
  "to pick a deployment use --env."
51
56
  );
@@ -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,13 +147,15 @@ 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\`
124
- is your own verified WhatsApp, with your role on the team; a number from
125
- \`vatio whatsapp phones\` is a customer. It stays a CLI chat: nothing goes
126
- to WhatsApp.
156
+ is your own verified WhatsApp, with your role on the team; one of the
157
+ workspace's customer phones (added in the inbox, under Conversations → Try the
158
+ agent → WhatsApp) is a customer. It stays a CLI chat: nothing goes to WhatsApp.
127
159
 
128
160
  \`export\` prints what people said and what they were answered between two
129
161
  dates (live unless --env says otherwise), one conversation per line as JSON,
@@ -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
  }