@infaris/calendar-cli 0.10.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
@@ -324,8 +324,13 @@ infaris-calendar mail messages --search "offerte"
324
324
  infaris-calendar mail read 4812
325
325
  infaris-calendar mail draft --reply 4812 --body "<p>Dank je, klopt helemaal.</p>"
326
326
 
327
- # Change a draft: save the new version and remove the old one in one go
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.
328
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
329
334
  infaris-calendar mail draft --replace 977 --to kees@example.com \
330
335
  --subject "Offerte v2" --body-file ./mail.html
331
336
 
@@ -333,8 +338,9 @@ infaris-calendar mail draft --replace 977 --to kees@example.com \
333
338
  infaris-calendar mail draft --to kees@example.com --body-file ./mail.html --dry-run
334
339
  infaris-calendar mail draft --to kees@example.com --body-file ./mail.md --preview /tmp/mail.html
335
340
 
336
- # Read the saved draft back to check it
337
- infaris-calendar mail read 978 --drafts
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
338
344
 
339
345
  # Many drafts at once (outreach): every draft is checked before any is saved
340
346
  cat > drafts.json <<'JSON'
@@ -369,6 +375,10 @@ infaris-calendar mail batch drafts.json --replace-map map.json --write-map map.j
369
375
  | `--folder <path>` | Folder of the original message (default `INBOX`) |
370
376
  | `--source-mailbox <id>` | Mailbox of the original (default: the draft mailbox) |
371
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 |
372
382
  | `--dry-run` | Print recipients, images and attachments without saving |
373
383
  | `--preview <file.html>` | Write the body with inline images to an HTML file; saves nothing |
374
384
  | `--no-inline-remote` | Keep `https://` images as links instead of embedding them |
@@ -394,7 +404,7 @@ Other `mail` commands, all read-only except `delete-draft` (removes a draft) and
394
404
  | `mail delete-draft <uid> [--mailbox]` (alias `draft-delete`) | Delete one draft, only from Concepten |
395
405
  | `mail messages [--mailbox] [--folder\|--sent] [--search] [--limit]` | List or search messages to find a UID |
396
406
  | `mail sent [--mailbox] [--search] [--limit]` | The newest messages in Verzonden |
