Semua artikel

How Do You Build a Browser Calling Desk for a 10-SIM GSM Gateway with Asterisk and Next.js?

Asterisk owns the calls, a Next.js portal owns the desk: number rules, SIM hunt, a live channel board and AMI, read from the Agent Line code and tests.

Muhammad Afzal Kalwar (Open-Source)10 min read0 kali dilihat
How Do You Build a Browser Calling Desk for a 10-SIM GSM Gateway with Asterisk and Next.js?

Short answer

Let Asterisk own every call, and let a small web app own everything around the call. In Agent Line, Asterisk runs in Docker with one ringall queue, each agent's browser registers as a SIP.js phone over WebSocket, and a Next.js portal talks to Asterisk through the Manager Interface (AMI). The portal never touches the audio. What it does own is the part that goes wrong in a real office: normalising Pakistani numbers, picking which of ten SIMs places a call, remembering which channel is busy, and popping up the customer.

This post walks through those pieces as they appear in the code, with the exact inputs and outputs the tests expect. There are no performance numbers here, because the repository doesn't contain any.

What problem is this solving?

A Pakistani ecommerce brand answers and places customer calls from one office. Seven to ten agents share the work. The voice path is a 10-SIM GSM gateway on the office LAN: each SIM is one channel and one real mobile number. The brand needs a shared queue, a phone in the browser, a customer card, and a record of which SIM carried each call. The desk also had to be usable before the gateway hardware arrived, so a simulated trunk is part of the design.

Agent Line is that desk. It is a TypeScript Next.js app with SQLite, MIT-licensed, version 0.1.0. It is local only: there is no public homepage, and the PBX stays on the office machine.

How are the two processes split?

Browser (SIP.js)  --WSS-->  Asterisk (Docker)  <--SIP-->  GSM gateway / simulate trunk
        ^                         ^
        |  HTTP + SSE             |  AMI (TCP)
        +------  Next.js portal --+

Per docs/ARCHITECTURE.md:

  • Asterisk has PJSIP WebRTC endpoints for agents, one queue named brand with strategy=ringall, a simulate trunk and a gateway trunk.
  • The Next.js portal runs as one Node process. It serves the UI, a JSON API and a server-sent event stream, and it talks to Asterisk over AMI. It does not parse or generate SIP.
  • Sign-in sets an HMAC cookie signed with SESSION_SECRET. The agent page then loads the agent's SIP credentials and SIP.js registers PJSIP/<username>.

The relevant lines of the queue config (asterisk/conf/queues.conf):

[brand]
strategy=ringall
timeout=30
retry=2
wrapuptime=0
ringinuse=no
joinempty=yes
leavewhenempty=no

ringall plus ringinuse=no means an inbound call rings every agent who is not already on a call, and the first answer takes it. The portal learns who answered from the AMI AgentConnect event, and the other agents see that channel turn busy.

How do you normalise Pakistani phone numbers?

The same number reaches the desk as 03001234567, 923001234567, +92 300-1234567 or 3001234567. Customers are stored one way and dialled another: stored as +92…, sent to the gateway with a leading 0. lib/numbers.ts does that in one function, and international numbers need an explicit confirmation:

export function parseNumber(input: string): ParsedNumber {
  const compact = input.trim().replace(/[\s().-]/g, "");
  if (!compact) return empty;
  const digits = compact.replace(/\D/g, "");
  if (!digits) return empty;

  if (compact.startsWith("00")) {
    const gateway = `00${digits.slice(2)}`;
    return { kind: "international", stored: gateway, gateway, needsConfirm: true };
  }
  if (compact.startsWith("+") && !compact.startsWith("+92")) {
    const gateway = `00${digits}`;
    return { kind: "international", stored: gateway, gateway, needsConfirm: true };
  }
  if (!compact.startsWith("+") && digits.length >= 3 && digits.length <= 6) {
    return { kind: "short", stored: digits, gateway: digits, needsConfirm: false };
  }

  let nsn = "";
  if (compact.startsWith("+92")) nsn = digits.slice(2);
  else if (digits.startsWith("92") && digits.length >= 12) nsn = digits.slice(2);
  else if (digits.startsWith("0")) nsn = digits.slice(1);
  else if (digits.startsWith("3") && digits.length === 10) nsn = digits;
  else return empty;

  nsn = nsn.replace(/^0+/, "");
  if (nsn.length < 8 || nsn.length > 12) return empty;
  return { kind: "pakistani", stored: `+92${nsn}`, gateway: `0${nsn}`, needsConfirm: false };
}

