chesly 0.3.0 → 0.4.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, 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.
7
+ Read your chats, download the files in them, send messages and files, edit or delete the ones you
8
+ sent, follow events as they happen, and manage webhooks, on WhatsApp, Telegram, Signal, iMessage,
9
+ Instagram, Messenger, X, LinkedIn, Discord, Slack, Reddit, Google Messages, Google Chat and email.
10
10
 
11
11
  ## Install
12
12
 
@@ -120,8 +120,56 @@ chesly search "boarding pass" --network whatsapp # one network only
120
120
  chesly send "Invoice 42" - --network email <<'EOF' # a reply to that thread
121
121
  Paid, thank you.
122
122
  EOF
123
+ chesly send "Invoice 42" - --network email --file receipt.pdf <<'EOF' # a reply with a file
124
+ Paid, the receipt is attached.
125
+ EOF
126
+ ```
127
+
128
+ An email thread's messages list their attachments, each with a media ID that `chesly download`
129
+ takes, and a reply can carry a file of its own, as its attachment (see below).
130
+
131
+ ## Download files
132
+
133
+ Each file in a message (a photo, a video, a voice note, a document) and each of an email's
134
+ attachments has a media ID (`media_…`). `chesly read` shows it under the message that carries it:
135
+
136
+ ```
137
+ Oct 27 09:00 Mom Look at this
138
+ [image] beach.jpg · media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv
139
+ Oct 27 09:03 Ana Here is the invoice.
140
+ [file] invoice.pdf · 120 KB · media_ZW1haWw6M2YyYzlhMWUtNWI3ZC00YzhlLTlmMGEtMWIyYzNkNGU1ZjYw
123
141
  ```
124
142
 
143
+ ```sh
144
+ chesly download media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv # saved here, as beach.jpg
145
+ chesly download media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv -o photo.jpg # under another name
146
+ chesly download media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv -o ~/Downloads # into a directory, under its own name
147
+ chesly download media_ZW1haWw6M2YyYzlhMWUtNWI3ZC00YzhlLTlmMGEtMWIyYzNkNGU1ZjYw -o - | pdftotext - -
148
+ ```
149
+
150
+ In JSON, a file's media ID is a message's `media.id`, or the `id` of each of an email's
151
+ `email.attachments` (`{"id","file_name","mime_type","size"}`; an email's `media` is `null`).
152
+
153
+ `download` saves the file under its own name, made safe to save: never a path, a hidden file or a
154
+ name that starts with `-`, and without characters a terminal or Windows would act on. A file without
155
+ a name is saved as its media ID with its type's extension. It never replaces a file without
156
+ `--force`: it exits 2 with `file_exists` (and the file's `path`) and saves nothing. The file is
157
+ written under a temporary name in the same directory and takes its name once whole, so a download
158
+ that fails or is stopped (Ctrl+C) leaves nothing behind.
159
+
160
+ It prints `{"path":"/home/me/beach.jpg","size":48213,"mime_type":"image/jpeg"}` (the whole path,
161
+ and the size in bytes), or `Saved beach.jpg · 48 KB · image/jpeg` in a terminal. The API sends a
162
+ file a browser could open as a page (a PDF, HTML, an SVG) as `application/octet-stream`;
163
+ `mime_type` then goes by the extension of the file's name. With `-o -` the file's bytes go to stdout
164
+ and nothing else does, so stdout must be a pipe or a file, never a terminal.
165
+
166
+ A file is at most 50 MB. An unknown media ID exits 4 (`media_not_found`), and a file no longer kept
167
+ exits 1 (`media_expired`). A file briefly unavailable (`media_unavailable`), a 502, 503, 504 or 429,
168
+ or a dropped connection is asked for again as a send is (after the answer's `Retry-After`, at most
169
+ 10 seconds, or 1 and then 2 seconds; twice at most), then exits 5, or 1 for a connection. A download
170
+ that sends nothing for 30 seconds has dropped. With `-o -`, nothing is asked for again once the first
171
+ bytes went out.
172
+
125
173
  ## Send messages
126
174
 
127
175
  ```sh
@@ -151,6 +199,13 @@ An upload must arrive whole within 60 seconds, at 50 KB/s or faster on average.
151
199
  refused (408 `upload_timeout`), and so are the account's uploads for the next 60 seconds (429
152
200
  `rate_limited`, with the seconds left); both exit 5. On a slow connection, send a smaller file.
153
201
 
202
+ `--file` works in an email thread too: the file goes as the reply's attachment, and the text as its
203
+ body. Email providers refuse files over 25 MB (25,000,000 bytes), so a bigger one is refused there
204
+ (400 `media_too_large`, exit 1).
205
+
206
+ To forward a file someone sent, give its media ID from `chesly read` as `--media-id`: it goes to the
207
+ other chat with no download or upload.
208
+
154
209
  `send` prints the message the API answered. Its `delivery.status` is `queued` until the network
155
210
  takes it; `--wait` checks every second (or later, when a refused check's Retry-After says so),
156
211
  within 30 seconds in all, until it is `sent`, `delivered` or `failed` (`delivered` comes only where
@@ -347,8 +402,8 @@ Sends:
347
402
  telegram · 0/30 this hour · 12/150 today
348
403
  ```
349
404
 
350
- An API plan is a flat monthly price, Personal or Pro: calls are counted, never billed, and each plan
351
- has its own transcription minutes and limits (https://web.chesly.app/api/billing). Minutes used
405
+ An API plan is a flat monthly price, Starter, Personal or Pro: calls are counted, never billed, and
406
+ each plan has its own limits and, on Personal and Pro, transcription minutes (https://web.chesly.app/api/billing). Minutes used
352
407
  round down, and once they're used up the line says when they come back
353
408
  (`600 of 600 min, used up until Nov 28`). A downgrade waits for the end of the period, and the plan
354
409
  line says when (`Plan: Pro, active: changes to Personal on Jan 14`). The request limits apply to
@@ -370,6 +425,7 @@ each key and to all your keys together. With `--json` it prints the API's `GET /
370
425
  | `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
426
  | `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
427
  | `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}`) |
428
+ | `chesly download <media_id> [-o <path>\|-] [--force]` | Saves a file from a message, or an email's attachment, under its own name or `-o`'s, or writes it to stdout (`GET /v1/media/{media_id}`) |
373
429
  | `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`) |
374
430
  | `chesly webhooks list\|create\|delete\|rotate\|test\|deliveries` | Manages webhooks (`/v1/webhooks`) |
375
431
  | `chesly keys list\|revoke <key_id>` | Lists or revokes API keys (`/v1/keys`) |
@@ -400,7 +456,8 @@ included, on every network but email (add `--network email` for email threads):
400
456
  ## For agents and scripts
401
457
 
402
458
  - **Output:** tables in a terminal. When stdout is piped, or with `--json`, it prints the API's JSON
403
- as is; `watch` prints one JSON object a line.
459
+ as is; `watch` prints one JSON object a line, and `download` where it saved the file
460
+ (`{"path","size","mime_type"}`), or with `-o -` the file itself.
404
461
  - **Errors** go to stderr. In JSON mode each one is a single line of problem details. Problem
