@infaris/calendar-cli 0.12.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -557,6 +557,33 @@ without billing or a Guard license. Check returned `warning` values before
557
557
  retrying. Ticket creation reports its task number if a later upload fails;
558
558
  retry with `attach task`, not a second ticket.
559
559
 
560
+ ## Keeping the CRM tidy (0.13.0)
561
+
562
+ ```bash
563
+ infaris-crm list --email treffendenco.nl --include-archived --kind CLIENT --status PROSPECT
564
+ infaris-crm create --name "Vimexx" --kind SUPPLIER --dry-run # reports similar customers, writes nothing
565
+ infaris-crm update RELATION --name "New name" --legal-name "New name BV" --kind NETWORK --status ARCHIVED
566
+ infaris-crm archive RELATION
567
+ infaris-crm merge R-DUPLICATE --into R-LEADING --yes
568
+ infaris-crm contact-delete RELATION CONTACT_ID --yes
569
+ infaris-crm note RELATION --method EMAIL --at 2026-10-05T12:00:00+02:00 --source mail:ID --body-file n.md
570
+ infaris-crm tidy [--apply] [--include-archived]
571
+ infaris-crm delete RELATION [--yes] # 0.14: without --yes only lists what blocks deletion
572
+ ```
573
+
574
+ `delete` permanently removes an archived customer and applies the same rules as Support's Verwijderen:
575
+ it refuses anything with accounts, organizations, Stripe, quotes, invoices, contacts, history,
576
+ sync traces or Calendar tasks, so in practice it only removes empty test records.
577
+
578
+ `create` answers 409 with the similar customers when the e-mail, website or name
579
+ already exists; `--allow-duplicate` creates anyway and `--dry-run` only reports. `list` hides
580
+ archived customers unless `--include-archived` or `--status` asks for them. `kind` is
581
+ `CLIENT` (default), `SUPPLIER`, `NETWORK`, `EVENT` or `EDUCATION`. `archive` and `update
582
+ --status ARCHIVED` refuse customers with a Stripe customer or Guard organization. `merge`
583
+ moves contacts and history and archives the duplicate; it refuses a duplicate with billing,
584
+ quotes, invoices or a Guard workspace and does not move Calendar tickets. `tidy` is a dry run
585
+ until `--apply`. Support must be deployed with these routes before the commands work.
586
+
560
587
  ## Quotes in Support (0.12.0)
561
588
 
562
589
  `infaris-crm quote` creates Guard quotes as drafts in Support, priced from the
