chesly 0.2.0 → 0.3.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
@@ -4,9 +4,9 @@ Your chats from the terminal, for you and your agents. `chesly` is the command-l
4
4
  [Chesly](https://chesly.app) API. It is built for agents (Claude Code, Codex, OpenClaw) as much as
5
5
  for people: JSON when piped, stable exit codes, and it never prompts.
6
6
 
7
- Read your chats, send messages, follow events as they happen, and manage webhooks, on WhatsApp,
8
- Telegram, Signal, iMessage, Instagram, Messenger, X, LinkedIn, Discord, Slack, Reddit, Google
9
- Messages, Google Chat and email.
7
+ Read your chats, send messages, edit or delete the ones you sent, follow events as they happen,
8
+ and manage webhooks, on WhatsApp, Telegram, Signal, iMessage, Instagram, Messenger, X, LinkedIn,
9
+ Discord, Slack, Reddit, Google Messages, Google Chat and email.
10
10
 
11
11
  ## Install
12
12
 
@@ -108,8 +108,9 @@ chesly accounts # your connected accounts and their statu
108
108
  Email is left out of `chats`, `catchup` and `search` unless you ask for it with `--network email`.
109
109
  `--network` takes any one network, and on `read` and `send` it says where to look a chat name up:
110
110
  an email thread's name is its subject. The names are `whatsapp`, `telegram`, `signal`, `imessage`,
111
- `instagram`, `messenger`, `twitter` (X), `linkedin`, `discord`, `slack`, `reddit`, `gmessages`
112
- (Google Messages), `googlechat` and `email`; `chesly accounts` shows each account's.
111
+ `instagram`, `messenger`, `line`, `twitter` (X), `linkedin`, `discord`, `slack`, `reddit`, `gmessages`
112
+ (Google Messages), `googlechat`, `grokbot` (Grok Bot), `chatgptdots` (OpenAI Dots), `muse` and `email`,
113
+ with `tiktok` and `wechat` coming soon; `chesly accounts` shows each account's.
113
114
 
114
115
  ```sh
115
116
  chesly chats --network email # your email threads
@@ -183,6 +184,56 @@ with the first attempt's result instead of sending again. A file send's error al
183
184
  upload as `media_id`: retry with `--media-id <that id>` instead of `--file`, since a new upload
184
185
  would be a new media ID, which the same key refuses (422 `idempotency_key_reused`).
185
186
 
187
+ ## Edit and delete messages
188
+
189
+ ```sh
190
+ chesly edit msg_... - <<'EOF' # change the text of a message you sent
191
+ On my way, 10 minutes
192
+ EOF
193
+ chesly delete msg_... # delete a message you sent, for everyone in the chat
194
+ ```
195
+
196
+ `delete` works on any message you sent: from Chesly (its apps or the API, such as a `chesly send`,
197
+ whose answer's `id` is the message ID) or from the network's own app (WhatsApp on your phone, say).
198
+ `edit` works only on messages you sent from Chesly: one you sent in the network's own app is
199
+ refused, as Chesly can't change its text on the network. Email can be neither edited nor unsent. `edit` takes text messages only, not photos, videos, files, voice notes,
200
+ stickers, locations, polls or calls. Its text comes on stdin like a send's, and the network caps it
201
+ as it caps a send: 1,000 characters on Instagram, 2,000 on Discord, 4,096 on Telegram, 10,000
202
+ elsewhere.
203
+
204
+ Each network's time limits apply. Past them the API refuses instead of pretending, because the
205
+ network would keep showing the old message:
206
+
207
+ | Network | Edit | Delete for everyone |
208
+ |---|---|---|
209
+ | WhatsApp | 15 minutes | 2 days |
210
+ | Signal | 24 hours, at most 10 edits | 24 hours |
211
+ | Telegram | 48 hours | no limit |
212
+ | Instagram | 15 minutes | no limit |
213
+ | Messenger | 15 minutes | 10 minutes |
214
+ | Google Messages | 15 minutes | 15 minutes |
215
+ | LinkedIn | 1 hour | 1 hour |
216
+ | iMessage | 15 minutes, at most 5 edits | 2 minutes |
217
+ | Discord, Slack, Google Chat, TikTok | no limit | no limit |
218
+ | X | no limit | not possible (X keeps it for the other person) |
219
+ | OpenAI Dots | no limit | not possible |
220
+ | WeChat | not possible | 2 minutes |
221
+ | LINE | not possible | 24 hours |
222
+ | Snapchat, Reddit | not possible | no limit |
223
+ | Grok Bot, Muse | not possible | not possible |
224
+
225
+ A refused edit exits 1 with `message_not_editable`, and a refused delete with
226
+ `message_not_deletable`. The error says why: not yours, not sent from Chesly (an edit), not text,
227
+ deleted, email, a network that takes none, or past the network's time limit, which it names.
228
+
229
+ `edit` prints the edited message, with its new `text` and `edited: true`. `delete` prints
230
+ `{"id":"msg_...","deleted":true}`, or "Deleted <id> for everyone in the chat." in a terminal. A
231
+ deleted message can't be brought back. Both are safe to run again: editing to the text a message
232
+ already has changes nothing, and deleting a message that is already deleted answers the same. An
233
+ account can edit or delete as many messages an hour as it can send (60 on WhatsApp, 30 elsewhere);
234
+ past that, the command exits 5 with `rate_limited` and `retry_after`. A read-only key can do
235
+ neither (403 `insufficient_scope`).
236
+
186
237
  ## Watch events
187
238
 
188
239
  ```sh
@@ -317,6 +368,8 @@ each key and to all your keys together. With `--json` it prints the API's `GET /
317
368
  | `chesly search <query> [--chat <chat>] [--network <name>] [--limit <n>]` | Searches your messages, in every chat or one (`GET /v1/messages/search`) |
318
369
  | `chesly catchup [--chats <n>] [--per-chat <n>] [--network <name>]` | Your unread chats (not muted or archived) with their latest messages, in one call (`GET /v1/catch_up`) |
319
370
  | `chesly send <chat> [text\|-] [--reply-to <msg_id>] [--file <path>\|--media-id <id>] [--wait] [--idempotency-key <key>] [--network <name>]` | Sends a message, a reply or a file (`POST /v1/media`, `POST /v1/chats/{chat_id}/messages`) |
371
+ | `chesly edit <message_id> <text\|->` | Changes the text of a message you sent from Chesly, for everyone in the chat (`PATCH /v1/messages/{message_id}`) |
372
+ | `chesly delete <message_id>` | Deletes a message you sent, from Chesly or the network's own app, for everyone in the chat (`DELETE /v1/messages/{message_id}`) |
320
373
  | `chesly watch [--chat <chat>] [--account <acct_id>] [--types <a,b>] [--networks <a,b>] [--after <evt_id>]` | Prints events as they happen, one per line (`GET /v1/events/stream`) |
321
374
  | `chesly webhooks list\|create\|delete\|rotate\|test\|deliveries` | Manages webhooks (`/v1/webhooks`) |
322
375
  | `chesly keys list\|revoke <key_id>` | Lists or revokes API keys (`/v1/keys`) |
@@ -378,14 +431,14 @@ included, on every network but email (add `--network email` for email threads):
378
431
  | 1 | error |
379
432
  | 2 | usage |
380
433
  | 3 | not signed in (no key, a malformed one, or the key was rejected) |
381
- | 4 | not found (an unknown chat, webhook or key, or a name that matches no chat), or ambiguous (a name that matches several) |
434
+ | 4 | not found (an unknown chat, message, webhook or key, or a name that matches no chat), or ambiguous (a name that matches several) |
382
435
  | 5 | not final, come back to it: rate limited (a 429: too many requests, a send cap, uploads held after a slow one, or too many open event streams), a request that took too long to arrive (a 408, such as an upload's `upload_timeout`), briefly unavailable (a 502, 503 or 504, from the API or a gateway), a first attempt still running (a 409 `idempotency_in_progress`), or a send the network didn't confirm (`delivery_unconfirmed`: check the chat before you send it again). `retry_after` says when, if the answer has it |
383
436
  | 6 | payment required: the account needs an API plan, or this period's transcription minutes are used up |
384
437
 
385
438
  - **MCP:** give Claude Code the Chesly MCP server with your key:
386
439
 
387
440
  ```sh
388
- claude mcp add --transport http chesly https://api.chesly.app/mcp \
441
+ claude mcp add --transport http chesly https://mcp.chesly.app/mcp \
389
442
  --header "Authorization: Bearer $(chesly key --reveal)"
390
443
  ```
391
444
 
package/dist/errors.js CHANGED
@@ -74,6 +74,8 @@ var API_ERROR_CODES = [
74
74
  { code: "idempotency_key_reused", status: 422, title: "This Idempotency-Key was used for a different request." },
75
75
  { code: "idempotency_in_progress", status: 409, title: "A request with this Idempotency-Key is still running." },
76
76
  { code: "message_request", status: 409, title: "This chat is a message request." },
77
+ { code: "message_not_editable", status: 409, title: "This message can't be edited." },
78
+ { code: "message_not_deletable", status: 409, title: "This message can't be deleted." },
77
79
  { code: "send_limit_reached", status: 429, title: "This account's send limit is reached." },
78
80
  { code: "text_too_long", status: 400, title: "The text is too long for this network." },
79
81
  { code: "invalid_reply_to", status: 400, title: "reply_to must be a message in this chat." },
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { STATUS_CODES } from "http";
9
9
  // package.json
10
10
  var package_default = {
11
11
  name: "chesly",
12
- version: "0.2.0",
12
+ version: "0.3.0",
13
13
  description: "Chesly CLI: your chats from the terminal and your agents",
14
14
  license: "MIT",
15
15
  type: "module",
@@ -1365,6 +1365,11 @@ function parseNetwork(value) {
1365
1365
  }
1366
1366
  return network;
1367
1367
  }
1368
+ function parseMessageId(value) {
1369
+ const id = value.trim();
1370
+ if (id === "") throw new InvalidArgumentError("Give a message ID (msg_\u2026).");
1371
+ return id;
1372
+ }
1368
1373
  function parseList(value) {
1369
1374
  const items = [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))];
1370
1375
  if (items.length === 0) throw new InvalidArgumentError("Give one or more names, separated by commas.");
@@ -1466,144 +1471,492 @@ Examples:
1466
1471
  });
