-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcall.ts
More file actions
1112 lines (990 loc) · 36.6 KB
/
Copy pathcall.ts
File metadata and controls
1112 lines (990 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execSync } from "child_process";
import { existsSync, readFileSync } from "fs";
import { createRequire } from "module";
import { dirname, join, resolve } from "path";
import * as readline from "readline";
import { fileURLToPath } from "url";
import type { Environment, StateFile } from "./types.ts";
const require = createRequire(import.meta.url);
// ─────────────────────────────────────────────────────────────────────────────
// Configuration
// ─────────────────────────────────────────────────────────────────────────────
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASE_DIR = join(__dirname, "..");
type ResourceType = "assistant" | "squad";
interface CallConfig {
env: Environment;
target: string;
resourceType: ResourceType;
token: string;
baseUrl: string;
}
// ─────────────────────────────────────────────────────────────────────────────
// Argument Parsing
// ─────────────────────────────────────────────────────────────────────────────
const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
function printUsage(): void {
console.error("❌ Usage: npm run call <org> -a <assistant-name>");
console.error(" npm run call <org> -s <squad-name>");
console.error("");
console.error(" Options:");
console.error(" -a <name> Call an assistant by name");
console.error(" -s <name> Call a squad by name");
console.error("");
console.error(" Examples:");
console.error(" npm run call my-org -a my-assistant");
console.error(" npm run call my-org -s my-squad");
}
function parseArgs(): CallConfig {
const args = process.argv.slice(2);
if (args.length < 3) {
printUsage();
process.exit(1);
}
const env = args[0] as Environment;
if (!SLUG_RE.test(env)) {
console.error(`❌ Invalid org name: ${env}`);
console.error(
" Must be lowercase alphanumeric with optional hyphens (e.g., dev, my-org)",
);
process.exit(1);
}
// Parse flags
let resourceType: ResourceType | null = null;
let target: string | null = null;
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (arg === "-a" || arg === "--assistant") {
if (resourceType) {
console.error("❌ Cannot specify both -a and -s");
process.exit(1);
}
const nextArg = args[i + 1];
if (!nextArg) {
console.error("❌ Missing assistant name after -a/--assistant");
printUsage();
process.exit(1);
}
resourceType = "assistant";
target = nextArg;
i++;
} else if (arg === "-s" || arg === "--squad") {
if (resourceType) {
console.error("❌ Cannot specify both -a and -s");
process.exit(1);
}
const nextArg = args[i + 1];
if (!nextArg) {
console.error("❌ Missing squad name after -s/--squad");
printUsage();
process.exit(1);
}
resourceType = "squad";
target = nextArg;
i++;
}
}
if (!resourceType || !target) {
console.error("❌ Must specify either -a <assistant> or -s <squad>");
printUsage();
process.exit(1);
}
// Load environment variables
const { token, baseUrl } = loadEnvFile(env);
return { env, target, resourceType, token, baseUrl };
}
function loadEnvFile(env: string): { token: string; baseUrl: string } {
const envFiles = [
join(BASE_DIR, `.env.${env}`),
join(BASE_DIR, `.env.${env}.local`),
join(BASE_DIR, ".env.local"),
];
const envVars: Record<string, string> = {};
for (const envFile of envFiles) {
if (existsSync(envFile)) {
const content = readFileSync(envFile, "utf-8");
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIndex = trimmed.indexOf("=");
if (eqIndex === -1) continue;
const key = trimmed.slice(0, eqIndex).trim();
let value = trimmed.slice(eqIndex + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
if (envVars[key] === undefined) {
envVars[key] = value;
}
}
}
}
const token = process.env.VAPI_TOKEN || envVars.VAPI_TOKEN;
const baseUrl =
process.env.VAPI_BASE_URL || envVars.VAPI_BASE_URL || "https://api.vapi.ai";
if (!token) {
console.error("❌ VAPI_TOKEN environment variable is required");
console.error(` Create a .env.${env} file with: VAPI_TOKEN=your-token`);
process.exit(1);
}
return { token, baseUrl };
}
// ─────────────────────────────────────────────────────────────────────────────
// Permission Check
// ─────────────────────────────────────────────────────────────────────────────
async function checkMicrophonePermission(): Promise<boolean> {
const platform = process.platform;
if (platform === "darwin") {
// macOS - check and prompt for microphone permission
console.log("🎤 Checking microphone permissions...");
try {
// Try to get microphone permission status using AppleScript
const result = execSync(
`osascript -e 'tell application "System Events" to return (name of processes whose name contains "sox" or name contains "rec")'`,
{ encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] },
);
// If we get here without error, we have some level of access
} catch {
// Ignore errors from the check itself
}
// Actually test microphone access by trying to record briefly
try {
// Check if sox/rec is available
execSync("which sox", { stdio: "pipe" });
// Try a quick recording to trigger permission prompt
console.log(
" Testing microphone access (this may prompt for permission)...",
);
execSync(
"rec -q -t raw -r 16000 -b 16 -c 1 -e signed-integer /dev/null trim 0 0.1 2>/dev/null || true",
{
timeout: 5000,
stdio: "pipe",
},
);
console.log("✅ Microphone permission granted\n");
return true;
} catch {
// sox not installed or permission denied
console.log("⚠️ Could not verify microphone access.");
console.log(
" If prompted, please grant microphone permission in System Settings.",
);
console.log(" System Settings > Privacy & Security > Microphone\n");
// Ask user to continue anyway
const shouldContinue = await askUserConfirmation(
"Continue without confirmed microphone access? (y/n): ",
);
return shouldContinue;
}
} else if (platform === "linux") {
// Linux - check if audio devices are accessible
console.log("🎤 Checking audio devices...");
try {
// Check for ALSA devices
execSync("arecord -l 2>/dev/null | grep -q card", { stdio: "pipe" });
console.log("✅ Audio recording devices found\n");
return true;
} catch {
console.log("⚠️ No audio recording devices found.");
console.log(
" Make sure your microphone is connected and ALSA is configured.\n",
);
const shouldContinue = await askUserConfirmation(
"Continue without confirmed microphone access? (y/n): ",
);
return shouldContinue;
}
} else if (platform === "win32") {
// Windows - just inform the user
console.log(
"🎤 On Windows, you may be prompted to grant microphone access.\n",
);
return true;
}
return true;
}
function askUserConfirmation(question: string): Promise<boolean> {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(question, (answer) => {
rl.close();
resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
});
});
}
// ─────────────────────────────────────────────────────────────────────────────
// State Loading
// ─────────────────────────────────────────────────────────────────────────────
function loadState(env: Environment): StateFile {
const stateFilePath = join(BASE_DIR, `.vapi-state.${env}.json`);
if (!existsSync(stateFilePath)) {
console.error(`❌ State file not found: .vapi-state.${env}.json`);
console.error(
" Run 'npm run apply -- " + env + "' first to create resources",
);
process.exit(1);
}
try {
const content = readFileSync(stateFilePath, "utf-8");
return JSON.parse(content) as StateFile;
} catch (error) {
console.error(`❌ Failed to parse state file: ${error}`);
process.exit(1);
}
}
function resolveTarget(
state: StateFile,
target: string,
resourceType: ResourceType,
): string {
if (resourceType === "squad") {
const squads = state.squads || {};
const uuid = squads[target]?.uuid;
if (!uuid) {
console.error(`❌ Squad not found: ${target}`);
console.error(" Available squads:");
const squadKeys = Object.keys(squads);
if (squadKeys.length === 0) {
console.error(" (no squads in state file)");
} else {
squadKeys.forEach((k) => console.error(` - ${k}`));
}
process.exit(1);
}
return uuid;
} else {
const uuid = state.assistants[target]?.uuid;
if (!uuid) {
console.error(`❌ Assistant not found: ${target}`);
console.error(" Available assistants:");
const assistantKeys = Object.keys(state.assistants);
if (assistantKeys.length === 0) {
console.error(" (no assistants in state file)");
} else {
assistantKeys.forEach((k) => console.error(` - ${k}`));
}
process.exit(1);
}
return uuid;
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Call Creation
// ─────────────────────────────────────────────────────────────────────────────
interface CreateCallResponse {
id: string;
transport?: {
websocketCallUrl?: string;
};
}
async function createCall(
config: CallConfig,
targetId: string,
): Promise<CreateCallResponse> {
const url = `${config.baseUrl}/call`;
const body: Record<string, unknown> = {
transport: {
provider: "vapi.websocket",
audioFormat: {
format: "pcm_s16le",
container: "raw",
sampleRate: 16000,
},
},
};
if (config.resourceType === "squad") {
body.squadId = targetId;
} else {
body.assistantId = targetId;
}
console.log(`📞 Creating call...`);
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${config.token}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text();
console.error(`❌ Failed to create call: ${response.status}`);
console.error(` ${errorText}`);
process.exit(1);
}
return response.json() as Promise<CreateCallResponse>;
}
// ─────────────────────────────────────────────────────────────────────────────
// WebSocket Connection
// ─────────────────────────────────────────────────────────────────────────────
interface TranscriptMessage {
type: "transcript";
role: "user" | "assistant";
transcriptType: "partial" | "final";
transcript: string;
}
interface SpeechUpdateMessage {
type: "speech-update";
role: "user" | "assistant";
status: "started" | "stopped";
}
interface CallEndedMessage {
type: "call-ended";
reason?: string;
}
// Individual tool call entries in a `tool-calls` event. Vapi can deliver
// the function name and arguments either at the top level (recent shape)
// or nested under a `function` object (older / server-url shape). We
// accept both and fall back to `<unknown>` so an unfamiliar payload
// never crashes the CLI.
interface ToolCallItem {
id?: string;
name?: string;
arguments?: unknown;
function?: {
name?: string;
arguments?: unknown;
};
}
interface ToolCallsMessage {
type: "tool-calls";
toolCallList?: ToolCallItem[];
toolWithToolCallList?: Array<{ toolCall?: ToolCallItem }>;
}
interface ToolCallResultMessage {
type: "tool-call-result";
toolCallId?: string;
name?: string;
result?: unknown;
error?: unknown;
}
interface StatusUpdateMessage {
type: "status-update";
status?: string;
endedReason?: string;
}
interface HangMessage {
type: "hang";
}
interface TransferUpdateMessage {
type: "transfer-update";
destination?: {
type?: string;
assistantName?: string;
number?: string;
sipUri?: string;
};
}
type ControlMessage =
| TranscriptMessage
| SpeechUpdateMessage
| CallEndedMessage
| ToolCallsMessage
| ToolCallResultMessage
| StatusUpdateMessage
| HangMessage
| TransferUpdateMessage
| { type: string };
// Cartesia Sonic and other chunked TTS providers stream each final
// transcript as 2-4 separate events per utterance, often split mid-sentence.
// Rather than rendering each fragment on its own `🤖 Assistant:` line, we
// buffer consecutive finals from the same role and flush them as a single
// merged line once the speaker pauses for `COALESCE_TIMEOUT_MS`. The same
// mechanism helps with user transcriber micro-pauses (Soniox, Gladia).
interface FinalBuffer {
role: "user" | "assistant";
fragments: string[];
flushTimer: NodeJS.Timeout | null;
}
interface CallDisplayState {
// The most recent partial transcript line written to stdout (so we can
// erase it before writing a new line — see `clearWrittenLine`).
lastTranscript: string;
// Pending buffered finals, waiting to be coalesced into a single line.
finalBuffer: FinalBuffer | null;
}
// Max wait between consecutive finals from the same role before the buffer
// auto-flushes. 600ms empirically captures most Cartesia chunk gaps without
// introducing noticeable display latency for the developer. Tune if your
// voice provider streams slower or faster.
const COALESCE_TIMEOUT_MS = 600;
function flushFinalBuffer(state: CallDisplayState): void {
const buf = state.finalBuffer;
if (!buf) return;
if (buf.flushTimer) {
clearTimeout(buf.flushTimer);
}
state.finalBuffer = null;
const merged = buf.fragments.join(" ").replace(/\s+/g, " ").trim();
if (merged.length === 0) return;
const prefix = buf.role === "user" ? "🎤 You" : "🤖 Assistant";
clearWrittenLine(process.stdout, state.lastTranscript);
state.lastTranscript = "";
console.log(`${prefix}: ${merged}`);
}
// Print an out-of-band event (tool call, handoff, status change, etc.)
// while respecting the in-flight transcript buffer and any partial line
// that's currently being overwritten in the TTY. Without this wrapper,
// event lines would either corrupt the partial overwrite region or
// interleave awkwardly with a pending coalesced final.
function printEvent(state: CallDisplayState, line: string): void {
flushFinalBuffer(state);
clearWrittenLine(process.stdout, state.lastTranscript);
state.lastTranscript = "";
console.log(line);
}
function truncate(text: string, maxLen: number): string {
if (text.length <= maxLen) return text;
return `${text.slice(0, maxLen)}... [truncated, ${text.length} chars]`;
}
function previewJson(value: unknown, maxLen: number): string {
try {
// Tool call arguments occasionally arrive as a JSON-encoded string
// instead of an object. Re-parse so the preview shows structured
// content rather than an escape-riddled single-line string.
let v: unknown = value;
if (typeof v === "string") {
const asString: string = v;
try {
v = JSON.parse(asString);
} catch {
return truncate(asString, maxLen);
}
}
const json = JSON.stringify(v);
if (typeof json !== "string") return "<unserializable>";
return truncate(json, maxLen);
} catch {
return "<unserializable>";
}
}
// Squad handoffs are delivered as `tool-calls` events where the function
// name follows the `handoff_to_<Target_Name>` convention (underscores
// replacing spaces in the target assistant's display name). Extract the
// target name when this naming pattern applies so we can render a
// distinct `🔀 Handoff → Target Name` line instead of a generic tool
// call. Returns null when the name doesn't match the handoff pattern.
function handoffTargetFromName(name: string): string | null {
const match = /^handoff_to_(.+)$/.exec(name);
const captured = match?.[1];
if (!captured) return null;
return captured.replace(/_/g, " ").trim();
}
function formatToolCall(call: ToolCallItem): string {
const name = call.name ?? call.function?.name ?? "<unknown>";
const args = call.arguments ?? call.function?.arguments;
const target = handoffTargetFromName(name);
if (target) {
return `🔀 Handoff → ${target}`;
}
if (args === undefined || args === null) {
return `🔧 Tool call: ${name}()`;
}
return `🔧 Tool call: ${name}(${previewJson(args, 160)})`;
}
function formatTransferDestination(
dest: TransferUpdateMessage["destination"],
): string {
if (!dest) return "";
if (dest.type === "assistant" && dest.assistantName) {
return ` → ${dest.assistantName}`;
}
if (dest.type === "number" && dest.number) {
return ` → ${dest.number}`;
}
if (dest.type === "sip" && dest.sipUri) {
return ` → ${dest.sipUri}`;
}
return dest.type ? ` (${dest.type})` : "";
}
async function connectWebSocket(
websocketUrl: string,
config: CallConfig,
): Promise<void> {
return new Promise((resolve, reject) => {
console.log(`🔌 Connecting to WebSocket...`);
const ws = new WebSocket(websocketUrl, {
headers: {
Authorization: `Bearer ${config.token}`,
},
} as WebSocket extends {
new (
url: string,
protocols?: string | string[],
options?: unknown,
): WebSocket;
}
? unknown
: never);
let audioContext: ReturnType<typeof createAudioContext> | null = null;
let micStream: ReturnType<typeof createMicrophoneStream> | null = null;
let isConnected = false;
const state: CallDisplayState = {
lastTranscript: "",
finalBuffer: null,
};
// Graceful shutdown
const cleanup = () => {
flushFinalBuffer(state);
clearWrittenLine(process.stdout, state.lastTranscript);
state.lastTranscript = "";
console.log("👋 Ending call...");
if (micStream) {
micStream.stop();
}
if (audioContext) {
audioContext.close();
}
if (ws.readyState === WebSocket.OPEN) {
ws.close();
}
resolve();
};
process.on("SIGINT", cleanup);
process.on("SIGTERM", cleanup);
ws.onopen = () => {
console.log("✅ Connected!");
console.log("🎤 Speak into your microphone...");
console.log(" Press Ctrl+C to end the call\n");
isConnected = true;
// Start audio capture
try {
audioContext = createAudioContext();
micStream = createMicrophoneStream((audioData: Buffer) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(audioData);
}
});
} catch (error) {
console.error("⚠️ Could not start microphone:", error);
console.log(" Continuing without microphone input...");
}
};
ws.onmessage = async (event) => {
const data = event.data;
// Binary audio data from assistant
if (data instanceof Buffer || data instanceof ArrayBuffer) {
if (audioContext) {
audioContext.playAudio(data);
}
} else if (typeof Blob !== "undefined" && data instanceof Blob) {
if (audioContext) {
const arrayBuffer = await data.arrayBuffer();
audioContext.playAudio(arrayBuffer);
}
} else if (ArrayBuffer.isView(data)) {
if (audioContext) {
audioContext.playAudio(data.buffer as ArrayBuffer);
}
} else {
// Control message (JSON)
try {
const message = JSON.parse(event.data as string) as ControlMessage;
handleControlMessage(message, state);
} catch {
// Ignore parse errors
}
}
};
ws.onerror = (error) => {
console.error("❌ WebSocket error:", error);
if (!isConnected) {
reject(error);
}
};
ws.onclose = (event) => {
flushFinalBuffer(state);
clearWrittenLine(process.stdout, state.lastTranscript);
state.lastTranscript = "";
console.log(`📴 Call ended (code: ${event.code})`);
cleanup();
};
});
}
// Approximate terminal display width of a string. Most terminals render
// emojis and CJK glyphs as 2 cells and ASCII as 1; we use a coarse range
// check rather than pulling in a full Unicode width table. Iteration is by
// code point so surrogate pairs (emoji) count once.
function getDisplayWidth(text: string): number {
let width = 0;
for (const char of text) {
const code = char.codePointAt(0) ?? 0;
if (code === 0xfe0f || (code >= 0x200b && code <= 0x200f)) {
// Variation selectors / zero-width joiners: no display width
continue;
}
if (
(code >= 0x1100 && code <= 0x115f) || // Hangul Jamo
(code >= 0x2e80 && code <= 0x303e) || // CJK radicals / punctuation
(code >= 0x3041 && code <= 0x33ff) || // Hiragana, Katakana, etc.
(code >= 0x3400 && code <= 0x4dbf) || // CJK Extension A
(code >= 0x4e00 && code <= 0x9fff) || // CJK Unified Ideographs
(code >= 0xa000 && code <= 0xa4cf) || // Yi Syllables
(code >= 0xac00 && code <= 0xd7a3) || // Hangul Syllables
(code >= 0xf900 && code <= 0xfaff) || // CJK Compatibility Ideographs
(code >= 0xfe30 && code <= 0xfe4f) || // CJK Compatibility Forms
(code >= 0xff00 && code <= 0xff60) || // Fullwidth forms
(code >= 0xffe0 && code <= 0xffe6) || // Fullwidth signs
(code >= 0x1f300 && code <= 0x1f64f) || // Emoji: misc symbols / pictographs / emoticons
(code >= 0x1f680 && code <= 0x1f6ff) || // Emoji: transport / map
(code >= 0x1f900 && code <= 0x1f9ff) || // Supplemental symbols / pictographs
(code >= 0x1fa70 && code <= 0x1faff) || // Symbols & pictographs extended-A
(code >= 0x2600 && code <= 0x27bf) // Misc symbols, dingbats
) {
width += 2;
} else {
width += 1;
}
}
return width;
}
// Erase the previously-written partial transcript, accounting for terminal
// wrap. \r alone only returns to column 0 of the *current* row, so wrapped
// content above the cursor would otherwise stay on screen and pile up as
// the partial is rewritten over and over.
function clearWrittenLine(stream: NodeJS.WriteStream, text: string): void {
if (!text || !stream.isTTY) return;
const cols = stream.columns || 80;
const rows = Math.max(1, Math.ceil(getDisplayWidth(text) / cols));
readline.cursorTo(stream, 0);
readline.clearLine(stream, 0);
for (let i = 1; i < rows; i++) {
readline.moveCursor(stream, 0, -1);
readline.clearLine(stream, 0);
}
}
function handleControlMessage(
message: ControlMessage,
state: CallDisplayState,
): void {
switch (message.type) {
case "transcript": {
const tm = message as TranscriptMessage;
const prefix = tm.role === "user" ? "🎤 You" : "🤖 Assistant";
if (tm.transcriptType === "final") {
// A role change means we have a held final buffer from the other
// speaker (e.g. assistant buffered fragments, user barges in and
// starts emitting finals) — flush it immediately so the previous
// turn prints as a complete line before the new one accumulates.
if (state.finalBuffer && state.finalBuffer.role !== tm.role) {
flushFinalBuffer(state);
}
if (!state.finalBuffer) {
state.finalBuffer = {
role: tm.role,
fragments: [],
flushTimer: null,
};
}
state.finalBuffer.fragments.push(tm.transcript);
if (state.finalBuffer.flushTimer) {
clearTimeout(state.finalBuffer.flushTimer);
}
state.finalBuffer.flushTimer = setTimeout(() => {
flushFinalBuffer(state);
}, COALESCE_TIMEOUT_MS);
} else if (process.stdout.isTTY) {
// Live partial overwrite only makes sense in a TTY. In non-TTY
// output (piped to a file, CI logs, etc.) every partial would
// print as its own line and produce huge spam — skip them and
// wait for the final.
const line = `${prefix}: ${tm.transcript}`;
clearWrittenLine(process.stdout, state.lastTranscript);
process.stdout.write(line);
state.lastTranscript = line;
}
break;
}
case "speech-update": {
const sm = message as SpeechUpdateMessage;
if (sm.status === "started") {
// If there's a held final buffer from the other speaker, flush it
// before announcing the new speaker so the banner doesn't appear
// above still-pending transcript from the last turn.
if (state.finalBuffer && state.finalBuffer.role !== sm.role) {
flushFinalBuffer(state);
}
const who = sm.role === "user" ? "You" : "Assistant";
clearWrittenLine(process.stdout, state.lastTranscript);
state.lastTranscript = "";
console.log(`💬 ${who} started speaking...`);
}
break;
}
case "call-ended": {
// Flush any held fragments before the call-ended line so the last
// words printed match what the speaker actually said.
flushFinalBuffer(state);
const cm = message as CallEndedMessage;
const reasonLabels: Record<string, string> = {
"silence-timed-out": "Silence timeout (no speech detected)",
"assistant-ended-call": "Assistant ended the call",
"customer-ended-call": "Customer ended the call",
"max-duration-reached": "Maximum call duration reached",
"assistant-error": "Assistant error",
"pipeline-error": "Pipeline error",
"voicemail-reached": "Voicemail detected",
"customer-did-not-answer": "No answer",
"assistant-request-returned-error": "Assistant request error",
"assistant-not-found": "Assistant not found",
};
const label = cm.reason
? (reasonLabels[cm.reason] ?? cm.reason)
: "unknown reason";
clearWrittenLine(process.stdout, state.lastTranscript);
state.lastTranscript = "";
console.log(`📞 Call ended: ${label}`);
break;
}
case "tool-calls": {
const tm = message as ToolCallsMessage;
// Some payloads deliver tool calls directly in `toolCallList`;
// others nest them in `toolWithToolCallList[].toolCall` (the
// "tool + toolCall" pair shape Vapi uses when it also wants to
// include the registered tool definition). Normalize both.
const calls: ToolCallItem[] = [
...(tm.toolCallList ?? []),
...(tm.toolWithToolCallList
?.map((e) => e.toolCall)
.filter((c): c is ToolCallItem => Boolean(c)) ?? []),
];
for (const call of calls) {
try {
printEvent(state, formatToolCall(call));
} catch {
// Never let an unexpected tool call shape crash the CLI —
// just fall through and drop the formatter output.
}
}
break;
}
case "tool-call-result": {
const tm = message as ToolCallResultMessage;
const name = tm.name ?? "<tool>";
try {
if (tm.error !== undefined && tm.error !== null && tm.error !== "") {
printEvent(
state,
`❌ Tool failed: ${name} → ${previewJson(tm.error, 200)}`,
);
} else if (tm.result !== undefined) {
printEvent(
state,
`✅ Tool result: ${name} → ${previewJson(tm.result, 200)}`,
);
}
} catch {
// Preserve CLI stability on unexpected payload shapes.
}
break;
}
case "status-update": {
const sm = message as StatusUpdateMessage;
if (!sm.status) break;
// Drop `queued`, `ringing`, `scheduled` — they're irrelevant for a
// WebSocket-transport developer call (there's no phone leg) and
// just add noise. Surface the useful lifecycle transitions.
if (
sm.status === "in-progress" ||
sm.status === "forwarding" ||
sm.status === "ended"
) {
const suffix =
sm.status === "ended" && sm.endedReason
? ` (reason: ${sm.endedReason})`
: "";
printEvent(state, `📞 Status: ${sm.status}${suffix}`);
}
break;
}
case "hang": {
// `hang` is a heads-up that the call is about to terminate (e.g.
// silence timeout is imminent). Useful for debugging hang-reason
// issues; payload fields vary so we just surface the signal.
printEvent(state, `⚠️ Hang warning`);
break;
}
case "transfer-update": {
const tm = message as TransferUpdateMessage;
printEvent(
state,
`🔀 Transfer${formatTransferDestination(tm.destination)}`,
);
break;
}
default:
// Silently ignore other message types (conversation-update,
// model-output, function-call, user-interrupted, etc.). These
// fire frequently and would drown out real transcript content.
// Set `VAPI_CALL_DEBUG=1` in the environment to log unknown
// message types for discovery work.
if (process.env.VAPI_CALL_DEBUG === "1") {
try {
const m = message as Record<string, unknown>;
const typeStr = typeof m.type === "string" ? m.type : "<untyped>";
const preview = previewJson(m, 200);
printEvent(state, `🔍 [debug] ${typeStr}: ${preview}`);
} catch {
// Debug output is best-effort; never crash from it.
}
}
break;
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Audio Utilities (Stubs - require native modules)
// ─────────────────────────────────────────────────────────────────────────────
interface SpeakerInstance {
write: (data: Buffer) => void;
end: () => void;
}
type SpeakerConstructor = new (options: {
channels: number;
bitDepth: number;
sampleRate: number;
}) => SpeakerInstance;
interface MicrophoneAudioStream {
on: (
event: "data" | "error",
listener: ((data: Buffer) => void) | ((error: Error) => void),
) => void;
}
interface MicrophoneInstance {
getAudioStream: () => MicrophoneAudioStream;
start: () => void;
stop: () => void;
}
type MicrophoneFactory = (
options: Record<string, string>,
) => MicrophoneInstance;
function createAudioContext(): {
playAudio: (data: Buffer | ArrayBuffer) => void;
close: () => void;
} {
let Speaker: SpeakerConstructor | null = null;
let speakerInstance: SpeakerInstance | null = null;
try {
Speaker = require("speaker") as SpeakerConstructor;
speakerInstance = new Speaker!({
channels: 1,
bitDepth: 16,
sampleRate: 16000,
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (msg.includes("Cannot find module")) {
console.warn(
"⚠️ 'speaker' module not installed. Audio playback disabled.",
);
console.warn(" Install with: npm install speaker");
} else if (
msg.includes("Could not locate the bindings file") ||
msg.includes("NODE_MODULE_VERSION")
) {
console.warn(
"⚠️ 'speaker' native bindings not built for this Node version.",
);
console.warn(" Rebuild with: npm rebuild speaker");
} else {
console.warn(`⚠️ Could not initialize speaker: ${msg}`);
}