@@ -0,0 +1,186 @@
1
+ import { Option } from "commander";
2
+ import { crmFetch } from "./crm-api.js";
3
+ export const RELATION_KINDS = [
4
+ "CLIENT",
5
+ "SUPPLIER",
6
+ "NETWORK",
7
+ "EVENT",
8
+ "EDUCATION",
9
+ ];
10
+ function output(value) {
11
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
12
+ }
13
+ const LEGAL_SUFFIX = /\s*[(,]?\s*(b\.?v\.?|v\.?o\.?f\.?|n\.?v\.?|c\.?v\.?|vof|bv|nv|eenmanszaak)\s*\)?\s*$/i;
14
+ /**
15
+ * Mirrors Support's normalizeRelationName: collapse whitespace and move a
16
+ * trailing legal form such as "(BV)" to the legal name.
17
+ */
18
+ export function tidyName(name, legalName) {
19
+ const collapsed = name.replace(/\s+/g, " ").trim();
20
+ const match = collapsed.match(LEGAL_SUFFIX);
21
+ const stripped = match ? collapsed.slice(0, match.index).trim() : collapsed;
22
+ if (!stripped)
23
+ return { name: collapsed, legalName };
24
+ const form = match?.[1]?.replace(/\./g, "").toUpperCase();
25
+ return {
26
+ name: stripped,
27
+ legalName: legalName ?? (form ? `${stripped} ${form}` : null),
28
+ };
29
+ }
30
+ /** The renames `tidy` would make; empty when every name is already clean. */
31
+ export function planTidy(items) {
32
+ const changes = [];
33
+ for (const item of items) {
34
+ const next = tidyName(item.name, item.legalName ?? null);
35
+ if (next.name === item.name && next.legalName === (item.legalName ?? null))
36
+ continue;
37
+ changes.push({
38
+ relationNumber: item.relationNumber,
39
+ from: item.name,
40
+ ...next,
41
+ });
42
+ }
43
+ return changes;
44
+ }
45
+ function patch(customer, body) {
46
+ return crmFetch(`/relations/${encodeURIComponent(customer)}`, {
47
+ method: "PATCH",
48
+ headers: { "content-type": "application/json" },
49
+ body: JSON.stringify(body),
50
+ });
51
+ }
52
+ export function registerAdminCommands(program) {
53
+ program
54
+ .command("update <customer>")
55
+ .description("Edit a customer's name, contact data, status or kind (pass only what changes)")
56
+ .option("--name <name>")
57
+ .option("--legal-name <name>")
58
+ .option("--email <email>")
59
+ .option("--phone <phone>")
60
+ .option("--website <url>")
61
+ .option("--contact-person <name>")
62
+ .addOption(new Option("--status <status>").choices([
63
+ "PROSPECT",
64
+ "ACTIVE",
65
+ "CHURNED",
66
+ "ARCHIVED",
67
+ ]))
68
+ .addOption(new Option("--kind <kind>").choices(RELATION_KINDS))
69
+ .option("--json", "Machine-readable output (default)")
70
+ .action(async (customer, opts) => {
71
+ const body = {};
72
+ if (opts.name !== undefined)
73
+ body.name = opts.name;
74
+ if (opts.legalName !== undefined)
75
+ body.legalName = opts.legalName;
76
+ if (opts.email !== undefined)
77
+ body.email = opts.email;
78
+ if (opts.phone !== undefined)
79
+ body.phone = opts.phone;
80
+ if (opts.website !== undefined)
81
+ body.website = opts.website;
82
+ if (opts.contactPerson !== undefined)
83
+ body.contactPerson = opts.contactPerson;
84
+ if (opts.status !== undefined)
85
+ body.status = opts.status;
86
+ if (opts.kind !== undefined)
87
+ body.kind = opts.kind;
88
+ if (!Object.keys(body).length)
89
+ throw new Error("Pass at least one field to change");
90
+ output(await patch(customer, body));
91
+ });
92
+ program
93
+ .command("archive <customer>")
94
+ .description("Archive a customer (hidden from list; history stays). Refused for billing or Guard customers")
95
+ .option("--json", "Machine-readable output (default)")
96
+ .action(async (customer) => {
97
+ output(await patch(customer, { status: "ARCHIVED" }));
98
+ });
99
+ program
100
+ .command("merge <duplicate>")
101
+ .description("Merge a duplicate dossier into the leading one: contacts and history move, the duplicate is archived")
102
+ .requiredOption("--into <customer>", "The dossier that stays")
103
+ .option("--yes", "Confirm the merge")
104
+ .option("--json", "Machine-readable output (default)")
105
+ .action(async (duplicate, opts) => {
106
+ if (!opts.yes)
107
+ throw new Error(`Merging moves all contacts and history of ${duplicate} into ${opts.into} and archives ${duplicate}. Repeat with --yes`);
108
+ output(await crmFetch(`/relations/${encodeURIComponent(duplicate)}/merge`, {
109
+ method: "POST",
110
+ headers: { "content-type": "application/json" },
111
+ body: JSON.stringify({ into: opts.into }),
112
+ }));
113
+ });
114
+ program
115
+ .command("contact-delete <customer> <contactId>")
116
+ .description("Delete a contact person; history entries keep the name but lose the link")
117
+ .option("--yes", "Confirm the deletion")
118
+ .action(async (customer, contactId, opts) => {
119
+ if (!opts.yes)
120
+ throw new Error("Repeat with --yes to delete the contact");
121
+ output(await crmFetch(`/relations/${encodeURIComponent(customer)}/contacts/${encodeURIComponent(contactId)}`, { method: "DELETE" }));
122
+ });
123
+ program
124
+ .command("delete <customer>")
125
+ .description("Permanently delete an archived customer without links or history. Without --yes only reports what blocks it")
126
+ .option("--yes", "Delete for real")
127
+ .action(async (customer, opts) => {
128
+ const path = `/relations/${encodeURIComponent(customer)}`;
129
+ if (!opts.yes) {
130
+ output(await crmFetch(`${path}?dryRun=1`, { method: "DELETE" }));
131
+ return;
132
+ }
133
+ output(await crmFetch(path, {
134
+ method: "DELETE",
135
+ headers: { "content-type": "application/json" },
136
+ body: JSON.stringify({ confirm: customer }),
137
+ }));
138
+ });
139
+ program
140
+ .command("tidy")
141
+ .description("Clean imported company names (line breaks, trailing (BV)/(VOF) moved to the legal name). Dry run unless --apply")
142
+ .option("--apply", "Write the renames")
143
+ .option("--include-archived", "Also tidy archived customers")
144
+ .action(async (opts) => {
145
+ const items = [];
146
+ for (let offset = 0;; offset += 100) {
147
+ const params = new URLSearchParams({
148
+ limit: "100",
149
+ offset: String(offset),
150
+ });
151
+ if (opts.includeArchived)
152
+ params.set("includeArchived", "1");
153
+ const page = (await crmFetch(`/relations?${params}`));
154
+ items.push(...page.items);
155
+ if (offset + 100 >= page.total)
156
+ break;
157
+ }
158
+ const changes = planTidy(items);
159
+ if (!opts.apply) {
160
+ output({ dryRun: true, checked: items.length, changes });
161
+ return;
162
+ }
163
+ const failed = [];
164
+ for (const change of changes) {
165
+ try {
166
+ await patch(change.relationNumber, {
167
+ name: change.name,
168
+ legalName: change.legalName,
169
+ });
170
+ }
171
+ catch (error) {
172
+ failed.push({
173
+ relationNumber: change.relationNumber,
174
+ error: error instanceof Error ? error.message : String(error),
175
+ });
176
+ }
177
+ }
178
+ output({
179
+ applied: changes.length - failed.length,
180
+ checked: items.length,
181
+ failed,
182
+ });
183
+ if (failed.length)
184
+ process.exitCode = 1;
185
+ });
186
+ }
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 { registerAdminCommands, RELATION_KINDS } from "./crm-admin.js";
7
8
  import { registerQuoteCommands } from "./crm-quote.js";