397
- | `mail read <uid> [--mailbox] [--folder\|--drafts\|--sent]` | Show one message as text; never marks it read. With `--json` and `--drafts`/`--sent`: recipients incl. Bcc, subject, body and `signatureCount` |
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` |
398
408
  | `mail status <uid\|message-id> [--mailbox]` | Is it still a draft, really in Verzonden, or gone? |
399
409
  | `mail send [uids...] [--all-drafts [--filter q]] --yes` | Send existing drafts; see below |
400
410
 
@@ -547,6 +557,36 @@ without billing or a Guard license. Check returned `warning` values before
547
557
  retrying. Ticket creation reports its task number if a later upload fails;
548
558
  retry with `attach task`, not a second ticket.
549
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
+
550
590
  Use `infaris-crm login`, or `login link` / `login code <value>` for remote sessions.
551
591
  The logout affects both CLI tools. `INFARIS_CALENDAR_CONFIG_DIR` can select an
552
592
  isolated login directory for a separate profile or automation session. Override the CRM server with `INFARIS_CRM_URL`;
package/dist/api.js CHANGED
@@ -400,6 +400,8 @@ export async function listMailMessages(opts = {}) {
400
400
  export async function readMailMessage(uid, opts = {}) {
401
401
  const params = mailParams(opts);
402
402
  params.set("uid", String(uid));
403
+ if (opts.preview)
404
+ params.set("preview", "1");
403
405
  const { res } = await authedFetch(`/api/mail/messages?${params}`, {
404
406
  method: "GET",
405
407
  });
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.10.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;
@@ -0,0 +1,174 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { Option } from "commander";
5
+ import { crmFetch, crmFetchRaw } from "./crm-api.js";
6
+ /**
7
+ * `infaris-crm quote`: Guard quotes as DRAFTs in Support, priced from the
8
+ * live Infaris catalogue, with the PDF Support renders. Support owns the
9
+ * numbering, totals and acceptance; this only sends the draft.
10
+ */
11
+ const MAX_LOGO_BYTES = 256 * 1024;
12
+ /** PNG or JPEG file as a data URI; Support renders it on white in the PDF header. */
13
+ export function logoDataUri(path) {
14
+ const bytes = readFileSync(path);
15
+ if (bytes.length > MAX_LOGO_BYTES)
16
+ throw new Error(`Logo ${path} is larger than 256 kB; crop or compress it`);
17
+ const png = bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
18
+ const jpeg = bytes[0] === 0xff && bytes[1] === 0xd8;
19
+ if (!png && !jpeg)
20
+ throw new Error(`Logo ${path} must be a PNG or JPEG (convert an SVG first)`);
21
+ return `data:image/${png ? "png" : "jpeg"};base64,${bytes.toString("base64")}`;
22
+ }
23
+ /**
24
+ * The quote JSON with its logo inlined and an idempotency key: the same file
25
+ * for the same relation always gives the same key, so a repeated command
26
+ * returns the quote it already made instead of a second one.
27
+ */
28
+ export function readQuoteFile(path, overrides = {}) {
29
+ const text = readFileSync(path, "utf8");
30
+ const quote = JSON.parse(text);
31
+ if (!quote || typeof quote !== "object" || Array.isArray(quote))
32
+ throw new Error(`${path} must hold a JSON object`);
33
+ if (overrides.relation)
34
+ quote.relation = overrides.relation;
35
+ if (overrides.organization)
36
+ quote.organization = overrides.organization;
37
+ const relation = typeof quote.relation === "string" ? quote.relation.trim() : "";
38
+ const organization = typeof quote.organization === "string" ? quote.organization.trim() : "";
39
+ // With only the organization, Support uses the relation it is linked to (by its trial).
40
+ if (!relation && !organization)
41
+ throw new Error("Give the relation (--customer) or the organization (--organization)");
42
+ const logo = overrides.logo ?? (typeof quote.logo === "string" && !quote.logo.startsWith("data:") ? resolve(dirname(path), quote.logo) : undefined);
43
+ if (logo)
44
+ quote.logo = logoDataUri(logo);
45
+ quote.key =
46
+ overrides.key ??
47
+ (typeof quote.key === "string" && quote.key
48
+ ? quote.key
49
+ : `cli:${createHash("sha256").update(`${relation || `org:${organization}`}\n${text}`).digest("hex").slice(0, 40)}`);
50
+ return quote;
51
+ }
52
+ const json = (body) => ({
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify(body),
56
+ });
57
+ function output(value) {
58
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
59
+ }
60
+ const enc = encodeURIComponent;
61
+ /** A Support without the quote API answers 404 on its collection routes. */
62
+ async function quoteApi(call) {
63
+ try {
64
+ return await call();
65
+ }
66
+ catch (error) {
67
+ if (error instanceof Error && /\(404\): Not Found$|\(404\): $/.test(error.message))
68
+ throw new Error("Support has no quote API yet (deploy Support with /api/crm/quotes first)");
69
+ throw error;
70
+ }
71
+ }
72
+ export function registerQuoteCommands(program) {
73
+ const quote = program
74
+ .command("quote")
75
+ .description("Guard quotes in Support: draft from the catalogue, PDF, send, decline");
76
+ quote
77
+ .command("catalog")
78
+ .description("Quotable Infaris components with live prices (ids for the quote file)")
79
+ .option("--json", "Machine-readable output (default)")
80
+ .action(async () => output(await quoteApi(() => crmFetch("/quotes/catalog"))));
81
+ quote
82
+ .command("create")
83
+ .description("Create a DRAFT quote from a JSON file; repeating returns the same quote")
84
+ .requiredOption("--file <path>", "Quote JSON (see the guard-quote skill)")
85
+ .option("--customer <relation>", "Relation number or id; leave out to use the relation the organization is linked to")
86
+ .option("--organization <slug>", "Organization the license belongs to (overrides the file)")
87
+ .option("--logo <path>", "Customer logo, PNG or JPEG on white")
88
+ .option("--key <key>", "Idempotency key (default: derived from relation and file)")
89
+ .option("--json", "Machine-readable output (default)")
90
+ .action(async (opts) => {
91
+ const body = readQuoteFile(opts.file, {
92
+ relation: opts.customer,
93
+ organization: opts.organization,
94
+ key: opts.key,
95
+ logo: opts.logo,
96
+ });
97
+ output(await quoteApi(() => crmFetch("/quotes", json(body))));
98
+ });
99
+ quote
100
+ .command("update <number>")
101
+ .description("Replace the lines and texts of a DRAFT quote")
102
+ .requiredOption("--file <path>", "Quote JSON")
103
+ .option("--customer <relation>")
104
+ .option("--organization <slug>")
105
+ .option("--logo <path>")
106
+ .option("--json", "Machine-readable output (default)")
107
+ .action(async (number, opts) => {
108
+ const body = readQuoteFile(opts.file, {
109
+ relation: opts.customer,
110
+ organization: opts.organization,
111
+ logo: opts.logo,
112
+ });
113
+ output(await crmFetch(`/quotes/${enc(number)}`, { ...json(body), method: "PUT" }));
114
+ });
115
+ quote
116
+ .command("show <number>")
117
+ .description("Status, totals, lines and the --components value for the trial")
118
+ .option("--json", "Machine-readable output (default)")
119
+ .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}`)));
120
+ quote
121
+ .command("list <customer>")
122
+ .description("Quotes of a relation, newest first")
123
+ .option("--json", "Machine-readable output (default)")
124
+ .action(async (customer) => output(await crmFetch(`/quotes?${new URLSearchParams({ relation: customer })}`)));
125
+ quote
126
+ .command("pdf <number>")
127
+ .description("Download the PDF Support renders for the quote")
128
+ .requiredOption("--out <path>", "Where to write the PDF")
129
+ .action(async (number, opts) => {
130
+ const res = await crmFetchRaw(`/quotes/${enc(number)}/pdf`);
131
+ if (!res.headers.get("content-type")?.includes("application/pdf"))
132
+ throw new Error("Support did not return a PDF");
133
+ const bytes = Buffer.from(await res.arrayBuffer());
134
+ writeFileSync(opts.out, bytes);
135
+ output({ pdf: resolve(opts.out), bytes: bytes.length });
136
+ });
137
+ quote
138
+ .command("send <number>")
139
+ .description("Mark the quote SENT once the mail draft with the PDF is ready")
140
+ .option("--json", "Machine-readable output (default)")
141
+ .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}/send`, json({}))));
142
+ quote
143
+ .command("accept <number>")
144
+ .description("Record the customer's acceptance, as on the quote page; starts the license and billing in Infaris")
145
+ .requiredOption("--by <name>", "Who agreed on behalf of the customer")
146
+ .addOption(new Option("--via <channel>", "How the customer agreed")
147
+ .choices(["email", "signed_pdf", "verbal"])
148
+ .makeOptionMandatory())
149
+ .addOption(new Option("--variant <variant>", "base (Guard) or option (e.g. Guard met support); required with an option").choices([
150
+ "base",
151
+ "option",
152
+ ]))
153
+ .option("--document-url <url>", "https link to the signed copy or the acceptance mail")
154
+ .option("--dpa-signed", "The data processing agreement is signed")
155
+ .option("--yes", "Confirm: this starts real billing")
156
+ .option("--json", "Machine-readable output (default)")
157
+ .action(async (number, opts) => {
158
+ if (!opts.yes)
159
+ throw new Error("Accepting starts the license and billing in Infaris. Only with the customer's confirmed acceptance, then repeat with --yes.");
160
+ output(await crmFetch(`/quotes/${enc(number)}/accept`, json({
161
+ by: opts.by,
162
+ via: opts.via,
163
+ variant: opts.variant,
164
+ documentUrl: opts.documentUrl,
165
+ dpaSigned: Boolean(opts.dpaSigned),
166
+ confirm: true,
167
+ })));
168
+ });
169
+ quote
170
+ .command("decline <number>")
171
+ .description("Record that the customer declined")
172
+ .option("--json", "Machine-readable output (default)")
173
+ .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}/decline`, json({}))));
174
+ }
package/dist/index.js CHANGED
@@ -25,7 +25,7 @@ const program = new Command();
25
25
  program