405
462
  details from the API print exactly as the API sent them (`type`, `title`, `status`, `detail`,
406
463
  `code`, `request_id`, and `retry_after` when it says when to retry). In a terminal, an error that
@@ -429,11 +486,11 @@ included, on every network but email (add `--network email` for email threads):
429
486
  |---|---|
430
487
  | 0 | ok |
431
488
  | 1 | error |
432
- | 2 | usage |
489
+ | 2 | usage: a wrong argument, or a file `download` would replace (`file_exists`) |
433
490
  | 3 | not signed in (no key, a malformed one, or the key was rejected) |
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) |
491
+ | 4 | not found (an unknown chat, message, file, webhook or key, or a name that matches no chat), or ambiguous (a name that matches several) |
435
492
  | 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 |
436
- | 6 | payment required: the account needs an API plan, or this period's transcription minutes are used up |
493
+ | 6 | payment required: the account needs an API plan, or this period's transcription minutes are used up (Starter has none) |
437
494
 
438
495
  - **MCP:** give Claude Code the Chesly MCP server with your key:
439
496
 
package/dist/errors.js CHANGED
@@ -34,8 +34,11 @@ var LOCAL_ERROR_CODES = [
34
34
  { code: "delivery_failed", title: "The network did not take the message." },
35
35
  { code: "delivery_unconfirmed", title: "The network didn't confirm the message, so it may have been delivered." },
36
36
  { code: "expired_token", title: "The sign-in code expired." },
37
+ { code: "file_exists", title: "A file is already there." },
37
38
  { code: "file_unreadable", title: "The file can't be read." },
39
+ { code: "file_unwritable", title: "The file can't be saved there." },
38
40
  { code: "internal_error", title: "Something went wrong on our side." },
41
+ { code: "interrupted", title: "The command was stopped before it finished." },
39
42
  { code: "invalid_api_url", title: "CHESLY_API_URL is not a usable API URL." },
40
43
  { code: "invalid_key_format", title: "The API key is not well formed." },
41
44
  { code: "invalid_response", title: "The API's answer is not what the CLI expects." },
@@ -99,7 +102,10 @@ var API_ERROR_CODES = [
99
102
  { code: "email_send_failed", status: 502, title: "The email provider refused the message." },
100
103
  { code: "account_reconnect_required", status: 409, title: "This account needs to be reconnected." },
101
104
  { code: "api_paused", status: 503, title: "The Chesly API is paused." },
102
- { code: "payload_too_large", status: 413, title: "The request body is too large." }
105
+ { code: "payload_too_large", status: 413, title: "The request body is too large." },
106
+ { code: "file_url_invalid", status: 400, title: "This file URL can't be used." },
107
+ { code: "file_fetch_failed", status: 422, title: "The file couldn't be fetched." },
108
+ { code: "link_not_found", status: 404, title: "Link not found." }
103
109
  ];
104
110
  var RETRY_LATER_STATUSES = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
105
111
  function apiExitCode(status, code) {
@@ -129,6 +135,14 @@ var KeychainTimeoutError = class extends Error {
129
135
  }
130
136
  seconds;
131
137
  };
138
+ function fileErrorReason(error) {
139
+ const { code, message } = error ?? {};
140
+ if (code === "ENOENT") return "no such file";
141
+ if (code === "EACCES" || code === "EPERM") return "permission denied";
142
+ if (code === "ENOSPC") return "no space left on the disk";
143
+ if (code === "EROFS") return "the file system is read-only";
144
+ return typeof message === "string" && message !== "" ? message : "it failed";
145
+ }
132
146
  function errorType(code) {
133
147
  return `https://agents.chesly.app/docs/errors#${code}`;
134
148
  }
@@ -169,5 +183,6 @@ export {
169
183
  RETRY_LATER_STATUSES,
170
184
  apiExitCode,
171
185
  errorType,
186
+ fileErrorReason,
172
187
  httpErrorCode
173
188
  };
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.3.0",
12
+ version: "0.4.0",
13
13
  description: "Chesly CLI: your chats from the terminal and your agents",
14
14
  license: "MIT",
15
15
  type: "module",
@@ -90,8 +90,11 @@ var LOCAL_ERROR_CODES = [
90
90
  { code: "delivery_failed", title: "The network did not take the message." },
91
91
  { code: "delivery_unconfirmed", title: "The network didn't confirm the message, so it may have been delivered." },
92
92
  { code: "expired_token", title: "The sign-in code expired." },
93
+ { code: "file_exists", title: "A file is already there." },
93
94
  { code: "file_unreadable", title: "The file can't be read." },
95
+ { code: "file_unwritable", title: "The file can't be saved there." },
94
96
  { code: "internal_error", title: "Something went wrong on our side." },
97
+ { code: "interrupted", title: "The command was stopped before it finished." },
95
98
  { code: "invalid_api_url", title: "CHESLY_API_URL is not a usable API URL." },
96
99
  { code: "invalid_key_format", title: "The API key is not well formed." },
97
100
  { code: "invalid_response", title: "The API's answer is not what the CLI expects." },
@@ -123,6 +126,14 @@ var KeychainTimeoutError = class extends Error {
123
126
  }
124
127
  seconds;
125
128
  };
129
+ function fileErrorReason(error) {
130
+ const { code, message } = error ?? {};
131
+ if (code === "ENOENT") return "no such file";
132
+ if (code === "EACCES" || code === "EPERM") return "permission denied";
133
+ if (code === "ENOSPC") return "no space left on the disk";
134
+ if (code === "EROFS") return "the file system is read-only";
135
+ return typeof message === "string" && message !== "" ? message : "it failed";
136
+ }
126
137
  function errorType(code) {
127
138
  return `https://agents.chesly.app/docs/errors#${code}`;
128
139
  }
@@ -212,10 +223,13 @@ var CheslyApiError = class extends Error {
212
223
  }
213
224
  };
214
225
  var CheslyNetworkError = class extends Error {
215
- /** No answer came within the request's time limit. */
226
+ /** No answer came within the request's time limit, or, partway, no byte within the idle limit. */
216
227
  timedOut;
217
- constructor(url, cause, timeoutMs = TIMEOUT_MS) {
218
- super(`Couldn't reach ${new URL(url).origin}: ${networkReason(cause, timeoutMs)}`);
228
+ /** `cause` is the error fetch or the body threw, or why in words. */
229
+ constructor(url, cause, timeoutMs = TIMEOUT_MS, midAnswer = false) {
230
+ const origin = new URL(url).origin;
231
+ const reason = typeof cause === "string" ? cause : networkReason(cause, timeoutMs, midAnswer);
232
+ super(midAnswer ? `The answer from ${origin} broke off: ${reason}` : `Couldn't reach ${origin}: ${reason}`);
219
233
  this.name = "CheslyNetworkError";
220
234
  this.timedOut = isTimeout(rootCause(cause));
221
235
  }
@@ -298,6 +312,10 @@ async function idempotentPost(path, init) {
298
312
  }
299
313
  }
300
314
  }