8
9
  import { createTask, addTaskAttachment, listTeamMembers, listTasks, } from "./api.js";
9
10
  import { resolveAttendeeIds } from "./selectors.js";
10
11
  const program = new Command()
11
12
  .name("infaris-crm")
12
- .version("0.12.1")
13
+ .version("0.14.0")
13
14
  .description("Customer dossiers, contact people, contact history and quotes. Shares infaris-calendar login.");
14
15
  function output(value) {
15
16
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
@@ -40,17 +41,35 @@ program
40
41
  program
41
42
  .command("list")
42
43
  .description("Find customers (paginated)")
43
- .option("--search <text>")
44
+ .option("--search <text>", "Matches name, legal name, contact person, website, e-mail and relation number")
45
+ .option("--email <text>", "Find by e-mail address or domain (same as --search)")
46
+ .addOption(new Option("--status <status>").choices([
47
+ "PROSPECT",
48
+ "ACTIVE",
49
+ "CHURNED",
50
+ "ARCHIVED",
51
+ ]))
52
+ .addOption(new Option("--kind <kind>").choices(RELATION_KINDS))
53
+ .option("--include-archived", "Also list archived customers")
44
54
  .option("--limit <number>", "Page size, max 100", "25")
45
55
  .option("--offset <number>", "Page offset", "0")
46
56
  .option("--json", "Machine-readable output (default)")
47
57
  .action(async (opts) => {
58
+ if (opts.search && opts.email)
59
+ throw new Error("Choose --search or --email");
48
60
  const params = new URLSearchParams({
49
61
  limit: opts.limit,
50
62
  offset: opts.offset,
51
63
  });
52
- if (opts.search)
53
- params.set("search", opts.search);
64
+ const search = opts.search ?? opts.email;
65
+ if (search)
66
+ params.set("search", search);
67
+ if (opts.status)
68
+ params.set("status", opts.status);
69
+ if (opts.kind)
70
+ params.set("kind", opts.kind);
71
+ if (opts.includeArchived)
72
+ params.set("includeArchived", "1");
54
73
  output(await crmFetch(`/relations?${params}`));
55
74
  });
56
75
  program
@@ -62,6 +81,9 @@ program
62
81
  .option("--website <url>")
63
82
  .option("--contact-person <name>")
64
83
  .option("--note <text>")
84
+ .addOption(new Option("--kind <kind>", "What the relation is (default CLIENT; use SUPPLIER, NETWORK, EVENT or EDUCATION for non-customers)").choices(RELATION_KINDS))
85
+ .option("--dry-run", "Only report similar existing customers; write nothing")
86
+ .option("--allow-duplicate", "Create even if a customer with the same e-mail, site or name exists")
65
87
  .option("--json", "Machine-readable output (default)")
66
88
  .action(async (opts) => {
67
89
  output(await crmFetch("/relations", {
@@ -74,6 +96,9 @@ program
74
96
  website: opts.website,
75
97
  contactPerson: opts.contactPerson,
76
98
  initialNote: opts.note,
99
+ kind: opts.kind,
100
+ dryRun: opts.dryRun || undefined,
101
+ allowDuplicate: opts.allowDuplicate || undefined,
77
102
  }),
78
103
  }));
79
104
  });
