TypeScript library for Asterisk AGI (Asterisk Gateway Interface) with production-ready improvements
Mono Bilişim's fork of typescript-agi-ipcom, which itself extends Brandon Lehmann's typescript-agi with reliability and functionality enhancements for production environments.
- Production-Ready FIFO Command Queue: Eliminates race conditions through sequential command processing
- Intelligent Timeout System: Context-aware timeouts (10 seconds to 6 hours) based on command type
- Inter-Digit Timeout Support: Enhanced
getData()with configurable delays between digit inputs - Queue Management APIs: Monitor and control command queue with
getQueueStats()andclearCommandQueue() - Comprehensive Event System: New events for command lifecycle tracking
- Backpressure Control: Configurable queue limits (default: 100 commands) prevent memory exhaustion
- Channel Lifecycle Management:
channelAliveflag ensures proper connection state tracking - AMI Client: Place calls (
Originate), send any manager action and receive events over the Asterisk Manager Interface - TypeScript Support: Full type definitions with ESM and CommonJS outputs
This package is not published to npm. Each v* tag builds a GitHub release with
the packed tarball attached; install it from there:
bun add https://github.com/monobilisim/typescript-agi/releases/download/v1.1.0/monobilisim-typescript-agi-1.1.0.tgzimport { AGIServer, Channel } from '@monobilisim/typescript-agi';
const agiServer = new AGIServer(3000, '0.0.0.0');
agiServer.on('channel', async (channel: Channel) => {
try {
await channel.answer();
await channel.sayNumber(12345);
await channel.hangup();
} catch (error) {
console.error('Error handling channel:', error);
}
});
agiServer.start();AGI only runs on a call that is already up. To start one from code, log in to
the Asterisk Manager Interface (AMI) with AMIClient and originate the call
into AGI; Asterisk connects back to the AGIServer once it is answered.
import { AGIServer, AMIClient, Channel } from '@monobilisim/typescript-agi';
const agiServer = new AGIServer(4573, '0.0.0.0');
agiServer.on('channel', async (channel: Channel) => {
await channel.answer();
await channel.sayNumber(1453);
await channel.hangup();
});
await agiServer.start();
const ami = new AMIClient({
host: '10.0.0.5', // Asterisk / FreePBX
username: 'app',
secret: process.env.AMI_SECRET!,
});
await ami.connect();
const result = await ami.originate({
// FreePBX: Local/<number>@from-internal dials through the outbound routes
channel: 'Local/905551112233@from-internal',
application: 'AGI',
data: `agi://${ami.localAddress}:4573`, // this machine, as Asterisk sees it
timeout: 30000, // ring for 30 seconds
});
if (!result.answered) {
console.log(`Not answered, reason ${result.reason}`); // see OriginateReason
}
await ami.close();The manager user needs write permission originate and read permission
call. Asterisk additionally requires write permission system to originate
into an application such as AGI; to avoid granting it, originate into a
dialplan location (context, exten, priority) that runs AGI() instead.
Allow the manager port (5038) only from the machines that run the client.
ami.action(name, fields) sends any other manager action and resolves with
its response; ami.on('event', …) receives the events the manager user may
read.
Collect multi-digit input with configurable inter-digit timeout:
agiServer.on('channel', async (channel: Channel) => {
await channel.answer();
// Collect up to 4 digits with 3-second timeout between digits
// Total timeout: 10 seconds after audio finishes
const result = await channel.getData(
'enter-account-number', // audio file
10000, // total timeout (10s)
4, // max digits
3000 // inter-digit timeout (3s)
);
if (result.timeout) {
await channel.streamFile('timeout');
} else {
await channel.verbose(`Collected: ${result.digits}`);
}
});Override default timeouts for long-running operations:
// Execute Dial with custom 2-hour timeout
await channel.exec(
'Dial',
'PJSIP/user@trunk,3600,tT',
7200000 // 2 hours in milliseconds
);
// Use Infinity for no timeout (relies on channelAlive flag)
await channel.exec('Queue', 'support,,,,,', Infinity);Monitor command queue health in real-time:
channel.on('commandQueued', ({ command, queueSize }) => {
console.log(`Queued: ${command}, Queue size: ${queueSize}`);
});
channel.on('commandProcessed', ({ command, duration }) => {
console.log(`Processed: ${command} in ${duration}ms`);
});
channel.on('commandFailed', ({ command, error }) => {
console.error(`Failed: ${command}`, error);
});
// Get current queue statistics
const stats = channel.getQueueStats();
console.log(`Queue: ${stats.size}, Processing: ${stats.isProcessing}`);Commands automatically use appropriate timeouts based on their type:
| Command Type | Default Timeout | Examples |
|---|---|---|
| Fast commands | 10 seconds | ANSWER, HANGUP, GET/SET VARIABLE, DATABASE |
| Audio commands | 60 seconds | STREAM FILE, SAY, GET DATA, GET OPTION |
| Recording | 10 minutes | RECORD FILE |
| Call control | 6 hours | EXEC (Dial, Queue, VoiceMail) |
You can override any timeout by passing a custom value to methods that support it.
channel: New channel ready for interactionlistening: Server started successfullyerror: Server error occurredclose: Server stopped
event: An AMI event (every message with anEventheader)close: Connection closed, by either sideerror: Connection error (only emitted while a listener is attached)
Standard events:
ready: Channel initialized and ready for commandssend: Data sent to Asteriskrecv: Raw response received from Asteriskresponse: Parsed response objecthangup: Call hung upclose: Socket closederror: Socket errortimeout: Socket timeout
Queue management events:
commandQueued: Command added to queuecommandProcessed: Command completed successfullycommandFailed: Command execution failedqueueEmpty: All commands processedqueueCleared: Queue manually or automatically cleared
Generate the TypeDoc HTML documentation into docs/ with:
bun run docs- AGIServer: TCP server that listens for AGI connections from Asterisk
- AMIClient: Asterisk Manager Interface connection: login, actions, events and
originate() - OriginateReason: Enum for how an originated call ended (ANSWERED, BUSY, NO_ANSWER, etc.)
- Channel: Represents an active AGI channel with full protocol support
- ChannelState: Enum for channel states (DOWN_AVAILABLE, OFF_HOOK, UP, etc.)
- DialStatus: Enum for Dial() results (ANSWER, BUSY, NOANSWER, etc.)
- PlaybackStatus: Enum for playback results (SUCCESS, USER_STOPPED, etc.)
This fork includes the following enhancements:
-
FIFO Command Queue: Original had race condition issues with concurrent commands receiving wrong responses. Now uses sequential queue processing.
-
Intelligent Timeouts: Original used fixed 10-second timeout for all commands. Now uses context-aware timeouts (10s - 6 hours) based on command type.
-
Inter-Digit Timeout: Original
getData()couldn't handle digit-by-digit collection with delays. New implementation supports configurable inter-digit timeouts. -
Production Reliability:
- Backpressure control (queue size limits)
- Channel lifecycle tracking (
channelAliveflag) - Proper cleanup on hangup/close
- Comprehensive error handling
-
Queue Management: New APIs for monitoring and controlling the command queue (
getQueueStats(),clearCommandQueue()). -
Enhanced Events: Additional events for command lifecycle tracking and queue management.
# Install dependencies
bun install
# Build ESM, CommonJS and type definitions into dist/
bun run build
# Run the tests
bun run test
# Generate the TypeDoc documentation into docs/
bun run docs
# Type check, format
bun run check
bun fmttests/ uses bun test and drives the library only through its public entry
point (@monobilisim/typescript-agi), the way an application would. A fake
Asterisk in tests/support/asterisk.ts connects to a real AGIServer over
loopback TCP, sends the agi_* environment and answers each command like
Asterisk does.
-
Bump
versioninpackage.jsonand commit. -
Tag the commit with the same version and push the tag:
git tag v1.0.1 git push origin v1.0.1
The Release workflow checks that the tag matches package.json, builds the
package, packs it with bun pm pack and attaches the tarball to a GitHub
release.
Issues and feature requests are welcome on the issues page.
Current Maintainer:
- Mono Bilişim
- GitHub: @monobilisim
Previous Maintainer:
- Fabio Theodoro fabio@ipcom.com.br
- GitHub: @ipcomtelecom
- Company: IPCOM
Original Author:
- Brandon Lehmann brandonlehmann@gmail.com
- GitHub: @brandonlehmann
- Original project: typescript-agi
Copyright 2020 Brandon Lehmann (original work) Copyright 2025 Fabio Theodoro / IPCOM (enhancements) Copyright 2026 Mono Bilişim
This project is MIT licensed.
Forked from ipcomtelecom/typescript-agi-ipcom.