Running it on a few inputs gives:

| Input | kind | stored | gateway | needsConfirm | |---|---|---|---|---| | +923001234567 | pakistani | +923001234567 | 03001234567 | false | | 03001234567 | pakistani | +923001234567 | 03001234567 | false | | 3001234567 | pakistani | +923001234567 | 03001234567 | false | | +9203001234567 (typed trunk 0) | pakistani | +923001234567 | 03001234567 | false | | 121 | short | 121 | 121 | false | | 00441234567890 | international | 00441234567890 | 00441234567890 | true | | +441234567890 | international | 00441234567890 | 00441234567890 | true | | two spaces | invalid | empty | empty | false |

Two design choices are worth copying. First, the stored form is canonical, so a customer lookup on an incoming caller ID is an equality check: findCustomerByCaller parses both sides and compares stored. The tests check that 03…, 92… and +92… find the same customer and that an unknown number finds nothing. Second, an international number is never dialled silently. The API answers "confirm first" and the button waits for a second click.

How do you choose which of ten SIMs places the call?

Each SIM is a channel with a slot, a number, a dial prefix, a primary flag and a busy flag. The pure function that picks one is four lines:

export function huntSim(channels: HuntChannel[]): HuntChannel | null {
  const free = channels.filter((channel) => !channel.busy).sort((a, b) => a.slot - b.slot);
  return free.find((channel) => channel.isPrimary) ?? free.find((channel) => !channel.isPrimary) ?? null;
}

Primary SIM if it is free, otherwise the lowest-numbered free SIM, otherwise nothing. The tests cover exactly those branches: primary free, primary busy so the next slot wins, a busy alternate that gets skipped, and all channels busy returning null.

One honest detail: planOutbound accepts an optional ownSlot. When an agent has a SIM slot assigned by the admin, placeCall passes that slot and the call goes out on that agent's own line, or fails with "Your line is busy". The primary-first hunt is the path for an agent with no fixed slot. Keeping both in one pure function means the policy can change without touching the Asterisk side.

When there is no free line, planOutbound returns a lines_full failure. The HTTP layer maps that to a 409, and the call button waits instead of placing a call that cannot connect.

How does the dial string reach the gateway?

buildDial turns the chosen SIM and the parsed number into an Asterisk target and a caller ID:

export function buildDial(mode: TrunkMode, sim: HuntChannel, gatewayNumber: string): DialPlan {
  const callerId = nationalCallerId(sim.e164);
  if (mode === "simulate") return { target: "Local/s@simulate-trunk", callerId };
  // ... a third mode for a handset bridge, not covered in this post ...
  return { target: `PJSIP/${sim.dialPrefix}${gatewayNumber}@gateway`, callerId };
}

The unit test for the gateway mode pins the result: a +923009998877 customer on the primary SIM becomes PJSIP/1*03009998877@gateway with caller ID 03001111111. When the primary is busy, the next call becomes PJSIP/2*03009998877@gateway with that SIM's number as caller ID.

That 1* and 2* is the gateway's per-channel prefix, stored on each SIM row. The simulate trunk ignores it and just answers, which is what lets the agent screens, the queue and the history rows work before any hardware exists. Switching TRUNK_MODE from simulate to gateway changes only the dial string. The README is also explicit about caller ID: it is the SIM the gateway used, and the project does not replace or spoof it.

How does the live board stay correct?

The board of ten channels is a reducer, the same pattern you would use in a front-end store:

export type BoardEvent =
  | { type: "sims"; sims: Pick<BoardChannel, "slot" | "e164" | "dialPrefix" | "isPrimary">[] }
  | { type: "ringing"; slot: number; remoteNumber: string; direction: "inbound" | "outbound"; callId: number }
  | { type: "answered"; slot: number; agentName: string; agentUsername: string }
  | { type: "idle"; slot: number };

reduceBoard(state, event) returns a new array: ringing marks a channel and records the remote number and call ID, answered marks it busy with the agent's name, idle clears everything. toHuntChannels then derives busy: state !== "idle" for the hunt. The test walks one channel through ringing, answered and idle and checks that channel 1 stays idle throughout.

The board is held in the portal's memory and updated by AMI events. The architecture notes say so directly: it is not the system of record. SQLite keeps the durable rows (users, sims, customers, calls, settings).

There is a small concurrency point here. In placeCall, the plan, the call row insert and the ringing board update all run before the first await, and the database calls are synchronous. In a single Node process that means two clicks cannot both plan the same free SIM. It only holds because the portal is one process on one machine, which is what the project is. A second portal process would need a real lock.

How does the portal talk to Asterisk?

lib/ami.ts is a small AMI client rather than a dependency. It parses frames split on blank lines, formats actions, logs in when it sees the banner, matches responses to actions by ActionID, rejects pending actions when the socket closes, and reconnects after three seconds. Events such as AgentConnect, OriginateResponse, Newstate and Hangup are emitted to the runtime, which updates the board and the calls table and pushes the change to every browser on the event stream. Outbound calls are placed by an AMI Originate into the click-to-call context, which dials the target and keeps the chosen SIM as caller ID.

What do the tests actually cover?

npm test runs Vitest. The suites in the repository cover number parsing, the SIM hunt, outbound planning (including the exact gateway dial strings above), customer lookup in memory and in a real SQLite file, the board reducer, the AMI frame parser and call statistics. They do not exercise a real GSM gateway or a real browser-to-browser call. The project status file lists the live two-browser trial as an open follow-up, and I would not call the desk field-proven until that is done.

FAQ

What is Agent Line?

A local multi-agent calling desk for a Pakistani ecommerce brand. Seven to ten agents answer from the browser on one Asterisk queue, and voice goes through a 10-SIM GSM gateway on the office LAN.

Why not put the SIP stack inside the Next.js app?

Calls are Asterisk's job. The PRD lists "a SIP stack inside the portal" as a non-goal. Keeping SIP in Asterisk means the portal can restart without dropping calls, and the portal only needs AMI events and actions.

How does an inbound call find the customer?

Asterisk reports the caller number on AgentConnect. The portal parses it with the same parseNumber, finds the customer whose stored number matches, and pushes a screen pop on the event stream. An unknown number can be saved from the call screen.

How do you test the desk before the gateway arrives?

With the simulate trunk. A simulated inbound call enters the same queue, rings every free agent, and one answer makes the channel busy for everyone else. Outbound click-to-call dials Local/s@simulate-trunk. The agent screens do not change when the trunk mode does.

Does Agent Line spoof caller ID?

No. The README and PRD say the caller ID the customer sees is the SIM that the gateway used.

What stack does it use?

TypeScript, Next.js, SQLite (through better-sqlite3 and Drizzle), SIP.js in the browser, and Asterisk in Docker. The repository is github.com/mafzalkalwardev/agent-line.


I'm Muhammad Afzal Kalwar, a Rust and Python automation engineer and founder of INDUS Web Agency in Islamabad. Code: github.com/mafzalkalwardev/agent-line.


Sumber artikel open-source oleh Muhammad Afzal Kalwar di DEV Community — Baca artikel asli. Topik: #typescript #nextjs #asterisk #voip

Sukai & bagikan artikel ini

Ditulis & Dikurasi Oleh

Muhammad Afzal Kalwar (Open-Source)

Software Engineer yang berfokus pada Next.js, TypeScript, arsitektur backend skalabel, Cloud, dan Applied AI.

Semua artikel

Komentar