@infaris/calendar-cli 0.9.0 → 0.12.1

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
@@ -294,27 +294,165 @@ infaris-calendar attach task --id 427 ./screenshot.png ./logs.pdf
294
294
 
295
295
  10 MB per file, same limit as the web app's attachment upload.
296
296
 
297
- ## Stage a mail draft
297
+ ## Mail drafts
298
298
 
299
- Prepares an editable concept in your own webmail; it never sends anything.
300
- Open the printed URL to review and send it from `/dashboard/mail`.
299
+ Saves a real draft in Concepten of one of your own mailboxes. `mail draft`
300
+ and `mail batch` never send; only [`mail send --yes`](#sending-drafts) does.
301
+ Your default signature is added below the body (do not put
302
+ a closing or signature in the HTML yourself). Without `--from` the draft goes
303
+ to your primary mailbox; a `--from` you have no access to is refused. The
304
+ printed URL opens the saved draft in `/dashboard/mail/compose`.
301
305
 
302
306
  ```bash
303
- infaris-calendar mail draft --to client@example.com --subject "Offerte" \
304
- --body "<p>Hoi,</p><p>Zie bijlage.</p>" --attach ./offerte.pdf
307
+ # New mail with several recipients, a PDF and a screenshot inline
308
+ infaris-calendar mail draft --to kees@example.com,anna@example.com \
309
+ --cc sales@example.com --subject "Offerte" \
310
+ --body-file ./mail.html --image ./screenshot.png --attach ./offerte.pdf
311
+
312
+ # Images referenced in the body are embedded as well (paths relative to the file)
313
+ echo '<p>Hoi Kees,</p><p>Zo ziet het eruit:</p><img src="shot.png">' > ./mail.html
314
+
315
+ # Markdown (.md) or plain text (.txt) bodies work too
316
+ printf 'Hoi Kees,\n\nZo ziet het eruit:\n\n![scherm](shot.png)\n\n- **LCP** 4,1 s\n' > ./mail.md
317
+ infaris-calendar mail draft --to kees@example.com --subject "Meting" --body-file ./mail.md
318
+
319
+ # Which --from addresses can I use, and which signature goes below?
320
+ infaris-calendar mail mailboxes
321
+
322
+ # Reply to a message: find its UID, read it, stage the reply
323
+ infaris-calendar mail messages --search "offerte"
324
+ infaris-calendar mail read 4812
325
+ infaris-calendar mail draft --reply 4812 --body "<p>Dank je, klopt helemaal.</p>"
326
+
327
+ # Change only the text of a draft: recipients, thread, signature, quote and
328
+ # attachments stay. --attach adds a file, --note leaves a note for the reviewer.
329
+ infaris-calendar mail drafts
330
+ infaris-calendar mail draft --edit 977 --body-file ./mail.md
331
+ infaris-calendar mail draft --edit 977 --attach offerte-v2.pdf --drop-attachments
332
+
333
+ # Or build the whole draft anew and remove the old one in one go
334
+ infaris-calendar mail draft --replace 977 --to kees@example.com \
335
+ --subject "Offerte v2" --body-file ./mail.html
336
+
337
+ # Check images, attachments and sizes without saving anything, or look at it
338
+ infaris-calendar mail draft --to kees@example.com --body-file ./mail.html --dry-run
339
+ infaris-calendar mail draft --to kees@example.com --body-file ./mail.md --preview /tmp/mail.html
340
+
341
+ # Read the saved draft back to check it; --preview writes it as the recipient
342
+ # sees it (signature and inline images included) to render and look at
343
+ infaris-calendar mail read 978 --drafts --preview /tmp/draft.html
344
+
345
+ # Many drafts at once (outreach): every draft is checked before any is saved
346
+ cat > drafts.json <<'JSON'
347
+ [
348
+ { "to": "kees@example.com", "subject": "Meting", "bodyFile": "kees.md", "images": ["kees.png"] },
349
+ { "to": ["anna@example.com"], "cc": "sales@example.com", "subject": "Offerte",
350
+ "bodyFile": "anna.md", "attach": ["offerte.pdf"] }
351
+ ]
352
+ JSON
353
+ infaris-calendar mail batch drafts.json --dry-run
354
+ infaris-calendar mail batch drafts.json --write-map map.json
355
+
356
+ # Edited the texts? Redo the batch; each draft replaces its predecessor
357
+ # (matched on the first recipient, or the subject when there is none)
358
+ infaris-calendar mail batch drafts.json --replace-map map.json --write-map map.json
359
+ ```
360
+
361
+ `mail draft` flags:
362
+
363
+ | Flag | Description |
364
+ | --- | --- |
365
+ | `--to/--cc/--bcc <emails...>` | Recipients; repeat or comma-separate. Optional with `--reply` |
366
+ | `--subject <text>` | Subject (default `Re:`/`Fwd:` of the original) |
367
+ | `--body <html>` / `--body-file <path>` | Body above the signature (file `-` = stdin); `.md` is Markdown, `.txt` plain text |
368
+ | `--format <html\|markdown\|text>` | Body format when the extension does not say it |
369
+ | `--image <paths...>` | Images shown inline below the body, in order |
370
+ | `--attach <paths...>` | Files to attach (PDF, images, docx, xlsx, ...) |
371
+ | `--from <email>` | Sender: a mailbox address or alias you have access to |
372
+ | `--no-signature` | Leave out the default signature |
373
+ | `--reply <uid>` / `--reply-all <uid>` | Draft as reply: thread headers, `Re:` and the quoted original |
374
+ | `--forward <uid>` | Draft as forward, with the original attachments (`--no-forward-attachments`) |
375
+ | `--folder <path>` | Folder of the original message (default `INBOX`) |
376
+ | `--source-mailbox <id>` | Mailbox of the original (default: the draft mailbox) |
377
+ | `--replace <uid>` | Replace an existing draft in Concepten |
378
+ | `--edit <uid>` | Change a draft in place: only what you pass changes; `--attach` adds files |
379
+ | `--mailbox <id>` | Mailbox of the draft to `--edit` |
380
+ | `--drop-attachments` | With `--edit`: remove the existing attachments |
381
+ | `--note <text>` | Private note for the reviewer (basis, what to check); shown in Calendar, never sent |
382
+ | `--dry-run` | Print recipients, images and attachments without saving |
383
+ | `--preview <file.html>` | Write the body with inline images to an HTML file; saves nothing |
384
+ | `--no-inline-remote` | Keep `https://` images as links instead of embedding them |
385
+ | `--no-optimize-images` | Do not shrink large inline images |
386
+ | `--json` | Output the saved draft (uid, folder, recipients, files, url) as JSON |
387
+
388
+ Local `<img src>` and Markdown `![](...)` paths in the body (relative to
389
+ `--body-file`, absolute or `file://`) and `--image` files are embedded inline as `cid:` images, so they
390
+ show in the mail itself instead of as a loose attachment. `https://` images
391
+ are downloaded on your machine and embedded too, because mail clients block
392
+ external images by default; one that fails stays a link, with a warning. The
393
+ server shrinks inline images above 200 kB to at most 1600 px wide (PNG
394
+ screenshots without transparency that stay above 1 MB become JPEG); attachments
395
+ are never changed. Images and attachments together may be 20 MB.
396
+
397
+ Other `mail` commands, all read-only except `delete-draft` (removes a draft) and `send` (sends one):
398
+
399
+ | Command | Description |
400
+ | --- | --- |
401
+ | `mail batch <file.json> [--dry-run] [--replace-map f] [--write-map f] [--json]` | Save many drafts; fields as in `mail draft`, paths relative to the file |
402
+ | `mail mailboxes` | Your mailboxes, `--from` addresses and the default signature as text |
403
+ | `mail drafts [--mailbox] [--search] [--limit]` | Newest drafts with UID and link |
404
+ | `mail delete-draft <uid> [--mailbox]` (alias `draft-delete`) | Delete one draft, only from Concepten |
405
+ | `mail messages [--mailbox] [--folder\|--sent] [--search] [--limit]` | List or search messages to find a UID |
406
+ | `mail sent [--mailbox] [--search] [--limit]` | The newest messages in Verzonden |
407
+ | `mail read <uid> [--mailbox] [--folder\|--drafts\|--sent] [--preview f.html]` | Show one message as text; never marks it read. Attachments with type and size, inline images apart. With `--json` and `--drafts`/`--sent`: recipients incl. Bcc, subject, body, `signatureCount`, `agentDraft` and `note` |
408
+ | `mail status <uid\|message-id> [--mailbox]` | Is it still a draft, really in Verzonden, or gone? |
409
+ | `mail send [uids...] [--all-drafts [--filter q]] --yes` | Send existing drafts; see below |
410
+
411
+ `--mailbox` accepts the mailbox id, its address or an alias. The same draft
412
+ actions exist for Claude Desktop/claude.ai in the Calendar mail MCP
413
+ (`/mcp`): `save_mail_draft`, `list_mail_drafts` and `delete_mail_draft`.
414
+
415
+ ### Sending drafts
416
+
417
+ `mail send` sends drafts that are already in Concepten, the same way the
418
+ **Verzenden** button does: SMTP from the draft's own sender address, a copy in
419
+ Verzonden, the draft removed. The draft goes out unchanged (same Message-ID,
420
+ signature, inline images and attachments); only the Bcc header is dropped from
421
+ the sent message (Bcc recipients still receive it) and the date is set to now.
422
+ Only drafts in a mailbox you have access to can be sent, from an address that
423
+ mailbox may send from. **Run it only when the user explicitly asked to send.**
424
+
425
+ ```bash
426
+ infaris-calendar mail drafts # find the UIDs
427
+ infaris-calendar mail send 4812 --dry-run # recipients, subject, files, signatures
428
+ infaris-calendar mail send 4812 --yes # really send
305
429
 
306
- infaris-calendar mail draft --to client@example.com --subject "Screenshot" \
307
- --body-file ./mail.html --from support@ipulse.one --json
430
+ # A batch: 10 s between mails by default, at most 100 per run
431
+ infaris-calendar mail send --all-drafts --filter "subject:Meting" --dry-run
432
+ infaris-calendar mail send --all-drafts --filter "subject:Meting" --yes --delay 15
433
+
434
+ # After an error or timeout: is it in Verzonden or not?
435
+ infaris-calendar mail status 4812
436
+ infaris-calendar mail sent --search "Meting" --limit 5
308
437
  ```
309
438
 
310
439
  | Flag | Description |
311
440
  | --- | --- |
312
- | `--to <email>` | Recipient (required) |
313
- | `--subject <text>` | Subject |
314
- | `--body <html>` / `--body-file <path>` | HTML body (file `-` = stdin) |
315
- | `--from <email>` | Preferred sender mailbox address |
316
- | `--attach <path>` | Image or PDF to attach (max 10 MB) |
317
- | `--json` | Output the draft id/url as JSON |
441
+ | `--yes` | Required to send. Without it you get the overview and an error |
442
+ | `--dry-run` | Show recipients (To/Cc/Bcc), subject, files and signature count; sends nothing |
443
+ | `--all-drafts` / `--filter <query>` | Every draft in Concepten, narrowed with a Mail search; or pass UIDs |
444
+ | `--delay <seconds>` | Pause between mails of a batch (default 10, `0` for none) |
445
+ | `--max <n>` | Refuse to send more than n (never more than 100 per run) |
446
+ | `--mailbox <id-or-address>` | Mailbox with the drafts (default: your first) |
447
+ | `--json` | Output `{ sent, alreadySent, failed, notAttempted }` |
448
+
449
+ Every draft is checked before the first one goes out; if one is blocked (no
450
+ recipient, a sender you may not use, the signature twice) nothing is sent. A
451
+ failure stops the batch and lists what already went out and what did not run.
452
+ A draft is never sent twice: one that is already in Verzonden is skipped (and
453
+ its leftover draft removed), and a request without an answer is reported as
454
+ "may have been sent": check `mail status` before trying again. The server
455
+ allows 200 sends per login per hour (`MAIL_SEND_HOURLY_LIMIT`).
318
456
 
319
457
  ## List tasks
320
458
 
@@ -419,6 +557,36 @@ without billing or a Guard license. Check returned `warning` values before
419
557
  retrying. Ticket creation reports its task number if a later upload fails;
420
558
  retry with `attach task`, not a second ticket.
421
559
 
560
+ ## Quotes in Support (0.12.0)
561
+
562
+ `infaris-crm quote` creates Guard quotes as drafts in Support, priced from the
563
+ live Infaris catalogue, and downloads the PDF Support renders. Acceptance stays
564
+ in Support, where it becomes the composed license and billing in Infaris.
565
+
566
+ ```bash
567
+ infaris-crm quote catalog --json # component ids, live prices, units
568
+ infaris-crm quote create --file offerte.json --customer RELATION --organization ORG_SLUG --logo logo.png --json
569
+ infaris-crm quote update Q-2026-0042 --file offerte.json --customer RELATION --json # drafts only
570
+ infaris-crm quote pdf Q-2026-0042 --out "Offerte Q-2026-0042.pdf"
571
+ infaris-crm quote send Q-2026-0042 # after the mail draft is ready
572
+ infaris-crm quote accept Q-2026-0042 --by "Name" --via email --variant option --yes # starts billing
573
+ infaris-crm quote show Q-2026-0042 --json # status, totals, prospectComponents
574
+ infaris-crm quote list RELATION --json
575
+ infaris-crm quote decline Q-2026-0042
576
+ ```
577
+
578
+ The quote file names components (`{"component": "website", "quantity": 5}`); a
579
+ `price` on a line or a `packagePrice` below the sum is reported back as a
580
+ deviation. `"optional": true` lines form the variant named by `optionLabel`.
581
+ The same file for the same relation derives the same idempotency key, so a
582
+ repeated `create` returns the existing quote; change a draft with `update`.
583
+ `quote accept` records the customer's acceptance exactly like the quote page
584
+ (same validation; repeating it changes nothing) and starts the license and
585
+ billing in Infaris, so it refuses without `--yes`. A refusal (Infaris, Stripe)
586
+ leaves the quote SENT with the reason in the error.
587
+ `prospectComponents` in the answer is the value for
588
+ `infaris-guard prospect --components`, so trial and quote hold the same.
589
+
422
590
  Use `infaris-crm login`, or `login link` / `login code <value>` for remote sessions.
423
591
  The logout affects both CLI tools. `INFARIS_CALENDAR_CONFIG_DIR` can select an
424
592
  isolated login directory for a separate profile or automation session. Override the CRM server with `INFARIS_CRM_URL`;
package/dist/api.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { extname } from "node:path";
2
+ import { basename, extname } from "node:path";
3
3
  import { getValidCredentials } from "./auth.js";
4
4
  export const PRODUCTS = [
5
5
  "general",
@@ -129,8 +129,16 @@ const EXTENSION_MIME_TYPES = {
129
129
  ".webp": "image/webp",
130
130
  ".svg": "image/svg+xml",
131
131
  ".pdf": "application/pdf",
132
+ ".txt": "text/plain",
133
+ ".csv": "text/csv",
134
+ ".html": "text/html",
135
+ ".ics": "text/calendar",
136
+ ".zip": "application/zip",
137
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
138
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
139
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
132
140
  };
133
- function guessMimeType(filePath) {
141
+ export function guessMimeType(filePath) {
134
142
  return (EXTENSION_MIME_TYPES[extname(filePath).toLowerCase()] ??
135
143
  "application/octet-stream");
136
144
  }
@@ -299,36 +307,26 @@ export async function deleteHours(input) {
299
307
  const data = (await res.json());
300
308
  return { deleted: Boolean(data.deleted), baseUrl };
301
309
  }
310
+ // --- Mail drafts (concepts) ---
311
+ /** Totaal aan bijlagen en inline afbeeldingen per concept (spiegelt de server). */
312
+ export const MAX_DRAFT_BYTES = 20 * 1024 * 1024;
313
+ /** Reads a local file as a draft attachment. */
314
+ export function readDraftAttachment(filePath) {
315
+ return {
316
+ filename: basename(filePath) || "bijlage",
317
+ contentBase64: readFileSync(filePath).toString("base64"),
318
+ contentType: guessMimeType(filePath),
319
+ };
320
+ }
302
321
  /**
303
- * Stages a mail draft in the user's own webmail (never sends). Returns the URL
304
- * to open in `/dashboard/mail` to review, edit and send it.
322
+ * Saves a real draft in the Drafts folder (Concepten) of one of the user's
323
+ * own mailboxes, with the default signature below the body. Never sends.
305
324
  */
306
325
  export async function createMailDraft(input) {
307
- let attachmentBase64;
308
- let attachmentFilename;
309
- let attachmentMimeType;
310
- if (input.attachmentPath) {
311
- const fileBytes = readFileSync(input.attachmentPath);
312
- if (fileBytes.byteLength > MAX_ATTACHMENT_BYTES) {
313
- throw new Error(`${input.attachmentPath} exceeds the 10 MB attachment limit`);
314
- }
315
- attachmentBase64 = fileBytes.toString("base64");
316
- attachmentFilename =
317
- input.attachmentPath.split(/[/\\]/).pop() || "attachment";
318
- attachmentMimeType = guessMimeType(input.attachmentPath);
319
- }
320
326
  const { res, baseUrl } = await authedFetch("/api/mail/drafts", {
321
327
  method: "POST",
322
328
  headers: { "content-type": "application/json" },
323
- body: JSON.stringify({
324
- to: input.to,
325
- subject: input.subject,
326
- html: input.html,
327
- fromAddress: input.fromAddress,
328
- attachmentBase64,
329
- attachmentFilename,
330
- attachmentMimeType,
331
- }),
329
+ body: JSON.stringify(input),
332
330
  });
333
331
  if (!res.ok) {
334
332
  throw new Error(await describeError(res));
@@ -336,6 +334,129 @@ export async function createMailDraft(input) {
336
334
  const data = (await res.json());
337
335
  return { ...data, baseUrl };
338
336
  }
337
+ /**
338
+ * Newest drafts in Concepten of one mailbox (id, address or alias; default the
339
+ * first), optionally narrowed with a Mail search query.
340
+ */
341
+ export async function listMailDrafts(opts = {}) {
342
+ const params = new URLSearchParams();
343
+ if (opts.mailbox)
344
+ params.set("mailbox", opts.mailbox);
345
+ if (opts.limit)
346
+ params.set("limit", String(opts.limit));
347
+ if (opts.search)
348
+ params.set("search", opts.search);
349
+ const { res } = await authedFetch(`/api/mail/drafts?${params}`, {
350
+ method: "GET",
351
+ });
352
+ if (!res.ok)
353
+ throw new Error(await describeError(res));
354
+ return (await res.json());
355
+ }
356
+ /** Deletes one draft from Concepten; never touches another folder. */
357
+ export async function deleteMailDraft(uid, mailbox) {
358
+ const params = new URLSearchParams({ uid: String(uid) });
359
+ if (mailbox)
360
+ params.set("mailbox", mailbox);
361
+ const { res } = await authedFetch(`/api/mail/drafts?${params}`, {
362
+ method: "DELETE",
363
+ });
364
+ if (!res.ok)
365
+ throw new Error(await describeError(res));
366
+ return (await res.json());
367
+ }
368
+ function mailParams(opts) {
369
+ const params = new URLSearchParams();
370
+ if (opts.mailbox)
371
+ params.set("mailbox", opts.mailbox);
372
+ if (opts.kind)
373
+ params.set("kind", opts.kind);
374
+ else if (opts.folder)
375
+ params.set("folder", opts.folder);
376
+ return params;
377
+ }
378
+ /** Your mailboxes, their sender addresses and the default signature as text. */
379
+ export async function listMailboxes() {
380
+ const { res } = await authedFetch("/api/mail/mailboxes", { method: "GET" });
381
+ if (!res.ok)
382
+ throw new Error(await describeError(res));
383
+ return (await res.json());
384
+ }
385
+ /** Recent or matching messages in one folder; reading never marks them read. */
386
+ export async function listMailMessages(opts = {}) {
387
+ const params = mailParams(opts);
388
+ if (opts.search)
389
+ params.set("search", opts.search);
390
+ if (opts.limit)
391
+ params.set("limit", String(opts.limit));
392
+ const { res } = await authedFetch(`/api/mail/messages?${params}`, {
393
+ method: "GET",
394
+ });
395
+ if (!res.ok)
396
+ throw new Error(await describeError(res));
397
+ return (await res.json());
398
+ }
399
+ /** One message as plain text, without marking it read. */
400
+ export async function readMailMessage(uid, opts = {}) {
401
+ const params = mailParams(opts);
402
+ params.set("uid", String(uid));
403
+ if (opts.preview)
404
+ params.set("preview", "1");
405
+ const { res } = await authedFetch(`/api/mail/messages?${params}`, {
406
+ method: "GET",
407
+ });
408
+ if (!res.ok)
409
+ throw new Error(await describeError(res));
410
+ return (await res.json());
411
+ }
412
+ /** No answer to a send request: the mail may or may not have gone out. */
413
+ export class SendOutcomeUnknownError extends Error {
414
+ }
415
+ /**
416
+ * Sends (`confirm`) or checks (`dryRun`) one existing draft in Concepten.
417
+ * Only a draft of a mailbox you have access to goes out, and one that is
418
+ * already sent is never sent twice. A request that gets no answer throws
419
+ * {@link SendOutcomeUnknownError}: look at `mailDraftStatus` before retrying.
420
+ */
421
+ export async function sendMailDraft(input) {
422
+ let res;
423
+ try {
424
+ ({ res } = await authedFetch("/api/mail/send", {
425
+ method: "POST",
426
+ headers: { "content-type": "application/json" },
427
+ body: JSON.stringify({
428
+ uid: input.uid,
429
+ mailbox: input.mailbox,
430
+ dryRun: input.dryRun ?? false,
431
+ confirm: input.confirm ?? false,
432
+ }),
433
+ // Grote bijlagen over SMTP duren langer dan een gewone aanroep.
434
+ signal: AbortSignal.timeout(120_000),
435
+ }));
436
+ }
437
+ catch (err) {
438
+ if (input.dryRun || !input.confirm)
439
+ throw err;
440
+ throw new SendOutcomeUnknownError(`No answer while sending draft ${input.uid} (${err instanceof Error ? err.message : String(err)}). It may have been sent: check \`infaris-calendar mail status ${input.uid}\` before trying again.`);
441
+ }
442
+ if (!res.ok)
443
+ throw new Error(await describeError(res));
444
+ return (await res.json());
445
+ }
446
+ /** Is this draft (uid) or message (Message-ID) really in Verzonden? */
447
+ export async function mailDraftStatus(ref, mailbox) {
448
+ const params = new URLSearchParams();
449
+ if (ref.uid)
450
+ params.set("uid", String(ref.uid));
451
+ if (ref.messageId)
452
+ params.set("messageId", ref.messageId);
453
+ if (mailbox)
454
+ params.set("mailbox", mailbox);
455
+ const { res } = await authedFetch(`/api/mail/send?${params}`, { method: "GET" });
456
+ if (!res.ok)
457
+ throw new Error(await describeError(res));
458
+ return (await res.json());
459
+ }
339
460
  async function describeError(res) {
340
461
  let detail = "";
341
462
  try {
package/dist/auth.js CHANGED
@@ -330,6 +330,18 @@ async function refreshAccessToken(stale) {
330
330
  return rotate(creds);
331
331
  });
332
332
  }
333
+ /** Credentials with a different refresh token than `used`, once another process saved them (max ~3 s). */
334
+ export async function awaitRotatedCredentials(used, { timeoutMs = 3_000, intervalMs = 200 } = {}) {
335
+ const deadline = Date.now() + timeoutMs;
336
+ for (;;) {
337
+ const current = loadCredentials();
338
+ if (current?.refreshToken && current.refreshToken !== used)
339
+ return current;
340
+ if (Date.now() >= deadline)
341
+ return null;
342
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
343
+ }
344
+ }
333
345
  async function rotate(creds) {
334
346
  if (!creds.refreshToken) {
335
347
  throw new Error("Your session has expired. Please run `infaris-calendar login` again.");
@@ -348,8 +360,19 @@ async function rotate(creds) {
348
360
  // error is worth retrying without a new sign-in.
349
361
  if (!/\((400|401)\)/.test(message))
350
362
  throw err;
363
+ // "Already used": a process outside our lock (an older CLI in another
364
+ // worktree shares this credentials file) rotated it a moment ago. Its new
365
+ // token lands in the file; take that instead of reporting a dead session.
366
+ if (/already been used/i.test(message)) {
367
+ const rotated = await awaitRotatedCredentials(creds.refreshToken);
368
+ if (rotated) {
369
+ return Date.now() + 30_000 < rotated.expiresAt ? rotated : rotate(rotated);
370
+ }
371
+ }
351
372
  throw new Error("Your session has expired. Please run `infaris-calendar login` again " +
352
- "(or `infaris-calendar login link` from an agent or SSH session).");
373
+ "(or `infaris-calendar login link` from an agent or SSH session). " +
374
+ "If this keeps happening, an older infaris-calendar in another worktree " +
375
+ "may share ~/.infaris/calendar and rotate the same session; update or remove it.");
353
376
  }
354
377
  const updated = toCredentials(creds.baseUrl, tokens);
355
378
  // Keep the old refresh token if the server did not send a new one.
package/dist/crm-api.js CHANGED
@@ -2,6 +2,10 @@ import { getValidCredentials } from "./auth.js";
2
2
  import { infarisEnv } from "./legacy.js";
3
3
  /** CRM shares Calendar's human PKCE login, not its service-to-service key. */
4
4
  export async function crmFetch(path, init = {}) {
5
+ return (await crmFetchRaw(path, init)).json();
6
+ }
7
+ /** As crmFetch, for a binary answer such as a quote PDF. */
8
+ export async function crmFetchRaw(path, init = {}) {
5
9
  const creds = await getValidCredentials();
6
10
  // A development Calendar login must never silently write to production CRM.
7
11
  const configured = infarisEnv("CRM_URL");
@@ -33,5 +37,5 @@ export async function crmFetch(path, init = {}) {
33
37
  const body = (await res.json().catch(() => ({})));
34
38
  throw new Error(`CRM request failed (${res.status}): ${body.error || res.statusText}${res.status === 401 ? ". Run infaris-crm login with an Infaris admin account." : ""}`);
35
39
  }
36
- return res.json();
40
+ return res;
37
41
  }
package/dist/crm-index.js CHANGED
@@ -4,12 +4,13 @@ import { Command, Option } from "commander";
4
4
  import { beginLogin, completeLogin, login, readLoginCode } from "./auth.js";
5
5
  import { clearCredentials, DEFAULT_BASE_URL } from "./config.js";
6
6
  import { crmFetch } from "./crm-api.js";
7
+ import { registerQuoteCommands } from "./crm-quote.js";
7
8
  import { createTask, addTaskAttachment, listTeamMembers, listTasks, } from "./api.js";
8
9
  import { resolveAttendeeIds } from "./selectors.js";
9
10
  const program = new Command()
10
11
  .name("infaris-crm")
11
- .version("0.9.0")
12
- .description("Customer dossiers, contact people and contact history. Shares infaris-calendar login.");
12
+ .version("0.12.1")
13
+ .description("Customer dossiers, contact people, contact history and quotes. Shares infaris-calendar login.");
13
14
  function output(value) {
14
15
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
15
16
  }
@@ -192,6 +193,7 @@ program
192
193
  }),
193
194
  }));
194
195
  });
196
+ registerQuoteCommands(program);
195
197
  program.parseAsync(process.argv).catch((error) => {
196
198
  process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
197
199
  process.exitCode = 1;