26
26
  .name("infaris-calendar")
27
27
  .description("Calendar CLI: agenda, tasks, mail drafts, and the urenstaat (hours).")
28
- .version("0.10.0");
28
+ .version("0.12.1");
29
29
  const loginCmd = program
30
30
  .command("login")
31
31
  .description("Sign in with Infaris in your browser and store a token")
@@ -866,6 +866,23 @@ function formatBytes(bytes) {
866
866
  ? `${(bytes / 1024 / 1024).toFixed(1)} MB`
867
867
  : `${Math.max(1, Math.round(bytes / 1024))} kB`;
868
868
  }
869
+ function escapeHtml(value) {
870
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
871
+ }
872
+ /** "Files:" for real attachments, "Inline:" for images in the text (older servers: names only). */
873
+ function describeAttachments(list) {
874
+ const files = list.map((a) => typeof a === "string" ? { filename: a, inline: false, label: a } : {
875
+ filename: a.filename,
876
+ inline: a.inline,
877
+ label: `${a.filename} (${a.contentType}, ${formatBytes(a.size)})`,
878
+ });
879
+ const attached = files.filter((f) => !f.inline).map((f) => f.label);
880
+ const inline = files.filter((f) => f.inline).map((f) => f.label);
881
+ return [
882
+ attached.length ? `Files: ${attached.join(", ")}` : "",
883
+ inline.length ? `Inline: ${inline.join(", ")}` : "",
884
+ ];
885
+ }
869
886
  mail
870
887
  .command("draft")
