create-micdrop 0.0.0-stage → 0.1.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.
Files changed (66) hide show
  1. package/README.md +61 -2
  2. package/dist/index.js +1315 -0
  3. package/package.json +53 -4
  4. package/templates/expo/App.tsx +123 -0
  5. package/templates/expo/README.md +65 -0
  6. package/templates/expo/_env.example +6 -0
  7. package/templates/expo/_gitignore +7 -0
  8. package/templates/expo/app.json +34 -0
  9. package/templates/expo/babel.config.js +6 -0
  10. package/templates/expo/index.ts +4 -0
  11. package/templates/expo/package.json +39 -0
  12. package/templates/expo/server/index.ts +36 -0
  13. package/templates/expo/server/tsconfig.json +14 -0
  14. package/templates/expo/src/serverUrl.ts +20 -0
  15. package/templates/expo/tsconfig.json +8 -0
  16. package/templates/nextjs/README.md +40 -0
  17. package/templates/nextjs/_env.example +9 -0
  18. package/templates/nextjs/_gitignore +7 -0
  19. package/templates/nextjs/app/CallLoader.tsx +10 -0
  20. package/templates/nextjs/app/VoiceCall.tsx +71 -0
  21. package/templates/nextjs/app/globals.css +45 -0
  22. package/templates/nextjs/app/layout.tsx +16 -0
  23. package/templates/nextjs/app/page.tsx +10 -0
  24. package/templates/nextjs/next.config.ts +5 -0
  25. package/templates/nextjs/package.json +34 -0
  26. package/templates/nextjs/server/index.ts +35 -0
  27. package/templates/nextjs/tsconfig.json +25 -0
  28. package/templates/nextjs/tsconfig.server.json +14 -0
  29. package/templates/node/README.md +48 -0
  30. package/templates/node/_env.example +6 -0
  31. package/templates/node/_gitignore +4 -0
  32. package/templates/node/package.json +21 -0
  33. package/templates/node/src/server.ts +34 -0
  34. package/templates/node/tsconfig.json +14 -0
  35. package/templates/phone/README.md +86 -0
  36. package/templates/phone/_env.example +31 -0
  37. package/templates/phone/_gitignore +5 -0
  38. package/templates/phone/package.json +25 -0
  39. package/templates/phone/src/recording.ts +65 -0
  40. package/templates/phone/src/server.ts +212 -0
  41. package/templates/phone/src/webhooks.ts +88 -0
  42. package/templates/phone/telephony/plivo/env.example +6 -0
  43. package/templates/phone/telephony/plivo/setup.md +7 -0
  44. package/templates/phone/telephony/plivo/telephony.ts +111 -0
  45. package/templates/phone/telephony/telnyx/env.example +8 -0
  46. package/templates/phone/telephony/telnyx/setup.md +9 -0
  47. package/templates/phone/telephony/telnyx/telephony.ts +107 -0
  48. package/templates/phone/telephony/twilio/env.example +6 -0
  49. package/templates/phone/telephony/twilio/setup.md +7 -0
  50. package/templates/phone/telephony/twilio/telephony.ts +98 -0
  51. package/templates/phone/telephony/vonage/env.example +7 -0
  52. package/templates/phone/telephony/vonage/setup.md +15 -0
  53. package/templates/phone/telephony/vonage/telephony.ts +105 -0
  54. package/templates/phone/tsconfig.json +14 -0
  55. package/templates/vite-react/README.md +39 -0
  56. package/templates/vite-react/_env.example +2 -0
  57. package/templates/vite-react/_gitignore +4 -0
  58. package/templates/vite-react/index.html +12 -0
  59. package/templates/vite-react/package.json +36 -0
  60. package/templates/vite-react/src/client/App.tsx +75 -0
  61. package/templates/vite-react/src/client/main.tsx +10 -0
  62. package/templates/vite-react/src/client/styles.css +45 -0
  63. package/templates/vite-react/src/server/index.ts +42 -0
  64. package/templates/vite-react/tsconfig.json +16 -0
  65. package/templates/vite-react/tsconfig.server.json +14 -0
  66. package/templates/vite-react/vite.config.ts +23 -0
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "concurrently -n server,next -c blue,green \"npm:dev:server\" \"npm:dev:next\"",
8
+ "dev:server": "tsx watch --env-file=.env server/index.ts",
9
+ "dev:next": "next dev",
10
+ "build": "next build",
11
+ "start": "concurrently -n server,next -c blue,green \"npm:start:server\" \"npm:start:next\"",
12
+ "start:server": "tsx --env-file=.env server/index.ts",
13
+ "start:next": "next start",
14
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.server.json"
15
+ },
16
+ "dependencies": {
17
+ "@micdrop/react": "*",
18
+ "@micdrop/server": "*",
19
+ "@micdrop/web": "*",
20
+ "next": "^16.4.6",
21
+ "react": "^19.3.1",
22
+ "react-dom": "^19.3.1",
23
+ "ws": "^8.19.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.19.13",
27
+ "@types/react": "^19.3.0",
28
+ "@types/react-dom": "^19.3.0",
29
+ "@types/ws": "^8.18.1",
30
+ "concurrently": "^9.2.1",
31
+ "tsx": "^4.20.6",
32
+ "typescript": "^5.9.3"
33
+ }
34
+ }
@@ -0,0 +1,35 @@
1
+ // The voice server, next to the Next.js app. Each WebSocket connection is a
2
+ // call: Micdrop transcribes what the user says, has the agent answer and
3
+ // speaks the answer back.
4
+ // https://micdrop.dev/docs/server
5
+
6
+ import { endCallTool, MicdropServer } from '@micdrop/server'
7
+ import { WebSocketServer } from 'ws'
8
+ import { createAi } from './ai'
9
+
10
+ const PORT = Number(process.env.PORT || 3001)
11
+
12
+ const server = new WebSocketServer({ port: PORT })
13
+
14
+ server.on('connection', (socket) => {
15
+ new MicdropServer(socket, {
16
+ // Spoken right away, before the user says anything
17
+ // https://micdrop.dev/docs/server/first-message
18
+ firstMessage: 'Hi! What can I do for you?',
19
+
20
+ // The answer shows up in the page as it is written
21
+ // https://micdrop.dev/docs/server/partial-messages
22
+ partialMessages: true,
23
+
24
+ // The providers picked when the project was created, in ai.ts
25
+ ...createAi({
26
+ systemPrompt:
27
+ 'You are a friendly assistant. Your answers are spoken out loud, so keep them short and conversational.',
28
+ // Lets the assistant hang up once the user says goodbye
29
+ // https://micdrop.dev/docs/server/auto-end-call
30
+ tools: [endCallTool()],
31
+ }),
32
+ })
33
+ })
34
+
35
+ console.log(`Micdrop server listening on ws://localhost:${PORT}`)
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
5
+ "allowJs": false,
6
+ "skipLibCheck": true,
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "esModuleInterop": true,
10
+ "module": "ESNext",
11
+ "moduleResolution": "bundler",
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "jsx": "react-jsx",
15
+ "incremental": true,
16
+ "plugins": [{ "name": "next" }]
17
+ },
18
+ "include": [
19
+ "next-env.d.ts",
20
+ "app",
21
+ ".next/types/**/*.ts",
22
+ ".next/dev/types/**/*.ts"
23
+ ],
24
+ "exclude": ["node_modules", "server"]
25
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "noEmit": true
12
+ },
13
+ "include": ["server"]
14
+ }
@@ -0,0 +1,48 @@
1
+ # {{name}}
2
+
3
+ A voice agent server built with [Micdrop](https://micdrop.dev). It listens on a
4
+ WebSocket, and each connection is a call with the AI.
5
+
6
+ - [`src/server.ts`](./src/server.ts) runs each call
7
+ - [`src/ai.ts`](./src/ai.ts) builds the AI providers
8
+
9
+ ## Run it
10
+
11
+ Fill `.env` with your keys, then:
12
+
13
+ ```bash
14
+ {{run:dev}}
15
+ ```
16
+
17
+ The server listens on `ws://localhost:3001`.
18
+
19
+ ## Talk to it
20
+
21
+ Any Micdrop client connects to it. In a web page:
22
+
23
+ ```bash
24
+ npm install @micdrop/web
25
+ ```
26
+
27
+ ```ts
28
+ import { Micdrop } from '@micdrop/web'
29
+
30
+ await Micdrop.start({ url: 'ws://localhost:3001' })
31
+ Micdrop.on('StateChange', (state) => console.log(state.conversation))
32
+ ```
33
+
34
+ On iOS and Android, [`@micdrop/react-native`](https://micdrop.dev/docs/react-native)
35
+ takes the same options.
36
+
37
+ ## AI providers
38
+
39
+ {{providers}}
40
+
41
+ Swap any of them in `src/ai.ts`. The [providers page](https://micdrop.dev/docs/providers)
42
+ lists them all.
43
+
44
+ ## Learn more
45
+
46
+ - [Server documentation](https://micdrop.dev/docs/server)
47
+ - [Tools](https://micdrop.dev/docs/server/tools): let the assistant call your functions
48
+ - [Auth and parameters](https://micdrop.dev/docs/server/auth-and-parameters): check who connects
@@ -0,0 +1,6 @@
1
+ # Port of the WebSocket server
2
+ PORT=3001
3
+
4
+ # Logs of the calls: info shows each turn, debug each step of the
5
+ # providers. Warnings and errors only by default.
6
+ # MICDROP_LOG=info
@@ -0,0 +1,4 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "tsx watch --env-file=.env src/server.ts",
8
+ "start": "tsx --env-file=.env src/server.ts",
9
+ "typecheck": "tsc --noEmit"
10
+ },
11
+ "dependencies": {
12
+ "@micdrop/server": "*",
13
+ "ws": "^8.19.0"
14
+ },
15
+ "devDependencies": {
16
+ "@types/node": "^22.19.13",
17
+ "@types/ws": "^8.18.1",
18
+ "tsx": "^4.20.6",
19
+ "typescript": "^5.9.3"
20
+ }
21
+ }
@@ -0,0 +1,34 @@
1
+ // A voice agent on a WebSocket. Each connection is a call: Micdrop transcribes
2
+ // what the user says, has the agent answer and speaks the answer back.
3
+ // https://micdrop.dev/docs/server
4
+
5
+ import { endCallTool, MicdropServer } from '@micdrop/server'
6
+ import { WebSocketServer } from 'ws'
7
+ import { createAi } from './ai'
8
+
9
+ const PORT = Number(process.env.PORT || 3001)
10
+
11
+ const server = new WebSocketServer({ port: PORT })
12
+
13
+ server.on('connection', (socket) => {
14
+ const call = new MicdropServer(socket, {
15
+ // Spoken right away, before the user says anything
16
+ // https://micdrop.dev/docs/server/first-message
17
+ firstMessage: 'Hi! What can I do for you?',
18
+
19
+ // The providers picked when the project was created, in ai.ts
20
+ ...createAi({
21
+ systemPrompt:
22
+ 'You are a friendly assistant. Your answers are spoken out loud, so keep them short and conversational.',
23
+ // Lets the assistant hang up once the user says goodbye
24
+ // https://micdrop.dev/docs/server/auto-end-call
25
+ tools: [endCallTool()],
26
+ }),
27
+ })
28
+
29
+ call.on('End', ({ duration }) =>
30
+ console.log(`Call ended after ${duration} s`)
31
+ )
32
+ })
33
+
34
+ console.log(`Micdrop server listening on ws://localhost:${PORT}`)
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "noEmit": true
12
+ },
13
+ "include": ["src"]
14
+ }
@@ -0,0 +1,86 @@
1
+ # {{name}}
2
+
3
+ A phone number answered by a voice agent, built with
4
+ [Micdrop](https://micdrop.dev) on your own Node server. The telephony provider
5
+ streams each call to the server, which runs the AI and speaks back on the line.
6
+
7
+ - [`src/server.ts`](./src/server.ts) answers the webhooks and runs each call:
8
+ first message, tools, end of call report
9
+ - [`src/telephony.ts`](./src/telephony.ts) speaks to your telephony provider
10
+ - [`src/webhooks.ts`](./src/webhooks.ts) checks that each request comes from it
11
+ - [`src/ai.ts`](./src/ai.ts) builds the AI providers
12
+ - [`src/recording.ts`](./src/recording.ts) saves each call, when `RECORDINGS_DIR` is set
13
+
14
+ ## Run it
15
+
16
+ The provider needs to reach the server from the internet. In development, open
17
+ a tunnel, for instance:
18
+
19
+ ```bash
20
+ ngrok http 3001
21
+ ```
22
+
23
+ Fill `.env` with your keys and the host the tunnel gave you in `PUBLIC_HOST`,
24
+ then:
25
+
26
+ ```bash
27
+ {{run:dev}}
28
+ ```
29
+
30
+ ## Point your number to it
31
+
32
+ {{telephonySetup}}
33
+
34
+ Call the number and talk. Say goodbye, and the agent hangs up.
35
+
36
+ ## What the agent does
37
+
38
+ | Feature | Where |
39
+ | ----------------------------------------------------- | ---------------------------------------------------- |
40
+ | Greets the caller as soon as the call connects | `firstMessage` in `src/server.ts` |
41
+ | Hangs up once the caller says goodbye | `endCallTool()` |
42
+ | Transfers to a person, when `TRANSFER_NUMBER` is set | `transferCallTool()`, cold or warm |
43
+ | Hears the keys pressed on the keypad | `dtmfInput()` |
44
+ | Checks in when the caller stays silent, then hangs up | `idleTimeout()` |
45
+ | Places calls, when `OUTBOUND_API_KEY` is set | `POST /call` and `placeCall()` in `src/telephony.ts` |
46
+ | Leaves a message on a voicemail, on an outbound call | `answeringMachine()` |
47
+ | Presses keys in the phone menu it reaches, outbound | `sendDtmfTool()` |
48
+ | Refuses the webhooks your provider did not sign | `isSigned()` in `src/telephony.ts` |
49
+ | Saves the audio and the transcript | `src/recording.ts` |
50
+ | Reports the conversation once the call is over | the `End` event of the server |
51
+
52
+ Add your own tools next to them, such as a lookup in your database or a
53
+ booking in your calendar: the [tools documentation](https://micdrop.dev/docs/server/tools)
54
+ shows how.
55
+
56
+ To place a call, once `OUTBOUND_API_KEY` and `OUTBOUND_NUMBER` are set:
57
+
58
+ ```bash
59
+ curl -X POST https://<PUBLIC_HOST>/call \
60
+ -H "Authorization: Bearer <OUTBOUND_API_KEY>" \
61
+ -H "Content-Type: application/json" \
62
+ -d '{"to": "+14155550100"}'
63
+ ```
64
+
65
+ ## Coming from a hosted voice platform
66
+
67
+ The assistant, its tools, its first message and the end of call report all
68
+ live in `src/server.ts`, as code you version and test. The guide
69
+ [Migrate from Vapi](https://micdrop.dev/docs/migration/from-vapi) maps
70
+ each concept of Vapi to its place in this project.
71
+
72
+ ## Before production
73
+
74
+ - Keep `VERIFY_SIGNATURES=true`: the server then refuses the webhooks your
75
+ provider did not sign, and the stream of each call opens on a secret path
76
+ that only those webhooks reveal.
77
+ - Run the server where it keeps a WebSocket open for the whole call, close to
78
+ your provider's media region for the lowest latency.
79
+ - Tell your callers when they are recorded.
80
+
81
+ ## AI providers
82
+
83
+ {{providers}}
84
+
85
+ Swap any of them in `src/ai.ts`. The [providers page](https://micdrop.dev/docs/providers)
86
+ lists them all.
@@ -0,0 +1,31 @@
1
+ # Port of the server
2
+ PORT=3001
3
+
4
+ # Public host of this server, as the tunnel gives it (ngrok, cloudflared),
5
+ # without the protocol, such as abcd.ngrok.app. The webhook signatures cover
6
+ # it, so it has to be the host your provider calls.
7
+ PUBLIC_HOST=
8
+
9
+ # The server refuses the webhooks your provider did not sign. Set to false to
10
+ # try it out without the secrets of your account, never in production.
11
+ VERIFY_SIGNATURES=true
12
+
13
+ # Number the assistant transfers the caller to when they ask for a person,
14
+ # in E.164 format such as +14155550100. Leave empty to turn transfers off.
15
+ TRANSFER_NUMBER=
16
+ # cold (default) hands the call over at once, warm has the person hear a
17
+ # summary before the caller joins
18
+ TRANSFER_MODE=cold
19
+
20
+ # Outbound calls, with POST /call: the key that request carries, and the
21
+ # number of your account that calls. Leave empty to turn them off.
22
+ OUTBOUND_API_KEY=
23
+ OUTBOUND_NUMBER=
24
+
25
+ # Folder where each call is saved, audio and transcript. Leave empty to
26
+ # record nothing. Tell your callers they are recorded.
27
+ RECORDINGS_DIR=
28
+
29
+ # Logs of the calls: info shows each turn, debug each step of the
30
+ # providers. Warnings and errors only by default.
31
+ # MICDROP_LOG=info
@@ -0,0 +1,5 @@
1
+ node_modules
2
+ dist
3
+ recordings
4
+ .env
5
+ .DS_Store
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "tsx watch --env-file=.env src/server.ts",
8
+ "start": "tsx --env-file=.env src/server.ts",
9
+ "typecheck": "tsc --noEmit"
10
+ },
11
+ "dependencies": {
12
+ "@micdrop/server": "*",
13
+ "@micdrop/silero": "*",
14
+ "@micdrop/telephony": "*",
15
+ "onnxruntime-node": "^1.31.1",
16
+ "ws": "^8.19.0",
17
+ "zod": "^4.6.7"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "^22.19.13",
21
+ "@types/ws": "^8.18.1",
22
+ "tsx": "^4.20.6",
23
+ "typescript": "^5.9.3"
24
+ }
25
+ }
@@ -0,0 +1,65 @@
1
+ // Saves each call: one WAV file per message, and the transcript.
2
+ // Swap the writes for an upload to your storage to keep them elsewhere.
3
+ // https://micdrop.dev/docs/server/recording-audio
4
+
5
+ import { mkdir, writeFile } from 'node:fs/promises'
6
+ import path from 'node:path'
7
+ import { AudioMessage, MicdropRecorder, MicdropServer } from '@micdrop/server'
8
+ import { TelephonyTransport } from '@micdrop/telephony'
9
+
10
+ const RECORDINGS_DIR = process.env.RECORDINGS_DIR
11
+
12
+ export function recordCall(
13
+ server: MicdropServer,
14
+ transport: TelephonyTransport
15
+ ) {
16
+ if (!RECORDINGS_DIR) return
17
+ const callId = transport.call.callId ?? `call-${Date.now()}`
18
+ const dir = path.join(RECORDINGS_DIR, callId)
19
+ const recorder = new MicdropRecorder(server)
20
+
21
+ recorder.on('Complete', async (messages: AudioMessage[]) => {
22
+ try {
23
+ await mkdir(dir, { recursive: true })
24
+ for (const [index, message] of messages.entries()) {
25
+ const name = `${String(index).padStart(3, '0')}-${message.role}.wav`
26
+ await writeFile(
27
+ path.join(dir, name),
28
+ toWav(message.buffer, message.sampleRate)
29
+ )
30
+ }
31
+ const transcript = {
32
+ call: transport.call,
33
+ messages: messages.map(({ role, content }) => ({ role, content })),
34
+ }
35
+ await writeFile(
36
+ path.join(dir, 'transcript.json'),
37
+ JSON.stringify(transcript, null, 2)
38
+ )
39
+ console.log(`Call saved in ${dir}`)
40
+ } catch (error) {
41
+ console.error('Saving the call failed:', error)
42
+ } finally {
43
+ recorder.destroy()
44
+ }
45
+ })
46
+ }
47
+
48
+ /** Wraps PCM 16 bits mono in a WAV header */
49
+ function toWav(pcm: Buffer, sampleRate: number): Buffer {
50
+ const header = Buffer.alloc(44)
51
+ header.write('RIFF', 0)
52
+ header.writeUInt32LE(36 + pcm.length, 4)
53
+ header.write('WAVE', 8)
54
+ header.write('fmt ', 12)
55
+ header.writeUInt32LE(16, 16) // Size of the format chunk
56
+ header.writeUInt16LE(1, 20) // PCM
57
+ header.writeUInt16LE(1, 22) // Mono
58
+ header.writeUInt32LE(sampleRate, 24)
59
+ header.writeUInt32LE(sampleRate * 2, 28) // Bytes per second
60
+ header.writeUInt16LE(2, 32) // Bytes per sample
61
+ header.writeUInt16LE(16, 34) // Bits per sample
62
+ header.write('data', 36)
63
+ header.writeUInt32LE(pcm.length, 40)
64
+ return Buffer.concat([header, pcm])
65
+ }
@@ -0,0 +1,212 @@
1
+ // A phone number answered by a voice agent, which can also place calls.
2
+ // The telephony provider calls a webhook when a call comes in, the server
3
+ // answers with a document that streams the call to a WebSocket of this server,
4
+ // and a telephony transport runs the call there with Micdrop.
5
+ // https://micdrop.dev/docs/transports/telephony
6
+
7
+ import { createServer } from 'node:http'
8
+ import {
9
+ dtmfInput,
10
+ endCallTool,
11
+ idleTimeout,
12
+ MicdropServer,
13
+ Tool,
14
+ waitForParams,
15
+ } from '@micdrop/server'
16
+ import {
17
+ answeringMachine,
18
+ sendDtmfTool,
19
+ TelephonyTransport,
20
+ transferCallTool,
21
+ } from '@micdrop/telephony'
22
+ // Loads Silero, which finds the turns of the caller on the server
23
+ import '@micdrop/silero/node'
24
+ import { WebSocketServer } from 'ws'
25
+ import { createAi } from './ai'
26
+ import { recordCall } from './recording'
27
+ import * as telephony from './telephony'
28
+ import { verifySignatures } from './webhooks'
29
+
30
+ const env = process.env
31
+ const PORT = Number(env.PORT || 3001)
32
+ const host = env.PUBLIC_HOST || `localhost:${PORT}`
33
+
34
+ const SYSTEM_PROMPT = `You answer the phone for a small company.
35
+ Your answers are spoken on a phone line, so keep them short and conversational.
36
+ When the caller says goodbye, end the call.`
37
+
38
+ /** Functions the assistant can call during the call */
39
+ function createTools(outbound: boolean): Tool[] {
40
+ // https://micdrop.dev/docs/server/tools
41
+ const tools: Tool[] = [
42
+ // Hangs up once the goodbye has played
43
+ // https://micdrop.dev/docs/server/auto-end-call
44
+ endCallTool(),
45
+ ]
46
+ // Sends the caller to a person, once the announcement has played
47
+ // https://micdrop.dev/docs/transports/call-transfer
48
+ if (env.TRANSFER_NUMBER && telephony.canUseApi) {
49
+ tools.push(
50
+ transferCallTool({
51
+ to: env.TRANSFER_NUMBER,
52
+ mode: env.TRANSFER_MODE === 'warm' ? 'warm' : 'cold',
53
+ })
54
+ )
55
+ }
56
+ // Calling a company, the assistant may meet its phone menu
57
+ if (outbound) tools.push(sendDtmfTool())
58
+ return tools
59
+ }
60
+
61
+ /** Runs a call once the provider opened its stream */
62
+ async function runCall(transport: TelephonyTransport) {
63
+ const params = await waitForParams(transport, (value) => value)
64
+ const outbound =
65
+ transport.call.direction === 'outbound' || params.direction === 'outbound'
66
+ console.log('Call started', transport.call, params)
67
+
68
+ const tools = createTools(outbound)
69
+ const transfers = tools.some((tool) => tool.name === 'transfer_call')
70
+ const server = new MicdropServer(transport, {
71
+ // A phone line has no client to find the turns, the server does it
72
+ // https://micdrop.dev/docs/server/vad
73
+ turns: { vad: 'silero' },
74
+
75
+ // Spoken as soon as the call connects
76
+ // https://micdrop.dev/docs/server/first-message
77
+ firstMessage: outbound
78
+ ? 'Hello, this is the assistant of Acme calling. Do you have a minute?'
79
+ : 'Hello, thanks for calling. How can I help you?',
80
+
81
+ // The providers picked when the project was created, in ai.ts
82
+ ...createAi({
83
+ systemPrompt: transfers
84
+ ? `${SYSTEM_PROMPT}\nWhen the caller asks for a person, transfer the call.`
85
+ : SYSTEM_PROMPT,
86
+ tools,
87
+ }),
88
+ })
89
+
90
+ // Keys pressed on the keypad become what the caller said
91
+ // https://micdrop.dev/docs/transports/phone-keypad
92
+ dtmfInput(server)
93
+
94
+ // "Are you still there?" after 10 s of silence, then goodbye
95
+ idleTimeout(server, { timeout: 10000 })
96
+
97
+ // A voicemail that picks up an outbound call gets a message, then the call
98
+ // ends
99
+ if (outbound) {
100
+ answeringMachine(server, {
101
+ message: 'Hi, this is Acme. Please call us back. Goodbye!',
102
+ })
103
+ }
104
+
105
+ // Saves the call, audio and transcript, when RECORDINGS_DIR is set
106
+ recordCall(server, transport)
107
+
108
+ // The report of the call, once it is over: store it, send it to your CRM
109
+ server.on('End', ({ conversation, duration }) => {
110
+ console.log(`Call ended after ${duration} s`)
111
+ for (const item of conversation) {
112
+ if (item.role === 'user' || item.role === 'assistant') {
113
+ console.log(` ${item.role}: ${item.content}`)
114
+ }
115
+ }
116
+ })
117
+ }
118
+
119
+ /**
120
+ * Places a call: `POST /call` with `{ "to": "+14155550100" }` and the header
121
+ * `Authorization: Bearer <OUTBOUND_API_KEY>`
122
+ */
123
+ async function placeCall(authorization: string | undefined, body: string) {
124
+ if (!env.OUTBOUND_API_KEY || !env.OUTBOUND_NUMBER || !telephony.placeCall) {
125
+ return { status: 404 }
126
+ }
127
+ if (authorization !== `Bearer ${env.OUTBOUND_API_KEY}`) {
128
+ return { status: 401 }
129
+ }
130
+ const { to } = JSON.parse(body || '{}')
131
+ if (typeof to !== 'string' || !/^\+[1-9]\d{5,14}$/.test(to)) {
132
+ return { status: 400, body: { error: 'to: a number in E.164 format' } }
133
+ }
134
+ const call = await telephony.placeCall({
135
+ to,
136
+ from: env.OUTBOUND_NUMBER,
137
+ host,
138
+ })
139
+ return { status: 200, body: call }
140
+ }
141
+
142
+ const http = createServer(async (request, response) => {
143
+ try {
144
+ const href = `https://${host}${request.url ?? '/'}`
145
+ const url = new URL(href)
146
+ // Kept as received, since the signature covers it
147
+ const chunks: Buffer[] = []
148
+ for await (const chunk of request) chunks.push(chunk)
149
+ const body = Buffer.concat(chunks).toString()
150
+
151
+ if (url.pathname === '/call' && request.method === 'POST') {
152
+ const result = await placeCall(request.headers.authorization, body)
153
+ response.writeHead(result.status, { 'Content-Type': 'application/json' })
154
+ response.end(JSON.stringify(result.body ?? {}))
155
+ return
156
+ }
157
+
158
+ const webhook = telephony.webhooks[url.pathname]
159
+ if (!webhook) {
160
+ response.writeHead(404).end()
161
+ return
162
+ }
163
+ const webhookRequest = {
164
+ url,
165
+ href,
166
+ method: request.method ?? 'GET',
167
+ headers: request.headers,
168
+ body,
169
+ }
170
+ if (verifySignatures && !telephony.isSigned(webhookRequest)) {
171
+ console.warn(
172
+ `Refused ${url.pathname}: its signature does not match. Check that PUBLIC_HOST is the host ${telephony.provider} calls.`
173
+ )
174
+ response.writeHead(telephony.refusedStatus).end()
175
+ return
176
+ }
177
+ const answer = await webhook(webhookRequest)
178
+ if (!answer) {
179
+ response.writeHead(204).end()
180
+ return
181
+ }
182
+ response.writeHead(200, { 'Content-Type': answer.contentType })
183
+ response.end(answer.body)
184
+ } catch (error) {
185
+ console.error(error)
186
+ if (!response.headersSent) response.writeHead(500).end()
187
+ }
188
+ })
189
+
190
+ // The WebSocket the provider streams each call to
191
+ const wss = new WebSocketServer({ noServer: true })
192
+ http.on('upgrade', (request, socket, head) => {
193
+ const { pathname } = new URL(request.url ?? '/', 'ws://localhost')
194
+ if (pathname !== telephony.streamPath) return socket.destroy()
195
+ wss.handleUpgrade(request, socket, head, (ws) => {
196
+ runCall(telephony.createTransport(ws)).catch((error) => {
197
+ console.error(error)
198
+ ws.close(1011)
199
+ })
200
+ })
201
+ })
202
+
203
+ http.listen(PORT, () => {
204
+ console.log(`Phone agent listening on http://localhost:${PORT}`)
205
+ console.log(`${telephony.provider} reaches it at https://${host}`)
206
+ for (const path of Object.keys(telephony.webhooks)) {
207
+ console.log(` webhook https://${host}${path}`)
208
+ }
209
+ if (!verifySignatures) {
210
+ console.warn('Webhook signatures are not checked (VERIFY_SIGNATURES=false)')
211
+ }
212
+ })