@@ -147,6 +172,7 @@ program
147
172
  ]))
148
173
  .option("--contact <id>", "Customer contact person id")
149
174
  .option("--at <iso>", "When the contact occurred (default now)")
175
+ .option("--source <ref>", "Where the note comes from, for example mail:<message id>")
150
176
  .option("--json", "Machine-readable output (default)")
151
177
  .action(async (customer, opts) => {
152
178
  if (opts.body !== undefined && opts.bodyFile !== undefined)
@@ -167,6 +193,7 @@ program
167
193
  contactMethod: opts.method,
168
194
  outcome: opts.outcome,
169
195
  contactId: opts.contact,
196
+ sourceRef: opts.source,
170
197
  occurredAt: opts.at || new Date().toISOString(),
171
198
  }),
172
199
  }));
@@ -193,6 +220,7 @@ program
193
220
  }),
194
221
  }));
195
222
  });
223
+ registerAdminCommands(program);
196
224
  registerQuoteCommands(program);
197
225
  program.parseAsync(process.argv).catch((error) => {
198
226
  process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
package/dist/crm-quote.js CHANGED
@@ -136,7 +136,7 @@ export function registerQuoteCommands(program) {
136
136
  });
137
137
  quote
138
138
  .command("send <number>")
139
- .description("Mark the quote SENT once the mail draft with the PDF is ready")
139
+ .description("Record the quote as SENT after confirmed sending; this command does not send email")
140
140
  .option("--json", "Machine-readable output (default)")
141
141
  .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}/send`, json({}))));
142
142
  quote
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.12.1");
28
+ .version("0.14.0");
29
29
  const loginCmd = program
30
30
  .command("login")
31
31
  .description("Sign in with Infaris in your browser and store a token")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infaris/calendar-cli",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
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",
package/dist/voice.js DELETED
@@ -1,321 +0,0 @@
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
- }