871
888
  .description([
@@ -892,6 +909,10 @@ mail
892
909
  .option("--source-mailbox <id>", "Mailbox id or address of the original (default: the draft mailbox)")
893
910
  .option("--no-forward-attachments", "Forward without the original attachments")
894
911
  .option("--replace <uid>", "Replace this existing draft in Concepten", parseUid)
912
+ .option("--edit <uid>", "Change this draft in place: only what you pass changes. New --body/--body-file replaces the text above the signature; recipients, subject, thread, signature, quote and attachments stay unless given; --attach adds files", parseUid)
913
+ .option("--mailbox <id>", "Mailbox (id, address or alias) of the draft to --edit")
914
+ .option("--drop-attachments", "With --edit: remove the draft's existing attachments")
915
+ .option("--note <text>", "Private note for whoever reviews the draft (what it is based on, what to check); shown in Calendar, never sent along")
895
916
  .option("--dry-run", "Check recipients, images and attachments without saving")
896
917
  .option("--preview <file.html>", "Write the body (images inline) to an HTML file to look at; implies --dry-run")
897
918
  .option("--no-inline-remote", "Keep https:// images as links instead of embedding them")
@@ -920,6 +941,10 @@ mail
920
941
  replace: opts.replace,
921
942
  inlineRemote: opts.inlineRemote,
922
943
  optimizeImages: opts.optimizeImages,
944
+ edit: opts.edit,
945
+ mailbox: opts.mailbox,
946
+ dropAttachments: opts.dropAttachments,
947
+ note: opts.note,
923
948
  }, process.cwd());
924
949
  for (const message of built.warnings)
925
950
  warn(message);
@@ -943,7 +968,7 @@ mail
943
968
  }
944
969
  });
945
970
  function printDraft(draft) {
946
- ok(`Draft ${draft.replaced ? `replaced (was ${draft.replaced}) ` : ""}saved in ${draft.folder} of ${draft.mailbox} (from ${draft.from})`);
971
+ ok(`Draft ${draft.edited ? `edited (was ${draft.edited}) ` : draft.replaced ? `replaced (was ${draft.replaced}) ` : ""}saved in ${draft.folder} of ${draft.mailbox} (from ${draft.from})`);
947
972
  const lines = [
948
973
  `To: ${draft.to.join(", ") || "-"}`,
949
974
  draft.cc.length ? `Cc: ${draft.cc.join(", ")}` : "",
@@ -955,7 +980,8 @@ function printDraft(draft) {
955
980
  draft.attachments.length
956
981
  ? `Files: ${draft.attachments.map((a) => `${a.filename} (${formatBytes(a.size)})`).join(", ")}`
957
982
  : "",
958
- draft.signature ? "" : "Signature: none",
983
+ draft.signature || draft.edited ? "" : "Signature: none",
984
+ draft.note ? `Note: ${draft.note}` : "",
959
985
  draft.url,
960
986
  ].filter(Boolean);
961
987
  process.stdout.write(lines.map((line) => ` ${line}\n`).join(""));
@@ -1101,7 +1127,7 @@ mail
1101
1127
  }
1102
1128
  process.stdout.write(`${list.folder} of ${list.mailbox}: ${list.total} draft(s)\n`);
1103
1129
  for (const d of list.drafts) {
1104
- process.stdout.write(` ${String(d.uid).padStart(6)} ${d.date?.slice(0, 16).replace("T", " ") ?? ""} ${d.to || "-"} ${d.subject}${d.hasAttachments ? " [bijlage]" : ""}\n`);
1130
+ process.stdout.write(` ${String(d.uid).padStart(6)} ${d.date?.slice(0, 16).replace("T", " ") ?? ""} ${d.to || "-"} ${d.subject}${d.hasAttachments ? " [bijlage]" : ""}${d.agentDraft ? " [agent]" : ""}\n`);
1105
1131
  }
1106
1132
  }
