chesly 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chesly, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,414 @@
1
- # Temporary Holding Version
1
+ # Chesly CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your chats from the terminal, for you and your agents. `chesly` is the command-line client for the
4
+ [Chesly](https://chesly.app) API. It is built for agents (Claude Code, Codex, OpenClaw) as much as
5
+ for people: JSON when piped, stable exit codes, and it never prompts.
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.
10
+
11
+ ## Install
12
+
13
+ For the alpha, install from the repo. You need Node 20 or later.
14
+
15
+ ```sh
16
+ git clone https://github.com/chesly-app/cli && cd cli
17
+ npm install # also builds dist/
18
+ npm install -g .
19
+ ```
20
+
21
+ Once the repo is public, one line does it: `npm i -g github:chesly-app/cli`.
22
+
23
+ ## Sign in
24
+
25
+ ```sh
26
+ chesly login # approve the code on web.chesly.app
27
+ chesly login --key - < chesly-key.txt # or store a key you already have (checked first)
28
+ ```
29
+
30
+ `chesly login` prints a link and a code, opens your browser wherever one can show (not over SSH,
31
+ not in CI, and not with `--no-browser`), and waits until you approve the code. It never reads
32
+ input. In JSON mode (piped, or `--json`) the link and the code are one JSON line on stderr:
33
+
34
+ ```json
35
+ {"verification_uri_complete":"https://web.chesly.app/cli?code=ABCD-EFGH","user_code":"ABCD-EFGH","expires_in":600}
36
+ ```
37
+
38
+ Once you approve, stdout holds the result: where the key went and its details, never the key itself
39
+ (`key` is `null` if they didn't load):
40
+
41
+ ```json
42
+ {"status":"signed_in","stored_in":"keychain","key":{"id":"…","name":"Chesly CLI on my-laptop","scope":"full","api_version":"2026-11-01"}}
43
+ ```
44
+
45
+ ### Signing in from an agent
46
+
47
+ An agent whose tool shows a command's output only once it ends can't relay the link while
48
+ `chesly login` waits. It signs in in two steps instead:
49
+
50
+ ```sh
51
+ chesly login --no-wait # prints the link and the code, and exits 0
52
+ chesly login --wait # once the person has the link: waits for the approval, stores the key
53
+ ```
54
+
55
+ `--no-wait` prints `{"status":"pending","verification_uri_complete":"…","user_code":"…","expires_in":600}`
56
+ on stdout (and opens the browser, as above). The sign-in waits in `~/.config/chesly/pending-login.json`
57
+ (mode 0600) until `--wait` finishes it or the code expires, 10 minutes later. A `--wait` cut short
58
+ (Ctrl+C, a tool's time limit) can run again. An agent whose tool streams output can instead start
59
+ `chesly login` in the background and relay the first line of stderr.
60
+
61
+ The key goes to your OS keychain (macOS Keychain, Windows Credential Manager, or the Secret Service
62
+ on Linux). Where there is none, it goes to `~/.config/chesly/credentials.json` with mode 0600.
63
+
64
+ A keychain that refuses (`keychain_error`) or doesn't answer within 10 seconds (`keychain_timeout`:
65
+ locked, or showing a dialog nobody answers) never leaves a command waiting:
66
+ - reading the key falls back to the credentials file when it holds one; only a read with no key in
67
+ the file fails with that code;
68
+ - plain `chesly login` and `chesly login --no-wait` stop with that code (exit 1), unless a key in the
69
+ credentials file still works: the keychain may hold a working key, and another sign-in would add
70
+ a key toward the 25;
71
+ - `chesly login --key` and `chesly login --force` store the key in the credentials file instead and
72
+ succeed (after up to 20 seconds when the keychain doesn't answer), as does `chesly login --wait`;
73
+ - `chesly logout` fails with that code too, but still removes the file and lists what it removed in
74
+ `removed`.
75
+
76
+ `--key -` reads the key from stdin. Never put a key itself on the command line: it would show in the
77
+ process list and your shell history. For CI and servers, set `CHESLY_API_KEY` instead. It wins over
78
+ the stored key.
79
+
80
+ Each sign-in makes a new key, and an account can have 25. So when the key `chesly login` stored
81
+ still works, `chesly login` says "Already signed in" and stops (`{"status":"already_signed_in",...}`
82
+ in JSON mode). `chesly login --force` signs in anyway, with a new key, and revokes the keys it
83
+ replaces: the ones it saw when it started that no store keeps any more, each by itself (the new key
84
+ steps in only for a read-only one). Without `--force`, only a stored key found not working is
85
+ revoked. Any other key the new one replaced, or one a store kept, is left alone, and if it still
86
+ works a `key_still_active` warning names it (ID, first 12 and last 4 characters) for the dashboard.
87
+ The two-step sign-in below does the same when `--wait` stores its key, for the keys `--no-wait` saw.
88
+
89
+ `chesly logout` revokes the key it stored, so the key stops working everywhere, then removes it from
90
+ this computer. When it can't revoke it from here (offline, or a read-only key), it still signs out,
91
+ and names the key that is still active (its ID, first 12 and last 4 characters): revoke it with
92
+ `chesly keys revoke <key_id>`, or in the dashboard at web.chesly.app/api/keys. In JSON mode the
93
+ result lists each key as `{"id","prefix","last4","revoked"}`, and each one still active is also a
94
+ `key_still_active` warning on stderr. `CHESLY_API_KEY` is never touched.
95
+
96
+ ## Read your chats
97
+
98
+ ```sh
99
+ chesly catchup # unread chats with their latest messages, in one call
100
+ chesly chats --unread # chats with unread messages
101
+ chesly read "Mom" # a chat's latest messages, by name or chat ID
102
+ chesly search "flight" --chat "Mom" # search every chat, or one
103
+ chesly accounts # your connected accounts and their status
104
+ ```
105
+
106
+ ### Email and other networks
107
+
108
+ Email is left out of `chats`, `catchup` and `search` unless you ask for it with `--network email`.
109
+ `--network` takes any one network, and on `read` and `send` it says where to look a chat name up:
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.
113
+
114
+ ```sh
115
+ chesly chats --network email # your email threads
116
+ chesly catchup --network email # unread email, with the latest messages
117
+ chesly read "Invoice 42" --network email # an email thread, by its subject
118
+ chesly search "boarding pass" --network whatsapp # one network only
119
+ chesly send "Invoice 42" - --network email <<'EOF' # a reply to that thread
120
+ Paid, thank you.
121
+ EOF
122
+ ```
123
+
124
+ ## Send messages
125
+
126
+ ```sh
127
+ chesly send "Mom" - <<'EOF' # the text, from stdin
128
+ On my way
129
+ EOF
130
+ chesly send "Mom" - --wait <<'EOF' # wait until the network has it
131
+ On my way
132
+ EOF
133
+ chesly send "Mom" - --reply-to msg_... <<'EOF' # a reply
134
+ Yes
135
+ EOF
136
+ chesly send "Mom" - --file plan.pdf <<'EOF' # a file (at most 50 MB), the text its caption
137
+ The plan
138
+ EOF
139
+ chesly send "Mom" - --media-id media_... <<'EOF' # a file uploaded before (a retry of a file send)
140
+ The plan
141
+ EOF
142
+ ```
143
+
144
+ Pass the text on stdin with a quoted heredoc (`- <<'EOF'`), never as a double-quoted argument:
145
+ inside double quotes the shell still expands `$` and backticks, so "It costs $5" would arrive as
146
+ "It costs ", while the quotes around `EOF` keep the text exactly as written.
147
+
148
+ A file can be at most 50 MB (50,000,000 bytes); a bigger one is refused before anything is uploaded.
149
+ An upload must arrive whole within 60 seconds, at 50 KB/s or faster on average. A slower one is
150
+ refused (408 `upload_timeout`), and so are the account's uploads for the next 60 seconds (429
151
+ `rate_limited`, with the seconds left); both exit 5. On a slow connection, send a smaller file.
152
+
153
+ `send` prints the message the API answered. Its `delivery.status` is `queued` until the network
154
+ takes it; `--wait` checks every second (or later, when a refused check's Retry-After says so),
155
+ within 30 seconds in all, until it is `sent`, `delivered` or `failed` (`delivered` comes only where
156
+ the network reports it, as iMessage does; elsewhere a send ends at `sent`). Each check counts as an
157
+ API call. A failure the network confirms exits 1
158
+ (`delivery_failed`) and says why. One it didn't confirm (`delivery.error.certain: false`: a timeout,
159
+ or an error the network didn't explain) reads `unconfirmed`, because the message may have been
160
+ delivered: check the chat before you send it again. `--wait` goes on asking, since such a failure
161
+ can still turn out sent, or certain; if it stays unconfirmed, `send` exits 5
162
+ (`delivery_unconfirmed`). Still
163
+ queued after 30 seconds exits 0, with the message as it was. Once the message went out it is always
164
+ printed and the exit is 0, even if following it fails (a 401 or 402 on a check, say): that is a
165
+ `delivery_wait_failed` warning on stderr, with the `idempotency_key` that asks the API for its
166
+ answer again.
167
+
168
+ Sends go only to chats you already have: there is no way to start a new conversation. Each
169
+ connected account can send 60 messages an hour and 250 a day on WhatsApp, and 30 an hour and 150 a
170
+ day on every other network, email included. Over a cap, `send` exits 5 with the time to wait.
171
+ Automation can get an account restricted by its network, a LinkedIn account in particular, which
172
+ is why the caps exist. `chesly usage` shows how much each account has left.
173
+
174
+ **Sending at most once.** Every send carries an `Idempotency-Key`: a new one per run unless you pass
175
+ `--idempotency-key <key>`. The CLI retries a network error, a 502, 503 or 504, or a 429 (twice),
176
+ and asks again while a first attempt is still running (409 `idempotency_in_progress`: 3 tries,
177
+ then exit 5), always with the same key, so a flaky connection never sends a message twice. Each
178
+ retry waits for the answer's `Retry-After`, at most 10 seconds, or 1 and then 2 seconds without one;
179
+ a 429 that lifts later than that (a send cap, say) exits 5 at once, with `retry_after`. When it
180
+ gives up without knowing whether the message went out, the error carries the key as
181
+ `idempotency_key`: run the command again with `--idempotency-key <that key>`, and the API answers
182
+ with the first attempt's result instead of sending again. A file send's error also carries its
183
+ upload as `media_id`: retry with `--media-id <that id>` instead of `--file`, since a new upload
184
+ would be a new media ID, which the same key refuses (422 `idempotency_key_reused`).
185
+
186
+ ## Watch events
187
+
188
+ ```sh
189
+ chesly watch --json # every event, one JSON object a line
190
+ chesly watch --chat "Mom" --types message.received # one chat, one type
191
+ chesly watch --networks email # email events (left out otherwise)
192
+ chesly watch --after evt_... # from a past event (within your plan's event history)
193
+ ```
194
+
195
+ `watch` prints events as they happen, until Ctrl+C (exit 0). In JSON mode each line is an event as
196
+ the API sends it:
197
+
198
+ ```json
199
+ {"id":"evt_...","type":"message.received","timestamp":"2026-10-28T09:05:00.000Z","data":{"message":{...},"chat":{"id":"chat_...","name":"Mom","network":"whatsapp","type":"dm"}}}
200
+ ```
201
+
202
+ In a terminal it prints `09:05 [whatsapp] Mom — Mom: Are you coming?` for messages and
203
+ `09:07 chat.read chat_...` for the rest.
204
+
205
+ The types are `message.received`, `message.sent` (your own, from any device), `message.edited`,
206
+ `message.deleted`, `message.delivery_failed`, `chat.created`, `chat.updated`, `chat.read`,
207
+ `account.connected`, `account.disconnected`, `account.needs_attention`, `reaction.added` and
208
+ `reaction.removed`.
209
+
210
+ When the connection drops, `watch` reconnects by itself (after 3 seconds, then longer, up to 30) and
211
+ resumes after the last event ID the stream gave it: an event's, or the stream's starting point when
212
+ the API names one. From then on nothing is missed. Before it has one, events that arrive while it
213
+ reconnects can be missed; `--after <evt_id>` pins where it starts. An event can arrive twice, so skip
214
+ IDs you have already handled. A `message.delivery_failed` the network didn't confirm
215
+ (`error.certain: false`) may have been delivered, and a terminal shows it as unconfirmed; if it later
216
+ turns out certain, a second `message.delivery_failed` for the same message follows, with `certain:
217
+ true`. The wait between tries keeps growing while connections drop before
218
+ delivering any event. An event too large to read (a line over 1 MiB, or over 4 MiB in all) ends the
219
+ connection; if the same one does so twice in a row, `watch` resumes after it and warns
220
+ `event_too_large` with its ID. A resume point older than your plan's event history starts again
221
+ from new events, with a warning on stderr. How many days of events your plan keeps, and how many
222
+ streams you can have open at once, are the plan's (`chesly usage` shows both); one stream more
223
+ exits 5 (`too_many_streams`).
224
+
225
+ ## Webhooks
226
+
227
+ Instead of keeping `watch` running, Chesly can POST each event to a URL of yours.
228
+
229
+ ```sh
230
+ chesly webhooks create https://example.com/chesly --types message.received,message.sent
231
+ chesly webhooks list
232
+ chesly webhooks test wh_... # sends a webhook.test event
233
+ chesly webhooks deliveries wh_... # how the deliveries went: status, attempts, answers
234
+ chesly webhooks deliveries wh_... --status failed
235
+ chesly webhooks rotate wh_... # a new secret; the old one keeps working for 24 hours
236
+ chesly webhooks delete wh_...
237
+ ```
238
+
239
+ `create` prints the webhook's signing secret (`whsec_...`) once: keep it. `--networks` limits a
240
+ webhook to some networks (it gets every network but email unless it names email), and
241
+ `--payload ids` sends only the IDs in `data` instead of the whole message (`full`, the default).
242
+ `deliveries` lists the newest 50 first: `--status` keeps one kind (`pending`, `succeeded`, `failed`
243
+ or `discarded`), `--limit` takes up to 100, and `--cursor` with a page's `next_cursor` goes further
244
+ back.
245
+
246
+ Each delivery is a `POST` with the event as its JSON body, signed the
247
+ [Standard Webhooks](https://www.standardwebhooks.com) way: the `webhook-id` header (the event ID,
248
+ `evt_...`), `webhook-timestamp` and `webhook-signature`. Check the signature on the raw body before
249
+ you trust it, for example with the `standardwebhooks` package:
250
+
251
+ ```js
252
+ import { Webhook } from 'standardwebhooks';
253
+
254
+ const webhook = new Webhook(process.env.CHESLY_WEBHOOK_SECRET); // whsec_...
255
+
256
+ // rawBody: the request body exactly as received, as a string, before any JSON parsing.
257
+ const event = webhook.verify(rawBody, {
258
+ 'webhook-id': request.headers['webhook-id'],
259
+ 'webhook-timestamp': request.headers['webhook-timestamp'],
260
+ 'webhook-signature': request.headers['webhook-signature'],
261
+ }); // throws WebhookVerificationError when the signature or the timestamp doesn't check out
262
+ ```
263
+
264
+ Answer with any 2xx to accept a delivery. Anything else, a redirect included, is retried after 5
265
+ seconds, 5 minutes, 30 minutes, 2, 5, 10 and 10 hours (about 28 hours in all). A 410 answer
266
+ disables the webhook at once, and so do 3 days of failures. The same event can arrive twice: use
267
+ `webhook-id` to skip duplicates.
268
+
269
+ `list` says why a webhook is off: `disabled: you turned it off`, `it failed for 3 days`, `your
270
+ endpoint answered 410 Gone`, or `the key that set it up was revoked`. That last one comes when
271
+ GitHub's secret scanning finds a Chesly key in public code: Chesly revokes the key and turns off the
272
+ webhooks it made or last changed, since whoever has the key could have pointed them elsewhere.
273
+ Check the URL, then turn the webhook back on in the dashboard at web.chesly.app/api/webhooks.
274
+
275
+ ## Keys and usage
276
+
277
+ ```sh
278
+ chesly keys list # your API keys (only their first 12 and last 4 characters)
279
+ chesly keys revoke <key_id> # the key stops working at its next request
280
+ chesly usage # your plan, this period's calls and minutes, limits and send caps
281
+ ```
282
+
283
+ New keys come from `chesly login`, or from the dashboard at https://web.chesly.app/api/keys. `keys
284
+ list` marks the key this CLI uses, and revoking it says so (run `chesly login` afterwards).
285
+ `chesly key` shows the key in use, masked.
286
+
287
+ `chesly usage` shows, in a terminal:
288
+
289
+ ```
290
+ Plan: Pro, trialing: the trial ends Nov 4
291
+ Calls this period: 12,345 (counted, not billed)
292
+ Transcription this period: 3 of 3,000 min
293
+ Limits: 30 requests a second, 1,800 a minute · 100 API keys · 100 webhooks · 25 event streams · 30 days of event history
294
+ Sends:
295
+ whatsapp · 3/60 this hour · 3/250 today
296
+ telegram · 0/30 this hour · 12/150 today
297
+ ```
298
+
299
+ An API plan is a flat monthly price, Personal or Pro: calls are counted, never billed, and each plan
300
+ has its own transcription minutes and limits (https://web.chesly.app/api/billing). Minutes used
301
+ round down, and once they're used up the line says when they come back
302
+ (`600 of 600 min, used up until Nov 28`). A downgrade waits for the end of the period, and the plan
303
+ line says when (`Plan: Pro, active: changes to Personal on Jan 14`). The request limits apply to
304
+ each key and to all your keys together. With `--json` it prints the API's `GET /v1/me` answer.
305
+
306
+ ## Commands
307
+
308
+ | Command | What it does |
309
+ |---|---|
310
+ | `chesly login [--key <key>\|-] [--no-browser] [--no-wait\|--wait] [--force]` | Signs in through the browser (in two steps with `--no-wait`, then `--wait`), or stores a key after checking it with `GET /v1/me`. A stored key that works means "Already signed in", unless `--force` |
311
+ | `chesly logout` | Revokes the stored key (`DELETE /v1/keys/{key_id}`) and removes it from this computer |
312
+ | `chesly whoami` | Shows the key in use: name, scope, API version and the plan's limits (`GET /v1/me`) |
313
+ | `chesly key [--reveal]` | Shows the key in use, masked (`ck_live_AbCd…WxYz`); `--reveal` prints the whole key and nothing else |
314
+ | `chesly accounts` | Lists your connected chat accounts and their status (`GET /v1/accounts`) |
315
+ | `chesly chats [--unread] [--account <id>] [--network <name>] [--limit <n>] [--cursor <cursor>]` | Lists your chats, pinned ones first, then the most recent (`GET /v1/chats`) |
316
+ | `chesly read <chat> [--network <name>] [--limit <n>] [--cursor <cursor>]` | Shows a chat's latest messages, oldest first in a terminal (`GET /v1/chats/{chat_id}/messages`) |
317
+ | `chesly search <query> [--chat <chat>] [--network <name>] [--limit <n>]` | Searches your messages, in every chat or one (`GET /v1/messages/search`) |
318
+ | `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
+ | `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`) |
320
+ | `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
+ | `chesly webhooks list\|create\|delete\|rotate\|test\|deliveries` | Manages webhooks (`/v1/webhooks`) |
322
+ | `chesly keys list\|revoke <key_id>` | Lists or revokes API keys (`/v1/keys`) |
323
+ | `chesly usage` | Shows your plan, this period's calls (counted, not billed) and transcription minutes, the plan's limits and send caps (`GET /v1/me`) |
324
+
325
+ Every command takes `--json`. `chesly <command> --help` explains each one, with an example. `--limit`
326
+ is 1 to 100. When there is more, JSON has a `next_cursor`, and the same command with
327
+ `--cursor <next_cursor>` gets the next page (older messages, for `read`).
328
+
329
+ ### Chat names
330
+
331
+ A `<chat>` is a chat ID (`chat_…`) or a name. A name is looked up across your chats, archived ones
332
+ included, on every network but email (add `--network email` for email threads):
333
+
334
+ - an exact name wins, in any case (`mom` finds "Mom");
335
+ - otherwise, the only partial match wins ("book" finds "Mom's book club");
336
+ - no match exits 4 with `chat_not_found`;
337
+ - several matches exit 4 with `ambiguous_chat`, listing the chats it could mean. In JSON mode they
338
+ are the `candidates`, as `/v1/chats` returns them:
339
+
340
+ ```json
341
+ {"type":"https://agents.chesly.app/docs/errors#ambiguous_chat","title":"\"Mom\" matches 2 chats. Use one of their chat IDs instead.","code":"ambiguous_chat","candidates":[{"id":"chat_…","name":"Mom","network":"whatsapp","type":"dm"},{"id":"chat_…","name":"MOM","network":"imessage","type":"dm"}]}
342
+ ```
343
+
344
+ (Each candidate has every chat field; this example shows four.) Run the command again with one of
345
+ their `id`s.
346
+
347
+ ## For agents and scripts
348
+
349
+ - **Output:** tables in a terminal. When stdout is piped, or with `--json`, it prints the API's JSON
350
+ as is; `watch` prints one JSON object a line.
351
+ - **Errors** go to stderr. In JSON mode each one is a single line of problem details. Problem
352
+ details from the API print exactly as the API sent them (`type`, `title`, `status`, `detail`,
353
+ `code`, `request_id`, and `retry_after` when it says when to retry). In a terminal, an error that
354
+ says when to retry ends with `Retry in N s.`, unless its message already says so, and where the
355
+ API's detail names a REST path or parameter (`GET /v1/chats`, `account_id`), the terminal shows
356
+ the error's title and the CLI command to use instead (`chesly chats`, `--account`).
357
+ The CLI's own errors print as `{"type":"https://agents.chesly.app/docs/errors#<code>","title":"...","code":"<code>"}`,
358
+ plus their own fields (`candidates` for an ambiguous chat name, `idempotency_key` for a send that
359
+ may or may not have gone out). An answer without problem details (a gateway's 502, say) gets
360
+ problem details built for it, with the code `http_400`, `http_404`, `http_413`, `http_429`,
361
+ `http_500`, `http_502`, `http_503` or `http_504`, or `http_error` for any other status (the status
362
+ is in `status`). Every code has its entry at https://agents.chesly.app/docs/errors.
363
+ - **Notices** (a reconnecting `watch`, an expired resume point, a `CHESLY_API_KEY` that wins over
364
+ the key `login` stored) go to stderr too, as one JSON line each in JSON mode:
365
+ `{"warning":"<code>","message":"..."}`. Paging hints are for terminals only: JSON has
366
+ `next_cursor`.
367
+ - **Other people's text** (names, messages) never reaches the terminal raw: tables drop escape
368
+ sequences and other control characters, and JSON escapes them, so the parsed text is exact.
369
+ - **Keys** are checked before they are sent, stored or shown: `ck_live_` and 48 letters, digits,
370
+ `_` or `-`. A malformed `CHESLY_API_KEY` or stored key exits 3, and a malformed key given to
371
+ `chesly login --key` exits 2 (usage). Neither is ever printed.
372
+ - **Nothing prompts**, ever. `-` reads stdin only when you pass it, and never a terminal.
373
+ - **Exit codes:**
374
+
375
+ | Code | Meaning |
376
+ |---|---|
377
+ | 0 | ok |
378
+ | 1 | error |
379
+ | 2 | usage |
380
+ | 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) |
382
+ | 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
+ | 6 | payment required: the account needs an API plan, or this period's transcription minutes are used up |
384
+
385
+ - **MCP:** give Claude Code the Chesly MCP server with your key:
386
+
387
+ ```sh
388
+ claude mcp add --transport http chesly https://api.chesly.app/mcp \
389
+ --header "Authorization: Bearer $(chesly key --reveal)"
390
+ ```
391
+
392
+ ## Environment
393
+
394
+ | Variable | Use |
395
+ |---|---|
396
+ | `CHESLY_API_KEY` | The API key to use instead of the stored one |
397
+ | `CHESLY_API_URL` | The API base URL (default `https://api.chesly.app`): `https://`, or `http://` only for this computer (`localhost`, `127.0.0.1`, `[::1]`), since the key would travel in clear text |
398
+
399
+ ## Development
400
+
401
+ ```sh
402
+ npm install
403
+ npm test # vitest; mocked fetch and keychain, no network
404
+ npm run typecheck
405
+ npm run build # tsup -> dist/index.js and dist/errors.js
406
+ npm run export-errors -- <dir> # writes cli-errors.json, cli-warnings.json and cli-api-codes.json
407
+ ```
408
+
409
+ Dependencies are pinned to exact versions, and `.npmrc` sets `min-release-age=14`, so npm never
410
+ installs a version published in the last two weeks.
411
+
412
+ ## License
413
+
414
+ MIT. See [LICENSE](LICENSE).
package/dist/errors.js ADDED
@@ -0,0 +1,171 @@
1
+ // src/errors.ts
2
+ var EXIT = {
3
+ OK: 0,
4
+ ERROR: 1,
5
+ USAGE: 2,
6
+ NOT_SIGNED_IN: 3,
7
+ NOT_FOUND: 4,
8
+ /**
9
+ * Temporary: a 429 (a limit), a 408 (a request, such as an upload, too slow to arrive), a 502-504
10
+ * (briefly unavailable) or a first attempt still running (409). Retry later.
11
+ */
12
+ RETRY_LATER: 5,
13
+ /** A 402: the account needs an API plan, or the plan's transcription minutes for the period are used up. */
14
+ PAYMENT_REQUIRED: 6
15
+ };
16
+ var HTTP_ERROR_TITLES = {
17
+ 400: "Bad Request, without details.",
18
+ 404: "Not Found, without details.",
19
+ 413: "Payload Too Large, without details.",
20
+ 429: "Too Many Requests, without details.",
21
+ 500: "Internal Server Error, without details.",
22
+ 502: "Bad Gateway, without details.",
23
+ 503: "Service Unavailable, without details.",
24
+ 504: "Gateway Timeout, without details."
25
+ };
26
+ function httpErrorCode(status) {
27
+ return status in HTTP_ERROR_TITLES ? `http_${status}` : "http_error";
28
+ }
29
+ var LOCAL_ERROR_CODES = [
30
+ { code: "access_denied", title: "The sign-in was denied." },
31
+ { code: "ambiguous_chat", title: "The chat name matches more than one chat." },
32
+ { code: "chat_not_found", title: "Chat not found." },
33
+ { code: "credentials_file_error", title: "The credentials file couldn't be read or written." },
34
+ { code: "delivery_failed", title: "The network did not take the message." },
35
+ { code: "delivery_unconfirmed", title: "The network didn't confirm the message, so it may have been delivered." },
36
+ { code: "expired_token", title: "The sign-in code expired." },
37
+ { code: "file_unreadable", title: "The file can't be read." },
38
+ { code: "internal_error", title: "Something went wrong on our side." },
39
+ { code: "invalid_api_url", title: "CHESLY_API_URL is not a usable API URL." },
40
+ { code: "invalid_key_format", title: "The API key is not well formed." },
41
+ { code: "invalid_response", title: "The API's answer is not what the CLI expects." },
42
+ { code: "keychain_error", title: "The OS keychain refused." },
43
+ { code: "keychain_timeout", title: "The OS keychain didn't answer in time." },
44
+ { code: "login_not_started", title: "No sign-in is waiting to finish." },
45
+ { code: "media_too_large", title: "The media is too large." },
46
+ { code: "network_error", title: "The CLI couldn't reach the API." },
47
+ { code: "not_signed_in", title: "Not signed in." },
48
+ { code: "usage_error", title: "The command is not valid." },
49
+ ...Object.entries(HTTP_ERROR_TITLES).map(([status, title]) => ({ code: `http_${status}`, title })),
50
+ { code: "http_error", title: "An HTTP error without details." }
51
+ ];
52
+ var API_ERROR_CODES = [
53
+ { code: "invalid_api_key", status: 401, title: "The API key is missing or not valid." },
54
+ { code: "forbidden", status: 403, title: "This request is not allowed." },
55
+ { code: "not_found", status: 404, title: "Not found." },
56
+ { code: "internal_error", status: 500, title: "Something went wrong on our side." },
57
+ { code: "invalid_request", status: 400, title: "The request is not valid." },
58
+ { code: "insufficient_scope", status: 403, title: "This API key does not allow this request." },
59
+ { code: "account_not_found", status: 404, title: "Account not found." },
60
+ { code: "chat_not_found", status: 404, title: "Chat not found." },
61
+ { code: "message_not_found", status: 404, title: "Message not found." },
62
+ { code: "media_not_found", status: 404, title: "Media not found." },
63
+ { code: "media_expired", status: 410, title: "The media has expired." },
64
+ { code: "media_too_large", status: 400, title: "The media is too large." },
65
+ { code: "media_unavailable", status: 503, title: "The media is temporarily unavailable." },
66
+ { code: "invalid_cursor", status: 400, title: "The cursor is not valid." },
67
+ { code: "rate_limited", status: 429, title: "Too many requests." },
68
+ { code: "network_unavailable", status: 503, title: "This network is temporarily unavailable." },
69
+ { code: "search_unavailable", status: 503, title: "Search is temporarily unavailable." },
70
+ { code: "feed_unavailable", status: 503, title: "The feed is temporarily unavailable." },
71
+ { code: "upstream_unavailable", status: 503, title: "Your messages are temporarily unavailable." },
72
+ { code: "signing_key_missing", status: 403, title: "The account signing key is missing." },
73
+ { code: "idempotency_key_invalid", status: 400, title: "The Idempotency-Key header is not valid." },
74
+ { code: "idempotency_key_reused", status: 422, title: "This Idempotency-Key was used for a different request." },
75
+ { code: "idempotency_in_progress", status: 409, title: "A request with this Idempotency-Key is still running." },
76
+ { code: "message_request", status: 409, title: "This chat is a message request." },
77
+ { code: "send_limit_reached", status: 429, title: "This account's send limit is reached." },
78
+ { code: "text_too_long", status: 400, title: "The text is too long for this network." },
79
+ { code: "invalid_reply_to", status: 400, title: "reply_to must be a message in this chat." },
80
+ { code: "unsupported_chat", status: 400, title: "Chesly can't send to this chat." },
81
+ { code: "upload_timeout", status: 408, title: "The upload took too long to arrive." },
82
+ { code: "events_expired", status: 410, title: "These events are no longer kept." },
83
+ { code: "too_many_streams", status: 429, title: "Too many open event streams." },
84
+ { code: "webhook_not_found", status: 404, title: "Webhook not found." },
85
+ { code: "webhook_limit_reached", status: 400, title: "This account has the most webhooks allowed." },
86
+ { code: "invalid_webhook_url", status: 400, title: "This webhook URL can't be used." },
87
+ { code: "not_a_voice_note", status: 400, title: "This message is not a voice note." },
88
+ { code: "transcription_unavailable", status: 503, title: "Transcription is temporarily unavailable." },
89
+ { code: "transcription_failed", status: 422, title: "This voice message could not be transcribed." },
90
+ { code: "key_not_found", status: 404, title: "API key not found." },
91
+ { code: "api_plan_required", status: 402, title: "An API plan is required." },
92
+ { code: "transcription_limit_reached", status: 402, title: "This period's transcription minutes are used up." },
93
+ { code: "already_subscribed", status: 409, title: "You already have an API plan." },
94
+ { code: "terms_changed", status: 409, title: "The API Terms changed." },
95
+ { code: "plan_unavailable", status: 503, title: "Your API plan can't be checked just now." },
96
+ { code: "plan_change_in_progress", status: 409, title: "A change to your plan is already under way." },
97
+ { code: "email_send_failed", status: 502, title: "The email provider refused the message." },
98
+ { code: "account_reconnect_required", status: 409, title: "This account needs to be reconnected." },
99
+ { code: "api_paused", status: 503, title: "The Chesly API is paused." },
100
+ { code: "payload_too_large", status: 413, title: "The request body is too large." }
101
+ ];
102
+ var RETRY_LATER_STATUSES = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
103
+ function apiExitCode(status, code) {
104
+ if (status === 400 && code === "invalid_request") return EXIT.USAGE;
105
+ if (status === 401) return EXIT.NOT_SIGNED_IN;
106
+ if (status === 402) return EXIT.PAYMENT_REQUIRED;
107
+ if (status === 404) return EXIT.NOT_FOUND;
108
+ if (RETRY_LATER_STATUSES.has(status)) return EXIT.RETRY_LATER;
109
+ if (status === 409 && code === "idempotency_in_progress") return EXIT.RETRY_LATER;
110
+ return EXIT.ERROR;
111
+ }
112
+ var LOCAL_WARNING_CODES = [
113
+ { code: "delivery_wait_failed", title: "The message was sent, but following its delivery failed." },
114
+ { code: "env_key_set", title: "CHESLY_API_KEY wins over the key login stored." },
115
+ { code: "event_too_large", title: "An event too large to read was skipped." },
116
+ { code: "events_expired", title: "The resume point is no longer kept, so watching starts from now." },
117
+ { code: "invalid_event", title: "An event the CLI could not read was skipped." },
118
+ { code: "key_details_unavailable", title: "The new key's details didn't load." },
119
+ { code: "key_still_active", title: "A key this CLI no longer uses is still active." },
120
+ { code: "reconnecting", title: "The event stream dropped and is reconnecting." }
121
+ ];
122
+ var KeychainTimeoutError = class extends Error {
123
+ constructor(seconds) {
124
+ super(`The keychain didn't answer within ${seconds} s.`);
125
+ this.seconds = seconds;
126
+ this.name = "KeychainTimeoutError";
127
+ }
128
+ seconds;
129
+ };
130
+ function errorType(code) {
131
+ return `https://agents.chesly.app/docs/errors#${code}`;
132
+ }
133
+ var AnnotatedError = class extends Error {
134
+ constructor(error, extras, hint) {
135
+ super(error.message);
136
+ this.error = error;
137
+ this.extras = extras;
138
+ this.hint = hint;
139
+ this.name = "AnnotatedError";
140
+ }
141
+ error;
142
+ extras;
143
+ hint;
144
+ };
145
+ var CliError = class extends Error {
146
+ constructor(code, message, exitCode = EXIT.ERROR, details = {}) {
147
+ super(message);
148
+ this.code = code;
149
+ this.exitCode = exitCode;
150
+ this.name = "CliError";
151
+ this.extras = details.extras ?? {};
152
+ this.hint = details.hint;
153
+ }
154
+ code;
155
+ exitCode;
156
+ extras;
157
+ hint;
158
+ };
159
+ export {
160
+ API_ERROR_CODES,
161
+ AnnotatedError,
162
+ CliError,
163
+ EXIT,
164
+ KeychainTimeoutError,
165
+ LOCAL_ERROR_CODES,
166
+ LOCAL_WARNING_CODES,
167
+ RETRY_LATER_STATUSES,
168
+ apiExitCode,
169
+ errorType,
170
+ httpErrorCode
171
+ };