315
+ function retryDelayMs(error, retried) {
316
+ if (retried >= RETRY_DELAYS_MS.length || !isShortLimit(error) && !isTransient(error)) return void 0;
317
+ return retryWaitMs(error, retried);
318
+ }
301
319
  function retryWaitMs(error, retried) {
302
320
  const retryAfter = error instanceof CheslyApiError ? error.retryAfter : void 0;
303
321
  if (retryAfter !== void 0) return Math.min(retryAfter, MAX_RETRY_WAIT_S) * 1e3;
@@ -311,15 +329,15 @@ function isTransient(error) {
311
329
  return error instanceof CheslyApiError && (error.status === 502 || error.status === 503 || error.status === 504);
312
330
  }
313
331
  function sleep(ms, signal) {
314
- return new Promise((resolve) => {
332
+ return new Promise((resolve2) => {
315
333
  if (signal?.aborted) {
316
- resolve();
334
+ resolve2();
317
335
  return;
318
336
  }
319
337
  const done = () => {
320
338
  clearTimeout(timer);
321
339
  signal?.removeEventListener("abort", done);
322
- resolve();
340
+ resolve2();
323
341
  };
324
342
  const timer = setTimeout(done, ms);
325
343
  signal?.addEventListener("abort", done, { once: true });
@@ -371,6 +389,34 @@ async function openEventStream(path, init) {
371
389
  clearTimeout(timer);
372
390
  }
373
391
  }
392
+ async function openDownload(path, init) {
393
+ const headers = requestHeaders(init.key, "*/*", { "accept-encoding": "identity" });
394
+ const url = `${apiBaseUrl()}${path}`;
395
+ const connection = new AbortController();
396
+ const close = () => connection.abort(init.signal.reason);
397
+ init.signal.addEventListener("abort", close, { once: true });
398
+ if (init.signal.aborted) close();
399
+ const timer = setTimeout(
400
+ () => connection.abort(new DOMException("No answer in time.", "TimeoutError")),
401
+ TIMEOUT_MS
402
+ );
403
+ try {
404
+ let response;
405
+ try {
406
+ response = await fetch(url, { headers, signal: connection.signal });
407
+ } catch (cause) {
408
+ if (init.signal.aborted) throw cause;
409
+ throw new CheslyNetworkError(url, cause);
410
+ }
411
+ if (!response.ok) {
412
+ const text = await response.text().catch(() => "");
413
+ throw errorFromResponse(response, parseJson(text));
414
+ }
415
+ return { response, url };
416
+ } finally {
417
+ clearTimeout(timer);
418
+ }
419
+ }
374
420
  function requestHeaders(key, accept, extra = {}) {
375
421
  if (key !== void 0 && !isApiKey(key)) {
376
422
  throw new CliError("invalid_key_format", "Refused to send an API key that is not well formed.", EXIT.NOT_SIGNED_IN);
@@ -433,15 +479,15 @@ function isRecord(value) {
433
479
  function nonEmpty(value) {
434
480
  return typeof value === "string" && value.trim() !== "" ? value : void 0;
435
481
  }
436
- function networkReason(error, timeoutMs) {
482
+ function networkReason(error, timeoutMs, midAnswer) {
437
483
  const current = rootCause(error);
438
- if (isTimeout(current)) return `no answer within ${timeoutMs / 1e3} s`;
484
+ if (isTimeout(current)) return midAnswer ? `nothing arrived for ${timeoutMs / 1e3} s` : `no answer within ${timeoutMs / 1e3} s`;
439
485
  if (current instanceof AggregateError) {
440
486
  const tried = current.errors.filter(isSystemError).map((attempt) => attempt.message);
441
487
  if (tried.length > 0) return tried.join("; ");
442
488
  }
443
489
  if (isSystemError(current)) return current.message;
444
- return "the request failed before it reached the API";
490
+ return midAnswer ? "the connection failed" : "the request failed before it reached the API";
445
491
  }
446
492
  function rootCause(error) {
447
493
  let current = error;
@@ -514,7 +560,7 @@ async function napiKeychain() {
514
560
  }
515
561
  function withTimeout(call) {
516
562
  const controller = new AbortController();
517
- return new Promise((resolve, reject) => {
563
+ return new Promise((resolve2, reject) => {
518
564
  const running = call(controller.signal);
519
565
  const timer = setTimeout(() => {
520
566
  controller.abort();
@@ -528,7 +574,7 @@ function withTimeout(call) {
528
574
  running.then(
529
575
  (value) => {
530
576
  clearTimeout(timer);
531
- resolve(value);
577
+ resolve2(value);
532
578
  },
533
579
  (error) => {
534
580
  clearTimeout(timer);
@@ -538,7 +584,7 @@ function withTimeout(call) {
538
584
  });
539
585
  }
540
586
  function security(args, input = "") {
541
- return new Promise((resolve, reject) => {
587
+ return new Promise((resolve2, reject) => {
542
588
  const child = spawn(SECURITY, args, { stdio: ["pipe", "pipe", "pipe"] });
543
589
  const timer = setTimeout(() => {
544
590
  child.kill("SIGKILL");
@@ -558,7 +604,7 @@ function security(args, input = "") {
558
604
  });
559
605
  child.on("close", (code) => {
560
606
  clearTimeout(timer);
561
- resolve({ code: code ?? 1, stdout, stderr });
607
+ resolve2({ code: code ?? 1, stdout, stderr });
562
608
  });
563
609
  child.stdin.on("error", () => {
564
610
  });
@@ -590,14 +636,14 @@ async function savePendingLogin(login) {
590
636
  async function readPendingLogin() {
591
637
  try {
592
638
  const value = JSON.parse(await readFile(pendingLoginPath(), "utf8"));
593
- const { deviceCode, userCode, link, interval, expiresAt } = value;
594
- if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof link !== "string") return null;
639
+ const { deviceCode, userCode, link: link2, interval, expiresAt } = value;
640
+ if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof link2 !== "string") return null;
595
641
  if (typeof interval !== "number" || typeof expiresAt !== "number") return null;
596
642
  const replaces = (Array.isArray(value.replaces) ? value.replaces : []).flatMap((hint) => {
597
643
  const { prefix, last4 } = hint ?? {};
598
644
  return typeof prefix === "string" && typeof last4 === "string" ? [{ prefix, last4 }] : [];
599
645
  });
600
- return { deviceCode, userCode, link, interval, expiresAt, replaces, force: value.force === true };
646
+ return { deviceCode, userCode, link: link2, interval, expiresAt, replaces, force: value.force === true };
601
647
  } catch {
602
648
  return null;
603
649
  }
@@ -766,6 +812,9 @@ import { CommanderError } from "commander";
766
812
  function processIo() {
767
813
  return {
768
814
  out: (text) => void process.stdout.write(text),
815
+ outBytes: (chunk) => new Promise((resolve2, reject) => {
816
+ process.stdout.write(chunk, (error) => error ? reject(error) : resolve2());
817
+ }),
769
818
  err: (text) => void process.stderr.write(text),
770
819
  isTTY: process.stdout.isTTY === true,
771
820
  stdin: {
@@ -780,10 +829,10 @@ function processIo() {
780
829
  }
781
830
  },
782
831
  onInterrupt: (handler) => {
783
- let interrupted = false;
832
+ let interrupted2 = false;
784
833
  const listener = () => {
785
- if (interrupted) process.exit(130);
786
- interrupted = true;
834
+ if (interrupted2) process.exit(130);
835
+ interrupted2 = true;
787
836
  handler();
788
837
  };
789
838
  process.on("SIGINT", listener);
@@ -875,6 +924,12 @@ function formatWhen(iso, options = {}) {
875
924
  function twoDigits(value) {
876
925
  return String(value).padStart(2, "0");
877
926
  }
927
+ function formatBytes(bytes) {
928
+ if (bytes < 1e3) return `${bytes} ${bytes === 1 ? "byte" : "bytes"}`;
929
+ const [value, unit] = bytes < 1e6 ? [bytes / 1e3, "KB"] : bytes < 1e9 ? [bytes / 1e6, "MB"] : [bytes / 1e9, "GB"];
930
+ const shown = value < 10 ? (Math.floor(value * 10) / 10).toFixed(1).replace(/\.0$/, "") : String(Math.floor(value));
931
+ return `${shown} ${unit}`;
932
+ }
878
933
  function reportError(error, io, json) {
879
934
  if (error instanceof CommanderError) {
880
935
  return error.exitCode === 0 ? EXIT.OK : EXIT.USAGE;
@@ -916,7 +971,8 @@ var CLI_WORDING = {
916
971
  message: "The upload was too slow, or didn't finish within 60 s.",
917
972
  hint: "Send it again in 60 s: this account's uploads are held that long after a slow one. On a slow connection, send a smaller file."
918
973
  },
919
- key_not_found: { hint: "chesly keys list lists your API keys." }
974
+ key_not_found: { hint: "chesly keys list lists your API keys." },
975
+ media_not_found: { hint: "chesly read <chat> shows the media ID of each file in a chat." }
920
976
  };
921
977
  function describeFailure(error) {
922
978
  if (error instanceof AnnotatedError) {
@@ -988,6 +1044,9 @@ function isAccountList(value) {
988
1044
  function isChatPage(value) {
989
1045
  return isRecord2(value) && Array.isArray(value.chats) && value.chats.every(hasId);
990
1046
  }
1047
+ function isEmailAttachment(value) {
1048
+ return isRecord2(value) && typeof value.id === "string" && value.id !== "";
1049
+ }
991
1050
  function deliveryState(delivery) {
992
1051
  if (delivery === null || delivery === void 0) return void 0;
993
1052
  if (delivery.status === "failed") return delivery.error?.certain === true ? "failed" : "unconfirmed";
@@ -1084,7 +1143,7 @@ function searchTable(hits) {
1084
1143
  formatWhen(hit.sent_at, { time: true }),
1085
1144
  oneLine(hit.chat_name ?? "", 30) || hit.chat_id,
1086
1145
  senderLabel(hit),
1087
- oneLine(messageText(hit), 100)
1146
+ messageLine(hit, 100)
1088
1147
  ])
1089
1148
  ]);
1090
1149
  }
@@ -1092,7 +1151,7 @@ function transcript(messages) {
1092
1151
  const rows = chronological(messages).map((message) => ({
1093
1152
  when: formatWhen(message.sent_at, { time: true }),
1094
1153
  who: senderLabel(message),
1095
- lines: messageText(message).split("\n")
1154
+ lines: messageLines(message)
1096
1155
  }));
1097
1156
  const whenWidth = Math.max(0, ...rows.map((row) => row.when.length));
1098
1157
  const whoWidth = Math.max(0, ...rows.map((row) => row.who.length));
@@ -1111,6 +1170,45 @@ function messageText(message) {
1111
1170
  const body = message.type === "text" ? text : [`[${message.type}]`, text || oneLine(message.media?.file_name ?? "")].filter(Boolean).join(" ");
1112
1171
  return `${body}${message.truncated ? " \u2026" : ""}${message.edited ? " (edited)" : ""}`;
1113
1172
  }
1173
+ function messageLines(message) {
1174
+ const files = filesOf(message).map(fileLine);
1175
+ if (files.length === 0) return messageText(message).split("\n");
1176
+ const text = terminalSafe(message.text ?? "").trim();
1177
+ const marks = `${message.truncated ? " \u2026" : ""}${message.edited ? " (edited)" : ""}`;
1178
+ if (text === "") return [`${files[0]}${marks}`, ...files.slice(1)];
1179
+ return [...`${text}${marks}`.split("\n"), ...files];
1180
+ }
1181
+ function messageLine(message, max) {
1182
+ const ids = filesOf(message).map((file) => oneLine(file.id));
1183
+ return [oneLine(messageText(message), max), ...ids].filter(Boolean).join(" \xB7 ");
1184
+ }
1185
+ function filesOf(message) {
1186
+ if (message.deleted) return [];
1187
+ const files = [];
1188
+ const { media, email } = message;
1189
+ if (isRecord2(media) && typeof media.id === "string" && media.id !== "") {
1190
+ files.push({ kind: textOf(message.type), name: textOf(media.file_name), size: void 0, id: media.id });
1191
+ }
1192
+ const attachments = isRecord2(email) && Array.isArray(email.attachments) ? email.attachments.filter(isEmailAttachment) : [];
1193
+ for (const attachment of attachments) {
1194
+ const size = attachment.size;
1195
+ files.push({
1196
+ kind: kindOf(textOf(attachment.mime_type)),
1197
+ name: textOf(attachment.file_name),
1198
+ size: typeof size === "number" && Number.isSafeInteger(size) && size >= 0 ? size : void 0,
1199
+ id: attachment.id
1200
+ });
1201
+ }
1202
+ return files;
1203
+ }
1204
+ function kindOf(mimeType) {
1205
+ const kind = mimeType.split("/")[0]?.trim().toLowerCase();
1206
+ return kind === "image" || kind === "video" || kind === "audio" ? kind : "file";
1207
+ }
1208
+ function fileLine(file) {
1209
+ const about = [oneLine(file.name, 80), file.size === void 0 ? "" : formatBytes(file.size)].filter(Boolean);
1210
+ return `[${oneLine(file.kind, 20) || "file"}] ${[...about, oneLine(file.id)].join(" \xB7 ")}`;
1211
+ }
1114
1212
  function sentLine(chat, message) {
1115
1213
  const where = oneLine(chat.name ?? "", 60) || chat.id;
1116
1214
  const state = deliveryState(message.delivery);
@@ -1124,7 +1222,7 @@ function eventLine(event) {
1124
1222
  const { message } = data;
1125
1223
  const network = oneLine(textOf(chat.network), 20);
1126
1224
  const name = oneLine(textOf(chat.name), 40) || message.chat_id;
1127
- return `${when} [${network}] ${name} \u2014 ${senderLabel(message)}: ${oneLine(messageText(message), 200)}`;
1225
+ return `${when} [${network}] ${name} \u2014 ${senderLabel(message)}: ${messageLine(message, 200)}`;
1128
1226
  }
1129
1227
  return [when, oneLine(event.type, 40), subjectOf(data, chat)].filter(Boolean).join(" ");
1130
1228
  }
@@ -1221,6 +1319,7 @@ function keyTable(keys, inUse) {
1221
1319
  }
1222
1320
  var BILLING_URL = "https://web.chesly.app/api/billing";
1223
1321
  var PLAN_NAMES = /* @__PURE__ */ new Map([
1322
+ ["starter", "Starter"],
1224
1323
  ["personal", "Personal"],
1225
1324
  ["pro", "Pro"]
1226
1325
  ]);
@@ -1288,6 +1387,7 @@ function scheduledChange(change) {
1288
1387
  return `changes to ${name} ${when.includes(":") ? "at" : "on"} ${when}`;
1289
1388
  }
1290
1389
  function transcriptionMinutes(plan) {
1390
+ if (plan.plan === "starter") return "not part of Starter";
1291
1391
  const usedSeconds = Number(plan.transcription_seconds_this_period) || 0;
1292
1392
  const used = count(Math.floor(usedSeconds / 60));
1293
1393
  const included = Number(plan.transcription_seconds_included);
@@ -1370,6 +1470,11 @@ function parseMessageId(value) {
1370
1470
  if (id === "") throw new InvalidArgumentError("Give a message ID (msg_\u2026).");
1371
1471
  return id;
1372
1472
  }
1473
+ function parseMediaId(value) {
1474
+ const id = value.trim();
1475
+ if (!/^media_[A-Za-z0-9_-]+$/.test(id)) throw new InvalidArgumentError("Give a file's media ID (media_\u2026), as chesly read shows it.");
1476
+ return id;
1477
+ }
1373
1478
  function parseList(value) {
1374
1479
  const items = [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))];
1375
1480
  if (items.length === 0) throw new InvalidArgumentError("Give one or more names, separated by commas.");
@@ -1497,49 +1602,13 @@ Example:
1497
1602
  });
1498
1603
  }
1499
1604
 
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
- });
1526
- }
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
- });
1533
- }
1534
- function sameName(chatName, name) {
1535
- return (chatName ?? "").trim().localeCompare(name, void 0, { sensitivity: "accent" }) === 0;
1536
- }
1605
+ // src/download.ts
1606
+ import { randomBytes } from "crypto";
1607
+ import { link, lstat, open, rename as rename2, rm as rm2, stat } from "fs/promises";
1608
+ import { dirname as dirname2, isAbsolute, join as join2, relative, resolve, sep } from "path";
1537
1609
 
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;
1610
+ // src/mime.ts
1611
+ import { extname } from "path";
1543
1612
  var MIME_TYPES = {
1544
1613
  jpg: "image/jpeg",
1545
1614
  jpeg: "image/jpeg",
@@ -1583,10 +1652,392 @@ var MIME_TYPES = {
1583
1652
  ppt: "application/vnd.ms-powerpoint",
1584
1653
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
1585
1654
  };
1655
+ var EXTENSIONS = new Map([
1656
+ ...Object.entries(MIME_TYPES).map(([extension, type]) => [type, extension]).reverse(),
1657
+ ["audio/opus", "opus"],
1658
+ ["audio/webm", "weba"],
1659
+ ["audio/x-wav", "wav"],
1660
+ ["video/ogg", "ogv"]
1661
+ ]);
1662
+ function mimeTypeOf(name) {
1663
+ return MIME_TYPES[extname(name).slice(1).toLowerCase()] ?? "application/octet-stream";
1664
+ }
1665
+ function extensionFor(mimeType) {
1666
+ return EXTENSIONS.get(mimeType);
1667
+ }
1668
+
1669
+ // src/download.ts
1670
+ var IDLE_TIMEOUT_MS = 3e4;
1671
+ var MAX_NAME_BYTES = 200;
1672
+ var WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\.|$)/i;
1673
+ async function placeFor(output, force) {
1674
+ if (output === void 0) return { dir: process.cwd(), path: void 0 };
1675
+ const path = resolve(output);
1676
+ if ((await stat(path).catch(() => void 0))?.isDirectory()) return { dir: path, path: void 0 };
1677
+ if (/[\\/]$/.test(output)) throw notSavable(`${output} is not a directory.`);
1678
+ const dir = dirname2(path);
1679
+ if (!(await stat(dir).catch(() => void 0))?.isDirectory()) {
1680
+ throw notSavable(`Can't save to ${output}: ${dirname2(output)} is not a directory.`);
1681
+ }
1682
+ if (!force) await refuseTaken(path, output);
1683
+ return { dir, path };
1684
+ }
1685
+ function notSavable(message, exitCode = EXIT.USAGE) {
1686
+ return new CliError("file_unwritable", message, exitCode);
1687
+ }
1688
+ async function refuseTaken(path, shown) {
1689
+ const taken = await lstat(path).then(
1690
+ () => true,
1691
+ () => false
1692
+ );
1693
+ if (taken) throw fileExists(path, shown);
1694
+ }
1695
+ function fileExists(path, shown) {
1696
+ return new CliError(
1697
+ "file_exists",
1698
+ `${shown} already exists. Add --force to replace it, or -o to save it under another name.`,
1699
+ EXIT.USAGE,
1700
+ { extras: { path } }
1701
+ );
1702
+ }
1703
+ async function downloadToFile(mediaId, key, place, force, io) {
1704
+ const temporary = join2(place.dir, `.chesly-${randomBytes(6).toString("hex")}.part`);
1705
+ let handle;
1706
+ try {
1707
+ handle = await open(temporary, "wx");
1708
+ } catch (error) {
1709
+ throw notSavable(`Can't save to ${shownPath(place.dir)}: ${fileErrorReason(error)}.`);
1710
+ }
1711
+ let handleOpen = true;
1712
+ try {
1713
+ const answer = await withAttempts(io, () => true, (stop) => {
1714
+ let path2 = place.path ?? place.dir;
1715
+ let written = 0;
1716
+ return transfer(mediaId, key, stop, {
1717
+ // Each attempt starts from an empty file, and names it from its answer unless -o did.
1718
+ start: async (headers) => {
1719
+ await saving(path2, () => handle.truncate(0));
1720
+ if (place.path !== void 0) return place.path;
1721
+ path2 = join2(place.dir, downloadName(headers, mediaId));
1722
+ if (!force) await refuseTaken(path2, shownPath(path2));
1723
+ return path2;
1724
+ },
1725
+ write: async (chunk) => {
1726
+ await saving(path2, () => writeAll(handle, chunk, written));
1727
+ written += chunk.byteLength;
1728
+ }
1729
+ });
1730
+ });
1731
+ const path = answer.started;
1732
+ await saving(path, () => handle.sync());
1733
+ handleOpen = false;
1734
+ await saving(path, () => handle.close());
1735
+ await saving(path, () => force ? rename2(temporary, path) : nameWithoutReplacing(temporary, path));
1736
+ return { path, size: answer.size, mimeType: fileType(answer.headers) };
1737
+ } finally {
1738
+ if (handleOpen) await handle.close().catch(() => {
1739
+ });
1740
+ await rm2(temporary, { force: true }).catch(() => {
1741
+ });
1742
+ }
1743
+ }
1744
+ async function saving(path, work) {
1745
+ try {
1746
+ return await work();
1747
+ } catch (error) {
1748
+ if (error instanceof CliError) throw error;
1749
+ throw notSavable(`Couldn't save ${shownPath(path)}: ${fileErrorReason(error)}.`, EXIT.ERROR);
1750
+ }
1751
+ }
1752
+ async function nameWithoutReplacing(temporary, path) {
1753
+ try {
1754
+ await link(temporary, path);
1755
+ return;
1756
+ } catch (error) {
1757
+ if (error.code === "EEXIST") throw fileExists(path, shownPath(path));
1758
+ }
1759
+ await refuseTaken(path, shownPath(path));
1760
+ await rename2(temporary, path);
1761
+ }
1762
+ async function writeAll(handle, chunk, position) {
1763
+ for (let done = 0; done < chunk.byteLength; ) {
1764
+ const { bytesWritten } = await handle.write(chunk, done, chunk.byteLength - done, position + done);
1765
+ if (bytesWritten === 0) throw new Error("the disk took no bytes");
1766
+ done += bytesWritten;
1767
+ }
1768
+ }
1769
+ async function downloadToStdout(mediaId, key, io) {
1770
+ let written = 0;
1771
+ await withAttempts(
1772
+ io,
1773
+ () => written === 0,
1774
+ (stop) => transfer(mediaId, key, stop, {
1775
+ start: async () => void 0,
1776
+ write: async (chunk) => {
1777
+ await io.outBytes(chunk);
1778
+ written += chunk.byteLength;
1779
+ }
1780
+ })
1781
+ );
1782
+ }
1783
+ async function withAttempts(io, again, attempt) {
1784
+ const stop = new AbortController();
1785
+ const stopListening = io.onInterrupt(() => stop.abort());
1786
+ try {
1787
+ for (let retried = 0; ; retried++) {
1788
+ try {
1789
+ return await attempt(stop.signal);
1790
+ } catch (error) {
1791
+ if (stop.signal.aborted) throw interrupted();
1792
+ const waitMs = again() ? retryDelayMs(error, retried) : void 0;
1793
+ if (waitMs === void 0) throw error;
1794
+ await sleep(waitMs, stop.signal);
1795
+ if (stop.signal.aborted) throw interrupted();
1796
+ }
1797
+ }
1798
+ } finally {
1799
+ stopListening();
1800
+ }
1801
+ }
1802
+ function interrupted() {
1803
+ return new CliError("interrupted", "Stopped before the download finished: nothing was saved.");
1804
+ }
1805
+ async function transfer(mediaId, key, stop, sink) {
1806
+ const connection = new AbortController();
1807
+ const hangUp = () => connection.abort(stop.reason);
1808
+ stop.addEventListener("abort", hangUp, { once: true });
1809
+ if (stop.aborted) hangUp();
1810
+ let idle;
1811
+ const quiet = () => connection.abort(new DOMException("Nothing arrived in time.", "TimeoutError"));
1812
+ try {
1813
+ const { response, url } = await openDownload(`/v1/media/${encodeURIComponent(mediaId)}`, {
1814
+ key,
1815
+ signal: connection.signal
1816
+ });
1817
+ const reader = response.body?.getReader();
1818
+ try {
1819
+ const started = await sink.start(response.headers);
1820
+ let size = 0;
1821
+ while (reader !== void 0) {
1822
+ idle = setTimeout(quiet, IDLE_TIMEOUT_MS);
1823
+ const read = await untilAborted(reader.read(), connection.signal).catch((cause) => {
1824
+ throw stop.aborted ? cause : new CheslyNetworkError(url, cause, IDLE_TIMEOUT_MS, true);
1825
+ }).finally(() => clearTimeout(idle));
1826
+ if (read.done) break;
1827
+ await sink.write(read.value);
1828
+ size += read.value.byteLength;
1829
+ }
1830
+ const length = wholeLength(response.headers);
1831
+ if (length !== void 0 && size !== length) {
1832
+ throw new CheslyNetworkError(url, `it ended after ${size} of ${length} bytes`, IDLE_TIMEOUT_MS, true);
1833
+ }
1834
+ return { started, headers: response.headers, size };
1835
+ } finally {
1836
+ await reader?.cancel().catch(() => {
1837
+ });
1838
+ }
1839
+ } finally {
1840
+ clearTimeout(idle);
1841
+ stop.removeEventListener("abort", hangUp);
1842
+ }
1843
+ }
1844
+ function untilAborted(promise, signal) {
1845
+ if (signal.aborted) return Promise.reject(signal.reason);
1846
+ return new Promise((resolvePromise, reject) => {
1847
+ const abort = () => reject(signal.reason);
1848
+ signal.addEventListener("abort", abort, { once: true });
1849
+ promise.then(
1850
+ (value) => {
1851
+ signal.removeEventListener("abort", abort);
1852
+ resolvePromise(value);
1853
+ },
1854
+ (error) => {
1855
+ signal.removeEventListener("abort", abort);
1856
+ reject(error);
1857
+ }
1858
+ );
1859
+ });
1860
+ }
1861
+ function wholeLength(headers) {
1862
+ const encoding = headers.get("content-encoding")?.trim().toLowerCase();
1863
+ const length = headers.get("content-length")?.trim();
1864
+ if (encoding !== void 0 && encoding !== "" && encoding !== "identity" || length === void 0) return void 0;
1865
+ return /^\d+$/.test(length) ? Number(length) : void 0;
1866
+ }
1867
+ function downloadName(headers, mediaId) {
1868
+ const sent = sentName(headers);
1869
+ if (sent !== null) return sent;
1870
+ const extension = extensionFor(mediaTypeOf2(headers));
1871
+ return fitName(extension === void 0 ? mediaId : `${mediaId}.${extension}`);
1872
+ }
1873
+ function sentName(headers) {
1874
+ const name = nameIn(headers.get("content-disposition"));
1875
+ const safe = name === null ? null : safeFileName(name);
1876
+ return safe === "download" ? null : safe;
1877
+ }
1878
+ function nameIn(disposition) {
1879
+ if (disposition === null) return null;
1880
+ const extended = /(?:^|;)\s*filename\*\s*=\s*([^;]*)/i.exec(disposition)?.[1]?.trim();
1881
+ const encoded = extended === void 0 ? null : /^([\w!#$%&+^`{}~-]+)'[^']*'(.*)$/.exec(extended);
1882
+ if (encoded !== null) {
1883
+ const decoded = decodeExtended(encoded[1] ?? "", encoded[2] ?? "");
1884
+ if (decoded !== null && decoded.trim() !== "") return decoded;
1885
+ }
1886
+ const plain = /(?:^|;)\s*filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;\s]+))/i.exec(disposition);
1887
+ if (plain === null) return null;
1888
+ return plain[1] === void 0 ? plain[2] ?? null : plain[1].replace(/\\(.)/g, "$1");
1889
+ }
1890
+ function decodeExtended(charset, value) {
1891
+ try {
1892
+ if (/^utf-8$/i.test(charset)) return decodeURIComponent(value);
1893
+ if (/^iso-8859-1$/i.test(charset)) {
1894
+ return value.replace(/%([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
1895
+ }
1896
+ } catch {
1897
+ }
1898
+ return null;
1899
+ }
1900
+ function safeFileName(name) {
1901
+ const cleaned = name.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "").replace(new RegExp("\\p{Cs}", "gu"), "").replace(/[\\/:*?"<>|]/g, "_").replace(/^[\s.-]+/, "").replace(/[\s.]+$/, "");
1902
+ if (cleaned === "") return null;
1903
+ return fitName(WINDOWS_DEVICE.test(cleaned) ? `_${cleaned}` : cleaned);
1904
+ }
1905
+ function fitName(name) {
1906
+ if (Buffer.byteLength(name) <= MAX_NAME_BYTES) return name;
1907
+ const dot = name.lastIndexOf(".");
1908
+ const extension = dot > 0 && name.length - dot <= 16 ? name.slice(dot) : "";
1909
+ let room = MAX_NAME_BYTES - Buffer.byteLength(extension);
1910
+ let stem = "";
1911
+ for (const char of name.slice(0, name.length - extension.length)) {
1912
+ room -= Buffer.byteLength(char);
1913
+ if (room < 0) break;
1914
+ stem += char;
1915
+ }
1916
+ return `${stem.replace(/[\s.]+$/, "")}${extension}`;
1917
+ }
1918
+ function mediaTypeOf2(headers) {
1919
+ return headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() || "application/octet-stream";
1920
+ }
1921
+ function fileType(headers) {
1922
+ const type = mediaTypeOf2(headers);
1923
+ const name = type === "application/octet-stream" ? sentName(headers) : null;
1924
+ return name === null ? type : mimeTypeOf(name);
1925
+ }
1926
+ function shownPath(path) {
1927
+ const fromHere = relative(process.cwd(), path);
1928
+ const outside = fromHere === "" || fromHere === ".." || fromHere.startsWith(`..${sep}`) || isAbsolute(fromHere);
1929
+ return outside ? path : fromHere;
1930
+ }
1931
+
1932
+ // src/commands/download.ts
1933
+ function registerDownload(program, io) {
1934
+ program.command("download").description("Download a file from a message: a photo, a video, a voice note, a document or an email's attachment").argument("<media_id>", "the file: a media_ ID from chesly read", parseMediaId).option("-o, --output <path>", "save it here: a file name, a directory, or - for stdout (default: its own name, in this directory)").option("--force", "replace a file that is already there").addHelpText(
1935
+ "after",
1936
+ `
1937
+ chesly read shows each file in a chat on a line of its own, under the
1938
+ message that carries it, with the media ID this command takes:
1939
+ [image] beach.jpg \xB7 media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv
1940
+ A file is a photo, a video, a voice note or a document, or each of an
1941
+ email's attachments. In JSON its media ID is a message's media.id, or the
1942
+ id of each of the message's email.attachments.
1943
+
1944
+ The file is saved under its own name in this directory, or where -o says:
1945
+ a file name, or a directory to save it in under its own name. Its own name
1946
+ is the one it was sent with, made safe to save (never a path, a hidden file
1947
+ or one starting with -); without one, it is the media ID with the type's
1948
+ extension. A file already there is never replaced without --force: the
1949
+ command exits 2 (file_exists) and saves nothing. The file is written under
1950
+ a temporary name and takes its name once whole, so a failed or stopped
1951
+ download leaves nothing behind.
1952
+
1953
+ Prints { "path", "size", "mime_type" }: where the file was saved (a whole
1954
+ path), its size in bytes and its type; "Saved <path> \xB7 <size> \xB7 <type>" in a
1955
+ terminal. With -o - the file's bytes go to stdout instead, and nothing else
1956
+ does; stdout must then be a pipe or a file, never a terminal.
1957
+
1958
+ A file is at most 50 MB. An unknown media ID exits 4 (media_not_found), a
1959
+ file no longer kept exits 1 (media_expired). A file briefly unavailable
1960
+ (media_unavailable), a 502, 503, 504 or 429, or a dropped connection is
1961
+ asked for again as a send is: after the answer's Retry-After, at most 10 s,
1962
+ or 1 s and then 2 s, twice at most; then it exits 5 (1 for a connection).
1963
+ A download that sends nothing for 30 s has dropped. With -o -, nothing is
1964
+ asked for again once the first bytes went out.
1965
+
1966
+ Examples:
1967
+ chesly read "Mom"
1968
+ chesly download media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv -o photo.jpg
1969
+ chesly download media_Y2hlc2x5LmFwcC9CZWFjaFBob3Rv -o ~/Downloads
1970
+ chesly download media_Y2hlc2x5LmFwcC9JbnZvaWNlUGRm -o - | pdftotext - -`
1971
+ ).action(async (mediaId, options, command) => {
1972
+ const out = new Output(io, command.optsWithGlobals());
1973
+ const force = options.force === true;
1974
+ if (options.output === "-") {
1975
+ if (io.isTTY) {
1976
+ throw new CliError(
1977
+ "usage_error",
1978
+ "-o - writes the file to stdout, and stdout is a terminal. Pipe it, or give a file name.",
1979
+ EXIT.USAGE
1980
+ );
1981
+ }
1982
+ await downloadToStdout(mediaId, (await requireKey()).key, io);
1983
+ return;
1984
+ }
1985
+ const place = await placeFor(options.output, force);
1986
+ const saved = await downloadToFile(mediaId, (await requireKey()).key, place, force, io);
1987
+ out.result(
1988
+ { path: saved.path, size: saved.size, mime_type: saved.mimeType },
1989
+ () => `Saved ${shownPath(saved.path)} \xB7 ${formatBytes(saved.size)} \xB7 ${saved.mimeType}`
1990
+ );
1991
+ });
1992
+ }
1993
+
1994
+ // src/commands/send.ts
1995
+ import { randomUUID } from "crypto";
1996
+
1997
+ // src/resolve-chat.ts
1998
+ var LOOKUP_LIMIT = 10;
1999
+ var CHAT_ARGUMENT_HELP = `A <chat> is a chat ID (chat_\u2026) or a name. An exact name wins, in any case;
2000
+ so does the only partial match. No match, or several, exits 4, and JSON
2001
+ mode lists the chats a name could mean as "candidates". Names are looked up
2002
+ on every network but email; --network names the one to look in (an email
2003
+ thread's name is its subject: --network email).`;
2004
+ async function resolveChat(arg, key, options = {}) {
2005
+ const name = arg.trim();
2006
+ if (name.startsWith("chat_")) return { id: name, name: null };
2007
+ if (name === "") throw new CliError("usage_error", "Give a chat ID (chat_\u2026) or a chat name.", EXIT.USAGE);
2008
+ const answer = await apiRequest("/v1/chats", {
2009
+ key: await key(),
2010
+ query: { q: name, archived: "all", limit: LOOKUP_LIMIT, network: options.network, account_id: options.accountId }
2011
+ });
2012
+ const page = expectAnswer(answer, isChatPage, "a page of chats");
2013
+ const exact = page.chats.filter((chat) => sameName(chat.name, name));
2014
+ const candidates = exact.length > 0 ? exact : page.chats;
2015
+ const [first, ...others] = candidates;
2016
+ if (first === void 0) {
2017
+ throw new CliError("chat_not_found", `No chat matches "${name}".`, EXIT.NOT_FOUND, {
2018
+ hint: "Run `chesly chats` to list your chats, or pass a chat ID."
2019
+ });
2020
+ }
2021
+ if (others.length === 0) return { id: first.id, name: first.name ?? null };
2022
+ const count2 = `${page.next_cursor ? "at least " : ""}${candidates.length}`;
2023
+ throw new CliError("ambiguous_chat", `"${name}" matches ${count2} chats. Use one of their chat IDs instead.`, EXIT.NOT_FOUND, {
2024
+ extras: { candidates },
2025
+ hint: indent(chatTable(candidates), " ")
2026
+ });
2027
+ }
2028
+ function sameName(chatName, name) {
2029
+ return (chatName ?? "").trim().localeCompare(name, void 0, { sensitivity: "accent" }) === 0;
2030
+ }
2031
+
2032
+ // src/upload.ts
2033
+ import { openAsBlob } from "fs";
2034
+ import { stat as stat2 } from "fs/promises";
2035
+ import { basename } from "path";
2036
+ var MAX_UPLOAD_BYTES = 5e7;
1586
2037
  var SLOWEST_UPLOAD_BYTES_PER_SECOND = 131072;
1587
2038
  async function readUpload(path) {
1588
2039
  try {
1589
- const info = await stat(path);
2040
+ const info = await stat2(path);
1590
2041
  if (!info.isFile()) throw new CliError("file_unreadable", `${path} is not a file.`, EXIT.USAGE);
1591
2042
  if (info.size > MAX_UPLOAD_BYTES) {
1592
2043
  throw new CliError("media_too_large", `${path} is over 50 MB, the most a message can carry.`);
@@ -1594,7 +2045,7 @@ async function readUpload(path) {
1594
2045
  return { blob: await openAsBlob(path, { type: mimeTypeOf(path) }), name: basename(path), size: info.size };
1595
2046
  } catch (error) {
1596
2047
  if (error instanceof CliError) throw error;
1597
- throw new CliError("file_unreadable", `Can't read ${path}: ${reasonOf2(error)}`, EXIT.USAGE);
2048
+ throw new CliError("file_unreadable", `Can't read ${path}: ${fileErrorReason(error)}`, EXIT.USAGE);
1598
2049
  }
1599
2050
  }
1600
2051
  async function uploadFile(file, key) {
@@ -1608,22 +2059,13 @@ async function uploadFile(file, key) {
1608
2059
  if (!isMediaUpload(upload)) throw new CliError("invalid_response", "The API sent no media ID for the upload.");
1609
2060
  return upload;
1610
2061
  }
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";
1619
- }
1620
2062
 
1621
2063
  // src/commands/send.ts
1622
2064
  var WAIT_MS = 3e4;
1623
2065
  var POLL_MS = 1e3;
1624
2066
  var MIN_POLL_MS = 1e3;
1625
2067
  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(
2068
+ 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, or 25 MB to email); the text is its caption, or the email's body").option("--media-id <id>", "attach a file by its media_ ID: one from chesly read, to forward it, or one uploaded before").option("--wait", "wait up to 30 s until the network has it: sent, delivered or failed").option(
1627
2069
  "--idempotency-key <key>",
1628
2070
  "send at most once per key, however often the command runs (default: a new key)",
1629
2071
  parseIdempotencyKey
@@ -1652,6 +2094,13 @@ sending twice, pass the same --idempotency-key again. A file send that gives
1652
2094
  up also names its upload: retry it with --media-id <id> instead of --file, as
1653
2095
  a new upload would make another media ID, which the same key refuses (422).
1654
2096
 
2097
+ In an email thread, --file sends the file as the reply's attachment, with
2098
+ the text as its body. Email providers refuse files over 25 MB, so a bigger
2099
+ one is refused there (media_too_large).
2100
+
2101
+ To forward a file someone sent, give its media ID from chesly read as
2102
+ --media-id: it goes to this chat with no download or upload.
2103
+
1655
2104
  Pass the text on stdin with a quoted heredoc (- <<'EOF'), not as a
1656
2105
  double-quoted argument: inside double quotes the shell still expands $ and
1657
2106
  backticks, while the quoted EOF keeps the text exactly as written.
@@ -1665,6 +2114,9 @@ Examples:
1665
2114
  EOF
1666
2115
  chesly send chat_7Hq2mR9xLp4vT1sK8nWz - --file report.pdf <<'EOF'
1667
2116
  The report is attached.
2117
+ EOF
2118
+ chesly send "Invoice 42" - --network email --file receipt.pdf <<'EOF'
2119
+ Paid, the receipt is attached.
1668
2120
  EOF`
1669
2121
  ).action(async (chat, text, options, command) => {
1670
2122
  const out = new Output(io, command.optsWithGlobals());
@@ -2526,7 +2978,7 @@ var STREAM_PATH = "/v1/events/stream";
2526
2978
  var FIRST_RETRY_MS = 3e3;
2527
2979
  var MIN_RETRY_MS = 1e3;
2528
2980
  var MAX_RETRY_MS = 3e4;
2529
- var IDLE_TIMEOUT_MS = 45e3;
2981
+ var IDLE_TIMEOUT_MS2 = 45e3;
2530
2982
  function registerWatch(program, io) {
2531
2983
  program.command("watch").description("Stream your events live, one line each, until Ctrl+C").option("--chat <chat>", "only this chat: a chat ID (chat_\u2026) or a chat name").option("--account <acct_id>", "only this account: an acct_ ID from chesly accounts").option("--types <a,b>", "only these event types, such as message.received,message.sent", parseList).option("--networks <a,b>", "only these networks, such as whatsapp,telegram (email only when named)", parseList).option("--after <evt_id>", "start after this event instead of now (as far back as your plan's event history)").addHelpText(
2532
2984
  "after",
@@ -2602,7 +3054,7 @@ async function watchEvents(out, key, filters, after) {
2602
3054
  });
2603
3055
  connected = true;
2604
3056
  try {
2605
- for await (const event of readEventStream(response, { idleTimeoutMs: IDLE_TIMEOUT_MS })) {
3057
+ for await (const event of readEventStream(response, { idleTimeoutMs: IDLE_TIMEOUT_MS2 })) {
2606
3058
  if (stopped.signal.aborted) return;
2607
3059
  if (event.retry !== void 0) retryMs = Math.min(Math.max(event.retry, MIN_RETRY_MS), MAX_RETRY_MS);
2608
3060
  if (event.data === null) {
@@ -2893,13 +3345,14 @@ Exit codes:
2893
3345
  running (409), or a send the network didn't confirm (check the chat
2894
3346
  before sending again); retry_after, when there is one, says when
2895
3347
  6 payment required: an API plan is needed, or this period's transcription
2896
- minutes are used up
3348
+ minutes are used up (Starter has none)
2897
3349
 
2898
3350
  Examples:
2899
3351
  chesly catchup your unread chats and their latest messages
2900
3352
  chesly send "Mom" - --wait <<'EOF' the text on stdin, exactly as written
2901
3353
  On my way
2902
3354
  EOF
3355
+ chesly download media_\u2026 a file from a message, by its media ID
2903
3356
  chesly watch --json live events, one JSON object a line
2904
3357
  chesly chats --network email your email threads
2905
3358
 
@@ -2930,6 +3383,7 @@ function buildProgram(io, json) {
2930
3383
  registerSend(program, io);
2931
3384
  registerEdit(program, io);
2932
3385
  registerDelete(program, io);
3386
+ registerDownload(program, io);
2933
3387
  registerWatch(program, io);
2934
3388
  registerWebhooks(program, io);
2935
3389
  registerKeys(program, io);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chesly",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Chesly CLI: your chats from the terminal and your agents",
5
5
  "license": "MIT",
6
6
  "type": "module",