1107
1133
  catch (err) {
@@ -1328,6 +1354,7 @@ mail
1328
1354
  .option("--folder <path>", "Folder", "INBOX")
1329
1355
  .option("--drafts", "Read from Concepten (e.g. the uid `mail draft` returned)")
1330
1356
  .option("--sent", "Read from Verzonden")
1357
+ .option("--preview <file.html>", "Also write the message as the recipient sees it (signature and inline images included) to an HTML file, to render and look at")
1331
1358
  .option("--json", "Output as JSON")
1332
1359
  .action(async (uid, opts) => {
1333
1360
  try {
@@ -1335,9 +1362,18 @@ mail
1335
1362
  mailbox: opts.mailbox,
1336
1363
  folder: opts.folder,
1337
1364
  kind: opts.drafts ? "drafts" : opts.sent ? "sent" : undefined,
1365
+ preview: Boolean(opts.preview),
1338
1366
  });
1367
+ const { previewHtml, ...rest } = message;
1368
+ if (opts.preview) {
1369
+ if (!previewHtml) {
1370
+ throw new Error("This Calendar server does not support --preview yet");
1371
+ }
1372
+ writeFileSync(opts.preview, `<!doctype html><meta charset="utf-8"><title>${escapeHtml(rest.subject)}</title>${previewHtml}`);
1373
+ process.stderr.write(`Preview: ${resolvePath(opts.preview)}\n`);
1374
+ }
1339
1375
  if (opts.json) {
1340
- process.stdout.write(`${JSON.stringify({ ...where, message }, null, 2)}\n`);
1376
+ process.stdout.write(`${JSON.stringify({ ...where, message: rest }, null, 2)}\n`);
1341
1377
  return;
1342
1378
  }
1343
1379
  const head = [
@@ -1350,9 +1386,9 @@ mail
1350
1386
  message.signatureCount !== undefined
1351
1387
  ? `Signatures: ${message.signatureCount}`
1352
1388
  : "",
1353
- message.attachments.length
1354
- ? `Files: ${message.attachments.join(", ")}`
1355
- : "",
1389
+ message.agentDraft ? "Staged: by an agent" : "",
1390
+ message.note ? `Note: ${message.note}` : "",
1391
+ ...describeAttachments(message.attachments),
1356
1392
  ].filter(Boolean);
1357
1393
  process.stdout.write(`${head.join("\n")}\n\n${message.body}\n`);
1358
1394
  }
@@ -213,6 +213,12 @@ export async function buildDraft(spec, baseDir, deps = {}) {
213
213
  if ([reply, replyAll, forward].filter(Boolean).length > 1) {
214
214
  throw new Error("Use only one of reply, replyAll or forward");
215
215
  }
216
+ const edit = positiveUid(spec.edit, "edit");
217
+ if (edit && (reply || replyAll || forward || spec.replace !== undefined)) {
218
+ throw new Error("edit does not combine with reply, replyAll, forward or replace");
219
+ }
220
+ // Bij edit blijft de tekst staan tenzij je nieuwe tekst of plaatjes meegeeft.
221
+ const newText = spec.body !== undefined || spec.bodyFile !== undefined || (spec.images?.length ?? 0) > 0;
216
222
  let source = spec.body ?? "";
217
223
  let bodyDir = baseDir;
218
224
  if (spec.bodyFile === "-") {
@@ -270,7 +276,7 @@ export async function buildDraft(spec, baseDir, deps = {}) {
270
276
  cc: addressList(spec.cc),
271
277
  bcc: addressList(spec.bcc),
272
278
  subject: spec.subject,
273
- html,
279
+ html: edit && !newText ? undefined : html,
274
280
  fromAddress: spec.from,
275
281
  signature: spec.signature ?? true,
276
282
  optimizeImages: spec.optimizeImages ?? true,
@@ -282,8 +288,12 @@ export async function buildDraft(spec, baseDir, deps = {}) {
282
288
  ? { ...ref, uid: forward, attachments: spec.forwardAttachments ?? true }
283
289
  : undefined,
284
290
  replaceUid: positiveUid(spec.replace, "replace"),
291
+ editUid: edit,
292
+ mailbox: spec.mailbox,
293
+ dropAttachments: spec.dropAttachments || undefined,
294
+ note: spec.note,
285
295
  };
286
- if (!input.to?.length && !input.replyTo) {
296
+ if (!input.to?.length && !input.replyTo && !edit) {
287
297
  warnings.push("No recipient: the draft is saved without To");
288
298
  }
289
299
  return { input, html, images, totalBytes, warnings };
package/dist/voice.js ADDED
@@ -0,0 +1,321 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { createTask } from "./api.js";
7
+ import { loadCredentials } from "./config.js";
8
+ const execFileAsync = promisify(execFile);
9
+ const WAKE_WORDS = [
10
+ "oké takie",
11
+ "oke takie",
12
+ "oké taki",
13
+ "oke taki",
14
+ "oké takkie",
15
+ "oke takkie",
16
+ "hey takie",
17
+ "hé takie",
18
+ "hee takie",
19
+ "hei takie",
20
+ "hey taki",
21
+ "hei taki",
22
+ "hey takkie",
23
+ "hei takkie",
24
+ "hey tanki",
25
+ "hei tanki",
26
+ "hey ta kie",
27
+ ];
28
+ export function containsWakeWord(text) {
29
+ const normalized = text
30
+ .toLocaleLowerCase("nl-NL")
31
+ .replace(/[,.!?]+/g, " ")
32
+ .replace(/\s+/g, " ");
33
+ if (WAKE_WORDS.some((word) => normalized.includes(word)))
34
+ return true;
35
+ const words = normalized.trim().split(" ");
36
+ for (let index = 0; index + 1 < words.length; index++) {
37
+ const greeting = words[index];
38
+ const name = words[index + 1];
39
+ const greetingMatches = ["oke", "oké", "hey", "hei", "hee", "hé"].some((candidate) => editDistance(greeting, candidate) <= 1);
40
+ if (greetingMatches && editDistance(name, "takie") <= 2)
41
+ return true;
42
+ }
43
+ return false;
44
+ }
45
+ function editDistance(left, right) {
46
+ const row = Array.from({ length: right.length + 1 }, (_, index) => index);
47
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
48
+ let diagonal = row[0];
49
+ row[0] = leftIndex;
50
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
51
+ const above = row[rightIndex];
52
+ row[rightIndex] = Math.min(row[rightIndex] + 1, row[rightIndex - 1] + 1, diagonal + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1));
53
+ diagonal = above;
54
+ }
55
+ }
56
+ return row[right.length];
57
+ }
58
+ export function commandAfterWakeWord(text) {
59
+ const lower = text.toLocaleLowerCase("nl-NL");
60
+ const match = WAKE_WORDS.map((word) => ({ word, index: lower.indexOf(word) }))
61
+ .filter(({ index }) => index >= 0)
62
+ .sort((a, b) => a.index - b.index)[0];
63
+ return match ? text.slice(match.index + match.word.length).trim().replace(/^[:,.-]\s*/, "") : "";
64
+ }
65
+ function fallbackIntent(command) {
66
+ const title = command
67
+ .replace(/^(maak|voeg|zet)\s+(een\s+)?(nieuwe\s+)?taak\s+(aan\s+)?(om|voor|met)?\s*/i, "")
68
+ .replace(/^dat\s+/i, "")
69
+ .trim();
70
+ if (!title)
71
+ throw new Error("Ik hoorde nog geen taakomschrijving.");
72
+ return {
73
+ title: title[0].toLocaleUpperCase("nl-NL") + title.slice(1),
74
+ product: "general",
75
+ priority: "medium",
76
+ types: ["general"],
77
+ response: `Ik maak de taak ${title} aan.`,
78
+ };
79
+ }
80
+ async function interpret(command, noAi) {
81
+ const apiKey = process.env.OPENAI_API_KEY;
82
+ if (!apiKey || noAi)
83
+ return fallbackIntent(command);
84
+ const response = await fetch("https://api.openai.com/v1/responses", {
85
+ method: "POST",
86
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
87
+ body: JSON.stringify({
88
+ model: process.env.PULSECALENDAR_AI_MODEL || "gpt-5-mini",
89
+ instructions: `Je bent Takie, de Nederlandstalige spraakassistent van PulseCalendar. Zet de opdracht om in precies één taak. Maak een korte imperatieve titel. Product is een van general, pulseguard, pulsefiles, pulseqr, pulsecalendar, pulsesupport, pulsemail, ipulse. Priority is high, medium of low. Geef een korte natuurlijke Nederlandse bevestiging in response. Verzin geen details.`,
90
+ input: command,
91
+ text: {
92
+ format: {
93
+ type: "json_schema",
94
+ name: "calendar_task",
95
+ strict: true,
96
+ schema: {
97
+ type: "object",
98
+ additionalProperties: false,
99
+ required: ["title", "description", "product", "priority", "response"],
100
+ properties: {
101
+ title: { type: "string" },
102
+ description: { type: "string" },
103
+ product: { type: "string", enum: ["general", "pulseguard", "pulsefiles", "pulseqr", "pulsecalendar", "pulsesupport", "pulsemail", "ipulse"] },
104
+ priority: { type: "string", enum: ["high", "medium", "low"] },
105
+ response: { type: "string" },
106
+ },
107
+ },
108
+ },
109
+ },
110
+ }),
111
+ });
112
+ if (!response.ok)
113
+ throw new Error(`AI-agent gaf ${response.status}: ${await response.text()}`);
114
+ const data = (await response.json());
115
+ if (!data.output_text)
116
+ throw new Error("AI-agent gaf geen taak terug.");
117
+ const parsed = JSON.parse(data.output_text);
118
+ return { ...parsed, types: ["general"] };
119
+ }
120
+ async function recordWav(path, seconds) {
121
+ const source = process.env.PULSECALENDAR_AUDIO_SOURCE || "RDPSource";
122
+ await new Promise((resolve, reject) => {
123
+ const child = spawn("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-re", "-f", "pulse", "-i", source, "-t", String(seconds), "-ac", "1", "-ar", "16000", path], { stdio: "inherit" });
124
+ child.once("error", reject);
125
+ child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`Opnemen stopte met code ${code}`)));
126
+ });
127
+ }
128
+ async function hasAudibleSignal(path) {
129
+ const wav = await readFile(path);
130
+ let peak = 0;
131
+ // ffmpeg writes 16-bit mono PCM; skip the WAV header and inspect samples.
132
+ for (let offset = 44; offset + 1 < wav.length; offset += 2) {
133
+ peak = Math.max(peak, Math.abs(wav.readInt16LE(offset)));
134
+ }
135
+ return peak >= Number(process.env.PULSECALENDAR_SILENCE_PEAK || "500");
136
+ }
137
+ async function buildOverlappingWakeAudio(currentPath, previousPath, analysisPath, hasPrevious) {
138
+ if (!hasPrevious) {
139
+ await copyFile(currentPath, analysisPath);
140
+ return;
141
+ }
142
+ await new Promise((resolve, reject) => {
143
+ const child = spawn("ffmpeg", [
144
+ "-hide_banner", "-loglevel", "error", "-y",
145
+ "-sseof", "-1", "-i", previousPath,
146
+ "-i", currentPath,
147
+ "-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1[out]",
148
+ "-map", "[out]", analysisPath,
149
+ ], { stdio: "inherit" });
150
+ child.once("error", reject);
151
+ child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`Audio-overlap stopte met code ${code}`)));
152
+ });
153
+ }
154
+ async function commandExists(command) {
155
+ try {
156
+ await execFileAsync("which", [command]);
157
+ return true;
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ }
163
+ async function transcribeLocal(audioPath, dir) {
164
+ const bin = process.env.PULSECALENDAR_WHISPER_BIN || "whisper";
165
+ if (!(await commandExists(bin)))
166
+ return null;
167
+ await execFileAsync(bin, [audioPath, "--model", process.env.PULSECALENDAR_WHISPER_MODEL || "base", "--language", "nl", "--output_format", "txt", "--output_dir", dir]);
168
+ return (await readFile(join(dir, "audio.txt"), "utf8")).trim();
169
+ }
170
+ async function transcribeOpenAi(audioPath) {
171
+ const apiKey = process.env.OPENAI_API_KEY;
172
+ if (!apiKey)
173
+ throw new Error("Geen lokale `whisper` gevonden en OPENAI_API_KEY ontbreekt.");
174
+ const bytes = await readFile(audioPath);
175
+ const form = new FormData();
176
+ form.set("model", process.env.PULSECALENDAR_TRANSCRIBE_MODEL || "whisper-1");
177
+ form.set("language", "nl");
178
+ form.set("file", new Blob([bytes], { type: "audio/wav" }), "audio.wav");
179
+ const response = await fetch("https://api.openai.com/v1/audio/transcriptions", { method: "POST", headers: { authorization: `Bearer ${apiKey}` }, body: form });
180
+ if (!response.ok)
181
+ throw new Error(`Whisper gaf ${response.status}: ${await response.text()}`);
182
+ return (await response.json()).text.trim();
183
+ }
184
+ async function transcribeGroq(audioPath) {
185
+ const apiKey = process.env.GROQ_API_KEY;
186
+ if (!apiKey)
187
+ return null;
188
+ const bytes = await readFile(audioPath);
189
+ const form = new FormData();
190
+ form.set("model", process.env.GROQ_TRANSCRIBE_MODEL || "whisper-large-v3-turbo");
191
+ form.set("language", "nl");
192
+ form.set("temperature", "0");
193
+ form.set("prompt", "Oké Takie. Hey Takie.");
194
+ form.set("file", new Blob([bytes], { type: "audio/wav" }), "audio.wav");
195
+ const response = await fetch("https://api.groq.com/openai/v1/audio/transcriptions", { method: "POST", headers: { authorization: `Bearer ${apiKey}` }, body: form });
196
+ if (!response.ok)
197
+ throw new Error(`Calendar Whisper gaf ${response.status}: ${await response.text()}`);
198
+ return (await response.json()).text.trim();
199
+ }
200
+ async function createTaskReliably(input) {
201
+ try {
202
+ return await createTask(input);
203
+ }
204
+ catch (error) {
205
+ const inboundKey = process.env.PULSECALENDAR_INBOUND_API_KEY;
206
+ const message = error instanceof Error ? error.message : String(error);
207
+ if (!inboundKey || !/unauthorized/i.test(message))
208
+ throw error;
209
+ const baseUrl = loadCredentials()?.baseUrl ||
210
+ process.env.PULSECALENDAR_URL?.replace(/\/$/, "") ||
211
+ "https://calendar.infaris.com";
212
+ const response = await fetch(`${baseUrl}/api/internal/work/tasks`, {
213
+ method: "POST",
214
+ headers: {
215
+ authorization: `Bearer ${inboundKey}`,
216
+ "content-type": "application/json",
217
+ },
218
+ body: JSON.stringify({ ...input, source: "takie-voice" }),
219
+ });
220
+ if (!response.ok) {
221
+ throw new Error(`Calendar-taak kon niet worden aangemaakt (${response.status}).`);
222
+ }
223
+ const data = (await response.json());
224
+ return { task: data.task, baseUrl };
225
+ }
226
+ }
227
+ async function transcribe(audioPath, dir) {
228
+ return ((await transcribeLocal(audioPath, dir)) ??
229
+ (await transcribeGroq(audioPath)) ??
230
+ transcribeOpenAi(audioPath));
231
+ }
232
+ async function speak(text) {
233
+ if (process.env.PULSECALENDAR_SILENT === "1")
234
+ return;
235
+ const encoded = Buffer.from(text, "utf16le").toString("base64");
236
+ const outputMatch = process.env.PULSECALENDAR_AUDIO_OUTPUT || "Realtek(R) Audio";
237
+ const outputEncoded = Buffer.from(outputMatch, "utf16le").toString("base64");
238
+ const script = `$t=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('${encoded}')); $m=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('${outputEncoded}')); $s=New-Object -ComObject SAPI.SpVoice; $o=$s.GetAudioOutputs() | Where-Object { $_.GetDescription() -like ('*'+$m+'*') } | Select-Object -First 1; if($o){$s.AudioOutput=$o}; [void]$s.Speak($t)`;
239
+ await execFileAsync("powershell.exe", ["-NoProfile", "-Command", script]);
240
+ }
241
+ async function waitForEnter() {
242
+ process.stdout.write("Druk op Enter en spreek daarna je taak in…\n");
243
+ process.stdin.resume();
244
+ await new Promise((resolve) => process.stdin.once("data", () => resolve()));
245
+ }
246
+ export async function runVoiceAssistant(options) {
247
+ const dir = await mkdtemp(join(tmpdir(), "takie-"));
248
+ let hasPreviousWakeAudio = false;
249
+ try {
250
+ process.stdout.write("Takie staat klaar. Zeg ‘Oké Takie’ of gebruik --push-to-talk.\n");
251
+ while (true) {
252
+ try {
253
+ let command = "";
254
+ if (options.pushToTalk) {
255
+ await waitForEnter();
256
+ }
257
+ else {
258
+ const wakeAudio = join(dir, "wake-current.wav");
259
+ const previousWakeAudio = join(dir, "wake-previous.wav");
260
+ const analysisAudio = join(dir, "audio.wav");
261
+ await recordWav(wakeAudio, Number(process.env.PULSECALENDAR_WAKE_SECONDS || "4"));
262
+ await buildOverlappingWakeAudio(wakeAudio, previousWakeAudio, analysisAudio, hasPreviousWakeAudio);
263
+ await copyFile(wakeAudio, previousWakeAudio);
264
+ hasPreviousWakeAudio = true;
265
+ if (!(await hasAudibleSignal(analysisAudio))) {
266
+ if (process.env.PULSECALENDAR_VOICE_DEBUG === "1") {
267
+ process.stdout.write("Microfoon: (stilte)\n");
268
+ }
269
+ continue;
270
+ }
271
+ const heard = await transcribe(analysisAudio, dir);
272
+ if (process.env.PULSECALENDAR_VOICE_DEBUG === "1") {
273
+ process.stdout.write(`Microfoon/Whisper: ${heard || "(niets gehoord)"}\n`);
274
+ }
275
+ if (!containsWakeWord(heard))
276
+ continue;
277
+ process.stdout.write(`Gehoord: ${heard}\n`);
278
+ // Wake fragments are deliberately never treated as commands. Whisper
279
+ // can append words from its spelling hint; always record a clean turn.
280
+ command = "";
281
+ await speak("Ja?");
282
+ await new Promise((resolve) => setTimeout(resolve, 400));
283
+ }
284
+ if (!command) {
285
+ const commandAudio = join(dir, "audio.wav");
286
+ await recordWav(commandAudio, Number(process.env.PULSECALENDAR_COMMAND_SECONDS || "7"));
287
+ if (!(await hasAudibleSignal(commandAudio))) {
288
+ throw new Error("De microfoonopname is stil; controleer microfoondoorgifte naar WSL.");
289
+ }
290
+ command = await transcribe(commandAudio, dir);
291
+ }
292
+ process.stdout.write(`Opdracht: ${command}\n`);
293
+ const intent = await interpret(command, Boolean(options.noAi));
294
+ if (options.dryRun) {
295
+ process.stdout.write(`${JSON.stringify(intent, null, 2)}\n`);
296
+ await speak(`Test. ${intent.response}`);
297
+ }
298
+ else {
299
+ const { response: spokenResponse, ...taskInput } = intent;
300
+ const { task, baseUrl } = await createTaskReliably(taskInput);
301
+ const confirmation = `${spokenResponse} Taak nummer ${task.taskKey}.`;
302
+ process.stdout.write(`Aangemaakt: ${baseUrl}/t/${task.taskKey}\n`);
303
+ await speak(confirmation);
304
+ }
305
+ if (options.once)
306
+ return;
307
+ }
308
+ catch (error) {
309
+ const message = error instanceof Error ? error.message : String(error);
310
+ process.stderr.write(`Takie: ${message}\n`);
311
+ await speak("Dat ging niet goed. Probeer het nog een keer.").catch(() => undefined);
312
+ if (options.once)
313
+ throw error;
314
+ }
315
+ }
316
+ }
317
+ finally {
318
+ await writeFile(join(dir, ".done"), "").catch(() => undefined);
319
+ await rm(dir, { recursive: true, force: true });
320
+ }
321
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infaris/calendar-cli",
3
- "version": "0.10.0",
3
+ "version": "0.12.1",
4
4
  "description": "Command line interface for Calendar by Infaris: log in once on your device, read your agenda, manage work tasks, and fill the urenstaat from tasks, commits and PRs.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",