1467
1472
  }
1468
1473
 
1469
- // src/commands/key.ts
1470
- function registerKey(program, io) {
1471
- program.command("key").description("Show the API key in use, masked; --reveal prints the whole key, for MCP clients").option("--reveal", "print the whole key and nothing else (as JSON only with an explicit --json)").addHelpText(
1474
+ // src/commands/delete.ts
1475
+ function registerDelete(program, io) {
1476
+ program.command("delete").description("Delete a message you sent, for everyone in the chat").argument("<message_id>", "the message: a msg_ ID from chesly send or chesly read", parseMessageId).addHelpText(
1472
1477
  "after",
1473
1478
  `
1474
- Example: add the Chesly MCP server to Claude Code
1475
- claude mcp add --transport http chesly https://api.chesly.app/mcp \\
1476
- --header "Authorization: Bearer $(chesly key --reveal)"`
1477
- ).action(async (options, command) => {
1478
- const globals = command.optsWithGlobals();
1479
- const { key, source } = await requireKey();
1480
- if (options.reveal && globals.json !== true) {
1481
- io.out(`${key}
1482
- `);
1483
- return;
1484
- }
1485
- const out = new Output(io, globals);
1486
- const data = options.reveal ? { key, source } : { ...keyHint(key), source };
1487
- out.result(data, () => `${maskKey(key)} (from ${describeSource(source)})`);
1479
+ Deletes a message you sent, from Chesly or the network's own app, for
1480
+ everyone in the chat, within the time the network allows, such as 2 days
1481
+ on WhatsApp or 24 hours on Signal. A deleted message can't be brought back.
1482
+ Someone else's message, an email, or one past the network's limit is
1483
+ refused with message_not_deletable (exit 1), and the error says why. An
1484
+ unknown ID exits 4.
1485
+
1486
+ Prints { "id", "deleted": true }, or "Deleted <id> for everyone in the
1487
+ chat." in a terminal. Deleting a message that is already deleted answers
1488
+ the same, so the command is safe to run again.
1489
+
1490
+ Example:
1491
+ chesly delete msg_7Hq2mR9xLp4vT1sK8nWz.JGV3A`
1492
+ ).action(async (messageId, _options, command) => {
1493
+ const out = new Output(io, command.optsWithGlobals());
1494
+ const { key } = await requireKey();
1495
+ await apiRequest(`/v1/messages/${encodeURIComponent(messageId)}`, { method: "DELETE", key });
1496
+ out.result({ id: messageId, deleted: true }, () => `Deleted ${messageId} for everyone in the chat.`);
1488
1497
  });
1489
1498
  }
1490
1499
 
1491
- // src/commands/keys.ts
1492
- var REVOKE_TIMEOUT_MS = 1e4;
1493
- async function revokeKey(key, fallback) {
1494
- const { prefix, last4 } = keyHint(key);
1495
- let id;
1496
- try {
1497
- const me = await apiRequest("/v1/me", { key, timeoutMs: REVOKE_TIMEOUT_MS });
1498
- if (!isMe(me)) return { id: null, prefix, last4, outcome: "active" };
1499
- id = me.key.id;
1500
- } catch (error) {
1501
- const refused = error instanceof CheslyApiError && error.status === 401;
1502
- return { id: null, prefix, last4, outcome: refused ? "gone" : "active" };
1500
+ // src/commands/send.ts
1501
+ import { randomUUID } from "crypto";
1502
+
1503
+ // src/resolve-chat.ts
1504
+ var LOOKUP_LIMIT = 10;
1505
+ var CHAT_ARGUMENT_HELP = `A <chat> is a chat ID (chat_\u2026) or a name. An exact name wins, in any case;
1506
+ so does the only partial match. No match, or several, exits 4, and JSON
1507
+ mode lists the chats a name could mean as "candidates". Names are looked up
1508
+ on every network but email; --network names the one to look in (an email
1509
+ thread's name is its subject: --network email).`;
1510
+ async function resolveChat(arg, key, options = {}) {
1511
+ const name = arg.trim();
1512
+ if (name.startsWith("chat_")) return { id: name, name: null };
1513
+ if (name === "") throw new CliError("usage_error", "Give a chat ID (chat_\u2026) or a chat name.", EXIT.USAGE);
1514
+ const answer = await apiRequest("/v1/chats", {
1515
+ key: await key(),
1516
+ query: { q: name, archived: "all", limit: LOOKUP_LIMIT, network: options.network, account_id: options.accountId }
1517
+ });
1518
+ const page = expectAnswer(answer, isChatPage, "a page of chats");
1519
+ const exact = page.chats.filter((chat) => sameName(chat.name, name));
1520
+ const candidates = exact.length > 0 ? exact : page.chats;
1521
+ const [first, ...others] = candidates;
1522
+ if (first === void 0) {
1523
+ throw new CliError("chat_not_found", `No chat matches "${name}".`, EXIT.NOT_FOUND, {
1524
+ hint: "Run `chesly chats` to list your chats, or pass a chat ID."
1525
+ });
1503
1526
  }
1504
- let outcome = await deleteKey(id, key, true);
1505
- if (outcome === "forbidden" && fallback !== void 0) outcome = await deleteKey(id, fallback, false);
1506
- return { id, prefix, last4, outcome: outcome === "forbidden" ? "active" : outcome };
1527
+ if (others.length === 0) return { id: first.id, name: first.name ?? null };
1528
+ const count2 = `${page.next_cursor ? "at least " : ""}${candidates.length}`;
1529
+ throw new CliError("ambiguous_chat", `"${name}" matches ${count2} chats. Use one of their chat IDs instead.`, EXIT.NOT_FOUND, {
1530
+ extras: { candidates },
1531
+ hint: indent(chatTable(candidates), " ")
1532
+ });
1507
1533
  }
1508
- async function deleteKey(id, using, self) {
1509
- try {
1510
- await apiRequest(`/v1/keys/${encodeURIComponent(id)}`, { method: "DELETE", key: using, timeoutMs: REVOKE_TIMEOUT_MS });
1511
- return "revoked";
1512
- } catch (error) {
1513
- if (!(error instanceof CheslyApiError)) return "active";
1514
- if (error.status === 403) return "forbidden";
1515
- if (self && (error.status === 401 || error.status === 404 && error.code === "key_not_found")) return "gone";
1516
- return "active";
1517
- }
1534
+ function sameName(chatName, name) {
1535
+ return (chatName ?? "").trim().localeCompare(name, void 0, { sensitivity: "accent" }) === 0;
1518
1536
  }
1519
- async function checkKey(key) {
1520
- const { prefix, last4 } = keyHint(key);
1537
+
1538
+ // src/upload.ts
1539
+ import { openAsBlob } from "fs";
1540
+ import { stat } from "fs/promises";
1541
+ import { basename, extname } from "path";
1542
+ var MAX_UPLOAD_BYTES = 5e7;
1543
+ var MIME_TYPES = {
1544
+ jpg: "image/jpeg",
1545
+ jpeg: "image/jpeg",
1546
+ png: "image/png",
1547
+ gif: "image/gif",
1548
+ webp: "image/webp",
1549
+ heic: "image/heic",
1550
+ heif: "image/heif",
1551
+ avif: "image/avif",
1552
+ bmp: "image/bmp",
1553
+ tif: "image/tiff",
1554
+ tiff: "image/tiff",
1555
+ svg: "image/svg+xml",
1556
+ mp4: "video/mp4",
1557
+ m4v: "video/x-m4v",
1558
+ mov: "video/quicktime",
1559
+ webm: "video/webm",
1560
+ mkv: "video/x-matroska",
1561
+ "3gp": "video/3gpp",
1562
+ mp3: "audio/mpeg",
1563
+ m4a: "audio/mp4",
1564
+ aac: "audio/aac",
1565
+ wav: "audio/wav",
1566
+ flac: "audio/flac",
1567
+ ogg: "audio/ogg",
1568
+ oga: "audio/ogg",
1569
+ opus: "audio/ogg",
1570
+ amr: "audio/amr",
1571
+ pdf: "application/pdf",
1572
+ txt: "text/plain",
1573
+ md: "text/markdown",
1574
+ csv: "text/csv",
1575
+ json: "application/json",
1576
+ vcf: "text/vcard",
1577
+ ics: "text/calendar",
1578
+ zip: "application/zip",
1579
+ doc: "application/msword",
1580
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1581
+ xls: "application/vnd.ms-excel",
1582
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1583
+ ppt: "application/vnd.ms-powerpoint",
1584
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
1585
+ };
1586
+ var SLOWEST_UPLOAD_BYTES_PER_SECOND = 131072;
1587
+ async function readUpload(path) {
1521
1588
  try {
1522
- const me = await apiRequest("/v1/me", { key, timeoutMs: REVOKE_TIMEOUT_MS });
1523
- return { id: isMe(me) ? me.key.id : null, prefix, last4, outcome: "active" };
1589
+ const info = await stat(path);
1590
+ if (!info.isFile()) throw new CliError("file_unreadable", `${path} is not a file.`, EXIT.USAGE);
1591
+ if (info.size > MAX_UPLOAD_BYTES) {
1592
+ throw new CliError("media_too_large", `${path} is over 50 MB, the most a message can carry.`);
1593
+ }
1594
+ return { blob: await openAsBlob(path, { type: mimeTypeOf(path) }), name: basename(path), size: info.size };
1524
1595
  } catch (error) {
1525
- const refused = error instanceof CheslyApiError && error.status === 401;
1526
- return { id: null, prefix, last4, outcome: refused ? "gone" : "active" };
1596
+ if (error instanceof CliError) throw error;
1597
+ throw new CliError("file_unreadable", `Can't read ${path}: ${reasonOf2(error)}`, EXIT.USAGE);
1527
1598
  }
1528
1599
  }
1529
- function stillActiveMessage(revocation, which = "This key") {
1530
- const id = revocation.id === null ? "" : `, id ${revocation.id}`;
1531
- return `${which} (${revocation.prefix}\u2026${revocation.last4}${id}) is still active; revoke it in the dashboard at web.chesly.app/api/keys.`;
1532
- }
1533
- function registerKeys(program, io) {
1534
- const keys = program.command("keys").description("List your API keys, or revoke one").addHelpText(
1535
- "after",
1536
- `
1537
- There is no keys create. New keys come from chesly login, or from the dashboard at
1538
- https://web.chesly.app/api/keys. chesly key shows the key this CLI uses.
1539
-
1540
- Examples:
1541
- chesly keys list
1542
- chesly keys revoke 0b5c9a52-6f1e-4c41-9a43-2b7f0d0e1a07`
1543
- );
1544
- keys.command("list").description("List your active API keys, marking the one this CLI uses").addHelpText(
1545
- "after",
1546
- `
1547
- Prints the API's { "keys": [...] }, or a table in a terminal. A key shows only
1548
- its first 12 and last 4 characters, never the whole key.
1549
-
1550
- Example:
1551
- chesly keys list --json`
1552
- ).action(async (_options, command) => {
1553
- const out = new Output(io, command.optsWithGlobals());
1554
- const { key } = await requireKey();
1555
- const answer = expectAnswer(await apiRequest("/v1/keys", { key }), isKeyList, "a list of API keys");
1556
- out.result(answer, () => answer.keys.length === 0 ? "No API keys." : keyTable(answer.keys, keyHint(key)));
1557
- });
1558
- keys.command("revoke").description("Revoke an API key; its next request is refused").argument("<key_id>", "the key: an ID from chesly keys list").addHelpText(
1559
- "after",
1560
- `
1561
- Prints { "id", "revoked": true, "in_use" }, or a sentence in a terminal.
1562
- "in_use" says it was the key this CLI uses, which then needs chesly login.
1563
- An unknown ID exits 4; a read-only key can't revoke.
1564
-
1565
- Example:
1566
- chesly keys revoke 0b5c9a52-6f1e-4c41-9a43-2b7f0d0e1a07`
1567
- ).action(async (keyId, _options, command) => {
1568
- const out = new Output(io, command.optsWithGlobals());
1569
- const { key, source } = await requireKey();
1570
- const id = keyId.trim();
1571
- const me = expectAnswer(await apiRequest("/v1/me", { key }), isMe, "the details of this key");
1572
- await apiRequest(`/v1/keys/${encodeURIComponent(id)}`, { method: "DELETE", key });
1573
- const inUse = me.key.id === id;
1574
- out.result({ id, revoked: true, in_use: inUse }, () => {
1575
- if (!inUse) return `Revoked ${id}.`;
1576
- if (source === "env") {
1577
- return `Revoked ${id}. This was the key this CLI uses, from CHESLY_API_KEY: put another key there, or unset it and run chesly login.`;
1578
- }
1579
- return `Revoked ${id}. This was the key this CLI uses; run chesly login.`;
1580
- });
1600
+ async function uploadFile(file, key) {
1601
+ const form = new FormData();
1602
+ form.append("file", file.blob, file.name);
1603
+ const upload = await apiRequest("/v1/media", {
1604
+ key,
1605
+ form,
1606
+ timeoutMs: 3e4 + Math.ceil(file.size / SLOWEST_UPLOAD_BYTES_PER_SECOND) * 1e3
1581
1607
  });
1608
+ if (!isMediaUpload(upload)) throw new CliError("invalid_response", "The API sent no media ID for the upload.");
1609
+ return upload;
1610
+ }
1611
+ function mimeTypeOf(path) {
1612
+ return MIME_TYPES[extname(path).slice(1).toLowerCase()] ?? "application/octet-stream";
1613
+ }
1614
+ function reasonOf2(error) {
1615
+ const { code, message } = error ?? {};
1616
+ if (code === "ENOENT") return "no such file";
1617
+ if (code === "EACCES" || code === "EPERM") return "permission denied";
1618
+ return typeof message === "string" && message !== "" ? message : "it failed";
1582
1619
  }
1583
1620
 
1584
- // src/commands/login.ts
1585
- import { spawn as spawn2 } from "child_process";
1586
- import { hostname } from "os";
1587
- function registerLogin(program, io) {
1588
- program.command("login").description("Sign in: approve this computer on web.chesly.app, or store a key with --key").option("--key <key>", "check an API key with the API, then store it (no browser); - reads it from stdin").option("--no-browser", "print the link only, without opening a browser").option("--force", "sign in with a new key even when the stored one works (which is then revoked)").option("--wait", "finish the sign-in --no-wait started: wait for the approval, then store the key").option("--no-wait", "start a sign-in, print its link and code, and exit at once").addHelpText(
1621
+ // src/commands/send.ts
1622
+ var WAIT_MS = 3e4;
1623
+ var POLL_MS = 1e3;
1624
+ var MIN_POLL_MS = 1e3;
1625
+ function registerSend(program, io) {
1626
+ program.command("send").description("Send a message to one of your chats: text, a reply, or a file with a caption").argument("<chat>", "a chat ID (chat_\u2026) or a chat name").argument("[text]", "the text to send; - reads it from stdin").option("--reply-to <msg_id>", "reply to this message: a msg_ ID from chesly read").option("--file <path>", "attach this file (at most 50 MB); the text becomes its caption").option("--media-id <id>", "attach a file uploaded before (a media_ ID), as a retry of a file send does").option("--wait", "wait up to 30 s until the network has it: sent, delivered or failed").option(
1627
+ "--idempotency-key <key>",
1628
+ "send at most once per key, however often the command runs (default: a new key)",
1629
+ parseIdempotencyKey
1630
+ ).option("--network <name>", "look the chat name up on this network: email for an email thread", parseNetwork).addHelpText(
1589
1631
  "after",
1590
1632
  `
1591
- When the key it stored still works, chesly login says "Already signed in"
1592
- and stops: each sign-in makes a key, and an account has 25 at most. --force
1593
- signs in anyway, and revokes the stored keys the new one replaces (any other
1594
- replaced key that still works is named in a key_still_active warning);
1595
- chesly logout revokes the stored key.
1633
+ ${CHAT_ARGUMENT_HELP}
1596
1634
 
1597
- Without --key, chesly login prints a link and a code, opens your browser
1598
- (wherever there is one to show: not over SSH, not in CI, not with
1599
- --no-browser), and waits until you approve the code on web.chesly.app.
1600
- It never reads input. In JSON mode the link and the code are one line on
1601
- stderr, and the result is one object on stdout:
1602
- {"verification_uri_complete":"\u2026","user_code":"ABCD-EFGH","expires_in":600}
1603
- {"status":"signed_in","stored_in":"keychain","key":{\u2026}}
1635
+ Prints the message the API answered: its JSON, or "Sent to <chat> \xB7 <status>"
1636
+ in a terminal. The status is queued until the network takes the message;
1637
+ with --wait the command waits up to 30 s in all for sent, delivered or failed
1638
+ (it asks once a second, or later when a refused ask's Retry-After says so,
1639
+ and each ask counts as an API call). A failure the network confirms exits 1
1640
+ (delivery_failed) with the reason. One it didn't confirm reads "unconfirmed":
1641
+ the message may have been delivered, so check the chat before you send it
1642
+ again; --wait goes on asking, and if it stays unconfirmed the command exits 5
1643
+ (delivery_unconfirmed). Once the message went out it is always printed, and
1644
+ following it failing is only a warning on stderr (delivery_wait_failed).
1604
1645
 
1605
- Agents: a tool that shows a command's output only once it ends can sign in in
1606
- two steps. chesly login --no-wait prints the link and the code and exits:
1646
+ Every send carries an Idempotency-Key, and the CLI's own retries (after a
1647
+ network error, a 502, 503 or 504, a 429, or while a first attempt is still
1648
+ running) reuse it, so the message goes out at most once. Each waits for the
1649
+ answer's Retry-After, at most 10 s, or 1 s and then 2 s without one; a 429
1650
+ that lifts later (a send cap) exits 5 at once. To retry later without
1651
+ sending twice, pass the same --idempotency-key again. A file send that gives
1652
+ up also names its upload: retry it with --media-id <id> instead of --file, as
1653
+ a new upload would make another media ID, which the same key refuses (422).
1654
+
1655
+ Pass the text on stdin with a quoted heredoc (- <<'EOF'), not as a
1656
+ double-quoted argument: inside double quotes the shell still expands $ and
1657
+ backticks, while the quoted EOF keeps the text exactly as written.
1658
+
1659
+ Examples:
1660
+ chesly send "Mom" - --wait <<'EOF'
1661
+ On my way
1662
+ EOF
1663
+ chesly send "Invoice 42" - --network email <<'EOF'
1664
+ Paid, thank you.
1665
+ EOF
1666
+ chesly send chat_7Hq2mR9xLp4vT1sK8nWz - --file report.pdf <<'EOF'
1667
+ The report is attached.
1668
+ EOF`
1669
+ ).action(async (chat, text, options, command) => {
1670
+ const out = new Output(io, command.optsWithGlobals());
1671
+ const body = await messageText2(text, io);
1672
+ if (options.file !== void 0 && options.mediaId !== void 0) {
1673
+ throw new CliError("usage_error", "A message carries one attachment: give --file or --media-id, not both.", EXIT.USAGE);
1674
+ }
1675
+ if (body === void 0 && options.file === void 0 && options.mediaId === void 0) {
1676
+ throw new CliError("usage_error", "Give the text to send, - to read it from stdin, or --file.", EXIT.USAGE);
1677
+ }
1678
+ const file = options.file === void 0 ? void 0 : await readUpload(options.file);
1679
+ const key = keyOnce();
1680
+ const target = await resolveChat(chat, key, { network: options.network });
1681
+ const idempotencyKey = options.idempotencyKey ?? randomUUID();
1682
+ const uploaded = file === void 0 ? void 0 : await uploadFile(file, await key());
1683
+ const mediaId = uploaded?.id ?? options.mediaId;
1684
+ const again = {
1685
+ flags: uploaded === void 0 ? `--idempotency-key ${idempotencyKey}` : `--media-id ${shellQuote(uploaded.id)} --idempotency-key ${idempotencyKey} (instead of --file)`,
1686
+ extras: { idempotency_key: idempotencyKey, ...mediaId === void 0 ? {} : { media_id: mediaId } }
1687
+ };
1688
+ const answer = await idempotentPost(`/v1/chats/${encodeURIComponent(target.id)}/messages`, {
1689
+ key: await key(),
1690
+ idempotencyKey,
1691
+ body: {
1692
+ ...body === void 0 ? {} : { text: body },
1693
+ ...options.replyTo === void 0 ? {} : { reply_to: options.replyTo },
1694
+ ...mediaId === void 0 ? {} : { media_id: mediaId }
1695
+ },
1696
+ again
1697
+ });
1698
+ if (!isMessage(answer)) {
1699
+ throw new AnnotatedError(
1700
+ new CliError("invalid_response", "The API sent no message for the send."),
1701
+ again.extras,
1702
+ `It may have gone out. Run the command again with ${again.flags} to see the API's answer.`
1703
+ );
1704
+ }
1705
+ const waited = options.wait ? await waitForDelivery(answer, await key()) : { message: answer, ranOut: false, failure: void 0 };
1706
+ const { message } = waited;
1707
+ const state = deliveryState(message.delivery);
1708
+ out.result(message, () => sentLine(target, message));
1709
+ if (waited.failure !== void 0) {
1710
+ out.warn(
1711
+ "delivery_wait_failed",
1712
+ `The message was sent, but following its delivery failed (${waited.failure}). chesly read shows it, and the command run again with ${again.flags} shows the API's answer.`,
1713
+ again.extras
1714
+ );
1715
+ } else if (waited.ranOut && state === "queued") {
1716
+ out.note(`Still queued after ${WAIT_MS / 1e3} s.`);
1717
+ }
1718
+ const delivery = message.delivery;
1719
+ if (state === "failed") {
1720
+ throw new CliError("delivery_failed", delivery?.error?.message ?? "The network did not take the message.", EXIT.ERROR, {
1721
+ extras: { message_id: message.id, delivery }
1722
+ });
1723
+ }
1724
+ if (state === "unconfirmed") {
1725
+ throw new CliError(
1726
+ "delivery_unconfirmed",
1727
+ "The network didn't confirm the message, so it may have been delivered. Check the chat before you send it again.",
1728
+ EXIT.RETRY_LATER,
1729
+ { extras: { message_id: message.id, delivery } }
1730
+ );
1731
+ }
1732
+ });
1733
+ }
1734
+ async function messageText2(text, io) {
1735
+ if (text !== "-") return text === "" ? void 0 : text;
1736
+ if (io.stdin.isTTY) {
1737
+ throw new CliError(
1738
+ "usage_error",
1739
+ "The text - reads stdin, and stdin is a terminal. Pipe the text in, or give it as an argument.",
1740
+ EXIT.USAGE
1741
+ );
1742
+ }
1743
+ const piped = (await io.stdin.read()).replace(/(?:\r?\n)+$/, "");
1744
+ return piped === "" ? void 0 : piped;
1745
+ }
1746
+ async function waitForDelivery(sent, key) {
1747
+ let message = sent;
1748
+ let failure;
1749
+ let pauseMs = POLL_MS;
1750
+ const deadline = Date.now() + WAIT_MS;
1751
+ while (!settled(message)) {
1752
+ if (deadline - Date.now() < pauseMs + MIN_POLL_MS) return { message, ranOut: failure === void 0, failure };
1753
+ await sleep(pauseMs);
1754
+ pauseMs = POLL_MS;
1755
+ try {
1756
+ const timeoutMs = deadline - Date.now();
1757
+ const polled = await apiRequest(`/v1/messages/${encodeURIComponent(message.id)}`, { key, timeoutMs });
1758
+ if (!isMessage(polled)) return { message, ranOut: false, failure: "the API sent an answer that is not a message" };
1759
+ message = polled;
1760
+ failure = void 0;
1761
+ } catch (error) {
1762
+ if (error instanceof CheslyNetworkError && error.timedOut) return { message, ranOut: true, failure: void 0 };
1763
+ failure = pollFailure(error);
1764
+ const passing = isTransient(error) || error instanceof CheslyApiError && error.status === 429;
1765
+ if (!passing) return { message, ranOut: false, failure };
1766
+ if (error instanceof CheslyApiError && error.retryAfter !== void 0) {
1767
+ pauseMs = Math.max(POLL_MS, error.retryAfter * 1e3);
1768
+ }
1769
+ }
1770
+ }
1771
+ return { message, ranOut: false, failure: void 0 };
1772
+ }
1773
+ function pollFailure(error) {
1774
+ if (error instanceof CheslyApiError) return `${error.status} ${error.code}`;
1775
+ if (error instanceof CheslyNetworkError) return "no answer from the API";
1776
+ return "an unexpected error";
1777
+ }
1778
+ function settled(message) {
1779
+ const state = deliveryState(message.delivery);
1780
+ return state === void 0 || state === "sent" || state === "delivered" || state === "failed";
1781
+ }
1782
+
1783
+ // src/commands/edit.ts
1784
+ function registerEdit(program, io) {
1785
+ program.command("edit").description("Change the text of a message you sent from Chesly, for everyone in the chat").argument("<message_id>", "the message: a msg_ ID from chesly send or chesly read", parseMessageId).argument("<text>", "the new text; - reads it from stdin").addHelpText(
1786
+ "after",
1787
+ `
1788
+ Changes the text of a message you sent from Chesly (its apps or the API),
1789
+ for everyone in the chat. Text messages only, within the time the network
1790
+ allows edits, such as 15 minutes on WhatsApp, 24 hours on Signal or 48
1791
+ hours on Telegram. A message you sent in the network's own app, an email,
1792
+ or one past the network's limit is refused with message_not_editable
1793
+ (exit 1), and the error says why. An unknown ID exits 4.
1794
+
1795
+ Prints the edited message: its JSON, or the message as chesly read shows it
1796
+ in a terminal. Editing to the text the message already has changes nothing,
1797
+ so the command is safe to run again.
1798
+
1799
+ Pass the text on stdin with a quoted heredoc (- <<'EOF'), not as a
1800
+ double-quoted argument: inside double quotes the shell still expands $ and
1801
+ backticks, while the quoted EOF keeps the text exactly as written.
1802
+
1803
+ Example:
1804
+ chesly edit msg_7Hq2mR9xLp4vT1sK8nWz.JGV3A - <<'EOF'
1805
+ On my way, 10 minutes
1806
+ EOF`
1807
+ ).action(async (messageId, text, _options, command) => {
1808
+ const out = new Output(io, command.optsWithGlobals());
1809
+ const body = await messageText2(text, io);
1810
+ if (body === void 0) throw new CliError("usage_error", "Give the new text, or - to read it from stdin.", EXIT.USAGE);
1811
+ const { key } = await requireKey();
1812
+ const answer = await apiRequest(`/v1/messages/${encodeURIComponent(messageId)}`, {
1813
+ method: "PATCH",
1814
+ key,
1815
+ body: { text: body }
1816
+ });
1817
+ const message = expectAnswer(answer, isMessage, "a message");
1818
+ out.result(message, () => transcript([message]));
1819
+ });
1820
+ }
1821
+
1822
+ // src/commands/key.ts
1823
+ function registerKey(program, io) {
1824
+ program.command("key").description("Show the API key in use, masked; --reveal prints the whole key, for MCP clients").option("--reveal", "print the whole key and nothing else (as JSON only with an explicit --json)").addHelpText(
1825
+ "after",
1826
+ `
1827
+ Example: add the Chesly MCP server to Claude Code
1828
+ claude mcp add --transport http chesly https://mcp.chesly.app/mcp \\
1829
+ --header "Authorization: Bearer $(chesly key --reveal)"`
1830
+ ).action(async (options, command) => {
1831
+ const globals = command.optsWithGlobals();
1832
+ const { key, source } = await requireKey();
1833
+ if (options.reveal && globals.json !== true) {
1834
+ io.out(`${key}
1835
+ `);
1836
+ return;
1837
+ }
1838
+ const out = new Output(io, globals);
1839
+ const data = options.reveal ? { key, source } : { ...keyHint(key), source };
1840
+ out.result(data, () => `${maskKey(key)} (from ${describeSource(source)})`);
1841
+ });
1842
+ }
1843
+
1844
+ // src/commands/keys.ts
1845
+ var REVOKE_TIMEOUT_MS = 1e4;
1846
+ async function revokeKey(key, fallback) {
1847
+ const { prefix, last4 } = keyHint(key);
1848
+ let id;
1849
+ try {
1850
+ const me = await apiRequest("/v1/me", { key, timeoutMs: REVOKE_TIMEOUT_MS });
1851
+ if (!isMe(me)) return { id: null, prefix, last4, outcome: "active" };
1852
+ id = me.key.id;
1853
+ } catch (error) {
1854
+ const refused = error instanceof CheslyApiError && error.status === 401;
1855
+ return { id: null, prefix, last4, outcome: refused ? "gone" : "active" };
1856
+ }
1857
+ let outcome = await deleteKey(id, key, true);
1858
+ if (outcome === "forbidden" && fallback !== void 0) outcome = await deleteKey(id, fallback, false);
1859
+ return { id, prefix, last4, outcome: outcome === "forbidden" ? "active" : outcome };
1860
+ }
1861
+ async function deleteKey(id, using, self) {
1862
+ try {
1863
+ await apiRequest(`/v1/keys/${encodeURIComponent(id)}`, { method: "DELETE", key: using, timeoutMs: REVOKE_TIMEOUT_MS });
1864
+ return "revoked";
1865
+ } catch (error) {
1866
+ if (!(error instanceof CheslyApiError)) return "active";
1867
+ if (error.status === 403) return "forbidden";
1868
+ if (self && (error.status === 401 || error.status === 404 && error.code === "key_not_found")) return "gone";
1869
+ return "active";
1870
+ }
1871
+ }
1872
+ async function checkKey(key) {
1873
+ const { prefix, last4 } = keyHint(key);
1874
+ try {
1875
+ const me = await apiRequest("/v1/me", { key, timeoutMs: REVOKE_TIMEOUT_MS });
1876
+ return { id: isMe(me) ? me.key.id : null, prefix, last4, outcome: "active" };
1877
+ } catch (error) {
1878
+ const refused = error instanceof CheslyApiError && error.status === 401;
1879
+ return { id: null, prefix, last4, outcome: refused ? "gone" : "active" };
1880
+ }
1881
+ }
1882
+ function stillActiveMessage(revocation, which = "This key") {
1883
+ const id = revocation.id === null ? "" : `, id ${revocation.id}`;
1884
+ return `${which} (${revocation.prefix}\u2026${revocation.last4}${id}) is still active; revoke it in the dashboard at web.chesly.app/api/keys.`;
1885
+ }
1886
+ function registerKeys(program, io) {
1887
+ const keys = program.command("keys").description("List your API keys, or revoke one").addHelpText(
1888
+ "after",
1889
+ `
1890
+ There is no keys create. New keys come from chesly login, or from the dashboard at
1891
+ https://web.chesly.app/api/keys. chesly key shows the key this CLI uses.
1892
+
1893
+ Examples:
1894
+ chesly keys list
1895
+ chesly keys revoke 0b5c9a52-6f1e-4c41-9a43-2b7f0d0e1a07`
1896
+ );
1897
+ keys.command("list").description("List your active API keys, marking the one this CLI uses").addHelpText(
1898
+ "after",
1899
+ `
1900
+ Prints the API's { "keys": [...] }, or a table in a terminal. A key shows only
1901
+ its first 12 and last 4 characters, never the whole key.
1902
+
1903
+ Example:
1904
+ chesly keys list --json`
1905
+ ).action(async (_options, command) => {
1906
+ const out = new Output(io, command.optsWithGlobals());
1907
+ const { key } = await requireKey();
1908
+ const answer = expectAnswer(await apiRequest("/v1/keys", { key }), isKeyList, "a list of API keys");
1909
+ out.result(answer, () => answer.keys.length === 0 ? "No API keys." : keyTable(answer.keys, keyHint(key)));
1910
+ });
1911
+ keys.command("revoke").description("Revoke an API key; its next request is refused").argument("<key_id>", "the key: an ID from chesly keys list").addHelpText(
1912
+ "after",
1913
+ `
1914
+ Prints { "id", "revoked": true, "in_use" }, or a sentence in a terminal.
1915
+ "in_use" says it was the key this CLI uses, which then needs chesly login.
1916
+ An unknown ID exits 4; a read-only key can't revoke.
1917
+
1918
+ Example:
1919
+ chesly keys revoke 0b5c9a52-6f1e-4c41-9a43-2b7f0d0e1a07`
1920
+ ).action(async (keyId, _options, command) => {
1921
+ const out = new Output(io, command.optsWithGlobals());
1922
+ const { key, source } = await requireKey();
1923
+ const id = keyId.trim();
1924
+ const me = expectAnswer(await apiRequest("/v1/me", { key }), isMe, "the details of this key");
1925
+ await apiRequest(`/v1/keys/${encodeURIComponent(id)}`, { method: "DELETE", key });
1926
+ const inUse = me.key.id === id;
1927
+ out.result({ id, revoked: true, in_use: inUse }, () => {
1928
+ if (!inUse) return `Revoked ${id}.`;
1929
+ if (source === "env") {
1930
+ return `Revoked ${id}. This was the key this CLI uses, from CHESLY_API_KEY: put another key there, or unset it and run chesly login.`;
1931
+ }
1932
+ return `Revoked ${id}. This was the key this CLI uses; run chesly login.`;
1933
+ });
1934
+ });
1935
+ }
1936
+
1937
+ // src/commands/login.ts
1938
+ import { spawn as spawn2 } from "child_process";
1939
+ import { hostname } from "os";
1940
+ function registerLogin(program, io) {
1941
+ program.command("login").description("Sign in: approve this computer on web.chesly.app, or store a key with --key").option("--key <key>", "check an API key with the API, then store it (no browser); - reads it from stdin").option("--no-browser", "print the link only, without opening a browser").option("--force", "sign in with a new key even when the stored one works (which is then revoked)").option("--wait", "finish the sign-in --no-wait started: wait for the approval, then store the key").option("--no-wait", "start a sign-in, print its link and code, and exit at once").addHelpText(
1942
+ "after",
1943
+ `
1944
+ When the key it stored still works, chesly login says "Already signed in"
1945
+ and stops: each sign-in makes a key, and an account has 25 at most. --force
1946
+ signs in anyway, and revokes the stored keys the new one replaces (any other
1947
+ replaced key that still works is named in a key_still_active warning);
1948
+ chesly logout revokes the stored key.
1949
+
1950
+ Without --key, chesly login prints a link and a code, opens your browser
1951
+ (wherever there is one to show: not over SSH, not in CI, not with
1952
+ --no-browser), and waits until you approve the code on web.chesly.app.
1953
+ It never reads input. In JSON mode the link and the code are one line on
1954
+ stderr, and the result is one object on stdout:
1955
+ {"verification_uri_complete":"\u2026","user_code":"ABCD-EFGH","expires_in":600}
1956
+ {"status":"signed_in","stored_in":"keychain","key":{\u2026}}
1957
+
1958
+ Agents: a tool that shows a command's output only once it ends can sign in in
1959
+ two steps. chesly login --no-wait prints the link and the code and exits:
1607
1960
  {"status":"pending","verification_uri_complete":"\u2026","user_code":"\u2026","expires_in":600}
1608
1961
  Show them to your person, then run chesly login --wait, which waits for the
1609
1962
  approval and stores the key. A --wait cut short can run again until the code
@@ -1962,48 +2315,13 @@ Example:
1962
2315
  return lines.join("\n");
1963
2316
  });
1964
2317
  if (out.json) {
1965
- for (const revocation of stillActive) {
1966
- const { id, prefix, last4 } = revocation;
1967
- out.warn("key_still_active", stillActiveMessage(revocation), { id, prefix, last4 });
1968
- }
1969
- }
1970
- });
1971
- }
1972
-
1973
- // src/resolve-chat.ts
1974
- var LOOKUP_LIMIT = 10;
1975
- var CHAT_ARGUMENT_HELP = `A <chat> is a chat ID (chat_\u2026) or a name. An exact name wins, in any case;
1976
- so does the only partial match. No match, or several, exits 4, and JSON
1977
- mode lists the chats a name could mean as "candidates". Names are looked up
1978
- on every network but email; --network names the one to look in (an email
1979
- thread's name is its subject: --network email).`;
1980
- async function resolveChat(arg, key, options = {}) {
1981
- const name = arg.trim();
1982
- if (name.startsWith("chat_")) return { id: name, name: null };
1983
- if (name === "") throw new CliError("usage_error", "Give a chat ID (chat_\u2026) or a chat name.", EXIT.USAGE);
1984
- const answer = await apiRequest("/v1/chats", {
1985
- key: await key(),
1986
- query: { q: name, archived: "all", limit: LOOKUP_LIMIT, network: options.network, account_id: options.accountId }
1987
- });
1988
- const page = expectAnswer(answer, isChatPage, "a page of chats");
1989
- const exact = page.chats.filter((chat) => sameName(chat.name, name));
1990
- const candidates = exact.length > 0 ? exact : page.chats;
1991
- const [first, ...others] = candidates;
1992
- if (first === void 0) {
1993
- throw new CliError("chat_not_found", `No chat matches "${name}".`, EXIT.NOT_FOUND, {
1994
- hint: "Run `chesly chats` to list your chats, or pass a chat ID."
1995
- });
1996
- }
1997
- if (others.length === 0) return { id: first.id, name: first.name ?? null };
1998
- const count2 = `${page.next_cursor ? "at least " : ""}${candidates.length}`;
1999
- throw new CliError("ambiguous_chat", `"${name}" matches ${count2} chats. Use one of their chat IDs instead.`, EXIT.NOT_FOUND, {
2000
- extras: { candidates },
2001
- hint: indent(chatTable(candidates), " ")
2318
+ for (const revocation of stillActive) {
2319
+ const { id, prefix, last4 } = revocation;
2320
+ out.warn("key_still_active", stillActiveMessage(revocation), { id, prefix, last4 });
2321
+ }
2322
+ }
2002
2323
  });
2003
2324
  }
2004
- function sameName(chatName, name) {
2005
- return (chatName ?? "").trim().localeCompare(name, void 0, { sensitivity: "accent" }) === 0;
2006
- }
2007
2325
 
2008
2326
  // src/commands/read.ts
2009
2327
  function registerRead(program, io) {
@@ -2067,254 +2385,6 @@ Examples:
2067
2385
  });
2068
2386
  }
2069
2387
 
2070
- // src/commands/send.ts
2071
- import { randomUUID } from "crypto";
2072
-
2073
- // src/upload.ts
2074
- import { openAsBlob } from "fs";
2075
- import { stat } from "fs/promises";
2076
- import { basename, extname } from "path";
2077
- var MAX_UPLOAD_BYTES = 5e7;
2078
- var MIME_TYPES = {
2079
- jpg: "image/jpeg",
2080
- jpeg: "image/jpeg",
2081
- png: "image/png",
2082
- gif: "image/gif",
2083
- webp: "image/webp",
2084
- heic: "image/heic",
2085
- heif: "image/heif",
2086
- avif: "image/avif",
2087
- bmp: "image/bmp",
2088
- tif: "image/tiff",
2089
- tiff: "image/tiff",
2090
- svg: "image/svg+xml",
2091
- mp4: "video/mp4",
2092
- m4v: "video/x-m4v",
2093
- mov: "video/quicktime",
2094
- webm: "video/webm",
2095
- mkv: "video/x-matroska",
2096
- "3gp": "video/3gpp",
2097
- mp3: "audio/mpeg",
2098
- m4a: "audio/mp4",
2099
- aac: "audio/aac",
2100
- wav: "audio/wav",
2101
- flac: "audio/flac",
2102
- ogg: "audio/ogg",
2103
- oga: "audio/ogg",
2104
- opus: "audio/ogg",
2105
- amr: "audio/amr",
2106
- pdf: "application/pdf",
2107
- txt: "text/plain",
2108
- md: "text/markdown",
2109
- csv: "text/csv",
2110
- json: "application/json",
2111
- vcf: "text/vcard",
2112
- ics: "text/calendar",
2113
- zip: "application/zip",
2114
- doc: "application/msword",
2115
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2116
- xls: "application/vnd.ms-excel",
2117
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2118
- ppt: "application/vnd.ms-powerpoint",
2119
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
2120
- };
2121
- var SLOWEST_UPLOAD_BYTES_PER_SECOND = 131072;
2122
- async function readUpload(path) {
2123
- try {
2124
- const info = await stat(path);
2125
- if (!info.isFile()) throw new CliError("file_unreadable", `${path} is not a file.`, EXIT.USAGE);
2126
- if (info.size > MAX_UPLOAD_BYTES) {
2127
- throw new CliError("media_too_large", `${path} is over 50 MB, the most a message can carry.`);
2128
- }
2129
- return { blob: await openAsBlob(path, { type: mimeTypeOf(path) }), name: basename(path), size: info.size };
2130
- } catch (error) {
2131
- if (error instanceof CliError) throw error;
2132
- throw new CliError("file_unreadable", `Can't read ${path}: ${reasonOf2(error)}`, EXIT.USAGE);
2133
- }
2134
- }
2135
- async function uploadFile(file, key) {
2136
- const form = new FormData();
2137
- form.append("file", file.blob, file.name);
2138
- const upload = await apiRequest("/v1/media", {
2139
- key,
2140
- form,
2141
- timeoutMs: 3e4 + Math.ceil(file.size / SLOWEST_UPLOAD_BYTES_PER_SECOND) * 1e3
2142
- });
2143
- if (!isMediaUpload(upload)) throw new CliError("invalid_response", "The API sent no media ID for the upload.");
2144
- return upload;
2145
- }
2146
- function mimeTypeOf(path) {
2147
- return MIME_TYPES[extname(path).slice(1).toLowerCase()] ?? "application/octet-stream";
2148
- }
2149
- function reasonOf2(error) {
2150
- const { code, message } = error ?? {};
2151
- if (code === "ENOENT") return "no such file";
2152
- if (code === "EACCES" || code === "EPERM") return "permission denied";
2153
- return typeof message === "string" && message !== "" ? message : "it failed";
2154
- }
2155
-
2156
- // src/commands/send.ts
2157
- var WAIT_MS = 3e4;
2158
- var POLL_MS = 1e3;
2159
- var MIN_POLL_MS = 1e3;
2160
- function registerSend(program, io) {
2161
- program.command("send").description("Send a message to one of your chats: text, a reply, or a file with a caption").argument("<chat>", "a chat ID (chat_\u2026) or a chat name").argument("[text]", "the text to send; - reads it from stdin").option("--reply-to <msg_id>", "reply to this message: a msg_ ID from chesly read").option("--file <path>", "attach this file (at most 50 MB); the text becomes its caption").option("--media-id <id>", "attach a file uploaded before (a media_ ID), as a retry of a file send does").option("--wait", "wait up to 30 s until the network has it: sent, delivered or failed").option(
2162
- "--idempotency-key <key>",
2163
- "send at most once per key, however often the command runs (default: a new key)",
2164
- parseIdempotencyKey
2165
- ).option("--network <name>", "look the chat name up on this network: email for an email thread", parseNetwork).addHelpText(
2166
- "after",
2167
- `
2168
- ${CHAT_ARGUMENT_HELP}
2169
-
2170
- Prints the message the API answered: its JSON, or "Sent to <chat> \xB7 <status>"
2171
- in a terminal. The status is queued until the network takes the message;
2172
- with --wait the command waits up to 30 s in all for sent, delivered or failed
2173
- (it asks once a second, or later when a refused ask's Retry-After says so,
2174
- and each ask counts as an API call). A failure the network confirms exits 1
2175
- (delivery_failed) with the reason. One it didn't confirm reads "unconfirmed":
2176
- the message may have been delivered, so check the chat before you send it
2177
- again; --wait goes on asking, and if it stays unconfirmed the command exits 5
2178
- (delivery_unconfirmed). Once the message went out it is always printed, and
2179
- following it failing is only a warning on stderr (delivery_wait_failed).
2180
-
2181
- Every send carries an Idempotency-Key, and the CLI's own retries (after a
2182
- network error, a 502, 503 or 504, a 429, or while a first attempt is still
2183
- running) reuse it, so the message goes out at most once. Each waits for the
2184
- answer's Retry-After, at most 10 s, or 1 s and then 2 s without one; a 429
2185
- that lifts later (a send cap) exits 5 at once. To retry later without
2186
- sending twice, pass the same --idempotency-key again. A file send that gives
2187
- up also names its upload: retry it with --media-id <id> instead of --file, as
2188
- a new upload would make another media ID, which the same key refuses (422).
2189
-
2190
- Pass the text on stdin with a quoted heredoc (- <<'EOF'), not as a
2191
- double-quoted argument: inside double quotes the shell still expands $ and
2192
- backticks, while the quoted EOF keeps the text exactly as written.
2193
-
2194
- Examples:
2195
- chesly send "Mom" - --wait <<'EOF'
2196
- On my way
2197
- EOF
2198
- chesly send "Invoice 42" - --network email <<'EOF'
2199
- Paid, thank you.
2200
- EOF
2201
- chesly send chat_7Hq2mR9xLp4vT1sK8nWz - --file report.pdf <<'EOF'
2202
- The report is attached.
2203
- EOF`
2204
- ).action(async (chat, text, options, command) => {
2205
- const out = new Output(io, command.optsWithGlobals());
2206
- const body = await messageText2(text, io);
2207
- if (options.file !== void 0 && options.mediaId !== void 0) {
2208
- throw new CliError("usage_error", "A message carries one attachment: give --file or --media-id, not both.", EXIT.USAGE);
2209
- }
2210
- if (body === void 0 && options.file === void 0 && options.mediaId === void 0) {
2211
- throw new CliError("usage_error", "Give the text to send, - to read it from stdin, or --file.", EXIT.USAGE);
2212
- }
2213
- const file = options.file === void 0 ? void 0 : await readUpload(options.file);
2214
- const key = keyOnce();
2215
- const target = await resolveChat(chat, key, { network: options.network });
2216
- const idempotencyKey = options.idempotencyKey ?? randomUUID();
2217
- const uploaded = file === void 0 ? void 0 : await uploadFile(file, await key());
2218
- const mediaId = uploaded?.id ?? options.mediaId;
2219
- const again = {
2220
- flags: uploaded === void 0 ? `--idempotency-key ${idempotencyKey}` : `--media-id ${shellQuote(uploaded.id)} --idempotency-key ${idempotencyKey} (instead of --file)`,
2221
- extras: { idempotency_key: idempotencyKey, ...mediaId === void 0 ? {} : { media_id: mediaId } }
2222
- };
2223
- const answer = await idempotentPost(`/v1/chats/${encodeURIComponent(target.id)}/messages`, {
2224
- key: await key(),
2225
- idempotencyKey,
2226
- body: {
2227
- ...body === void 0 ? {} : { text: body },
2228
- ...options.replyTo === void 0 ? {} : { reply_to: options.replyTo },
2229
- ...mediaId === void 0 ? {} : { media_id: mediaId }
2230
- },
2231
- again
2232
- });
2233
- if (!isMessage(answer)) {
2234
- throw new AnnotatedError(
2235
- new CliError("invalid_response", "The API sent no message for the send."),
2236
- again.extras,
2237
- `It may have gone out. Run the command again with ${again.flags} to see the API's answer.`
2238
- );
2239
- }
2240
- const waited = options.wait ? await waitForDelivery(answer, await key()) : { message: answer, ranOut: false, failure: void 0 };
2241
- const { message } = waited;
2242
- const state = deliveryState(message.delivery);
2243
- out.result(message, () => sentLine(target, message));
2244
- if (waited.failure !== void 0) {
2245
- out.warn(
2246
- "delivery_wait_failed",
2247
- `The message was sent, but following its delivery failed (${waited.failure}). chesly read shows it, and the command run again with ${again.flags} shows the API's answer.`,
2248
- again.extras
2249
- );
2250
- } else if (waited.ranOut && state === "queued") {
2251
- out.note(`Still queued after ${WAIT_MS / 1e3} s.`);
2252
- }
2253
- const delivery = message.delivery;
2254
- if (state === "failed") {
2255
- throw new CliError("delivery_failed", delivery?.error?.message ?? "The network did not take the message.", EXIT.ERROR, {
2256
- extras: { message_id: message.id, delivery }
2257
- });
2258
- }
2259
- if (state === "unconfirmed") {
2260
- throw new CliError(
2261
- "delivery_unconfirmed",
2262
- "The network didn't confirm the message, so it may have been delivered. Check the chat before you send it again.",
2263
- EXIT.RETRY_LATER,
2264
- { extras: { message_id: message.id, delivery } }
2265
- );
2266
- }
2267
- });
2268
- }
2269
- async function messageText2(text, io) {
2270
- if (text !== "-") return text === "" ? void 0 : text;
2271
- if (io.stdin.isTTY) {
2272
- throw new CliError(
2273
- "usage_error",
2274
- "The text - reads stdin, and stdin is a terminal. Pipe the text in, or give it as an argument.",
2275
- EXIT.USAGE
2276
- );
2277
- }
2278
- const piped = (await io.stdin.read()).replace(/(?:\r?\n)+$/, "");
2279
- return piped === "" ? void 0 : piped;
2280
- }
2281
- async function waitForDelivery(sent, key) {
2282
- let message = sent;
2283
- let failure;
2284
- let pauseMs = POLL_MS;
2285
- const deadline = Date.now() + WAIT_MS;
2286
- while (!settled(message)) {
2287
- if (deadline - Date.now() < pauseMs + MIN_POLL_MS) return { message, ranOut: failure === void 0, failure };
2288
- await sleep(pauseMs);
2289
- pauseMs = POLL_MS;
2290
- try {
2291
- const timeoutMs = deadline - Date.now();
2292
- const polled = await apiRequest(`/v1/messages/${encodeURIComponent(message.id)}`, { key, timeoutMs });
2293
- if (!isMessage(polled)) return { message, ranOut: false, failure: "the API sent an answer that is not a message" };
2294
- message = polled;
2295
- failure = void 0;
2296
- } catch (error) {
2297
- if (error instanceof CheslyNetworkError && error.timedOut) return { message, ranOut: true, failure: void 0 };
2298
- failure = pollFailure(error);
2299
- const passing = isTransient(error) || error instanceof CheslyApiError && error.status === 429;
2300
- if (!passing) return { message, ranOut: false, failure };
2301
- if (error instanceof CheslyApiError && error.retryAfter !== void 0) {
2302
- pauseMs = Math.max(POLL_MS, error.retryAfter * 1e3);
2303
- }
2304
- }
2305
- }
2306
- return { message, ranOut: false, failure: void 0 };
2307
- }
2308
- function pollFailure(error) {
2309
- if (error instanceof CheslyApiError) return `${error.status} ${error.code}`;
2310
- if (error instanceof CheslyNetworkError) return "no answer from the API";
2311
- return "an unexpected error";
2312
- }
2313
- function settled(message) {
2314
- const state = deliveryState(message.delivery);
2315
- return state === void 0 || state === "sent" || state === "delivered" || state === "failed";
2316
- }
2317
-
2318
2388
  // src/commands/usage.ts
2319
2389
  function registerUsage(program, io) {
2320
2390
  program.command("usage").description("Your API plan: this period's calls and minutes, its limits, and send caps").addHelpText(
@@ -2858,6 +2928,8 @@ function buildProgram(io, json) {
2858
2928
  registerSearch(program, io);
2859
2929
  registerCatchup(program, io);
2860
2930
  registerSend(program, io);
2931
+ registerEdit(program, io);
2932
+ registerDelete(program, io);
2861
2933
  registerWatch(program, io);
2862
2934
  registerWebhooks(program, io);
2863
2935
  registerKeys(program, io);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chesly",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Chesly CLI: your chats from the terminal and your agents",
5
5
  "license": "MIT",
6
6
  "type": "module",