@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 +181 -13
- package/dist/api.js +147 -26
- package/dist/auth.js +24 -1
- package/dist/crm-api.js +5 -1
- package/dist/crm-index.js +4 -2
- package/dist/crm-quote.js +174 -0
- package/dist/index.js +536 -23
- package/dist/mail-draft.js +357 -0
- package/dist/mail-send.js +97 -0
- package/dist/voice.js +321 -0
- package/package.json +1 -1
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.
|
|
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",
|