# Build Pivot Applications

Source: https://docs.qvoice.net/api/pivot-apps/

Pivot lets your own HTTP application decide, during a live call, what the call does next.
QVOICE Platform sends the call data to your URL, waits for your answer and runs the callflow you
return.

The **`fonouc_callcontrol`** SDK (Python) is the starting point for building one. Its repository is
written to be read by an AI coding agent: point the agent at it, describe the call logic you want, and
it has the request fields, the response format, the builders and a working sample app in one place.

- Repository: [bitbucket.org/fonouc/fonouc\_callcontrol](https://bitbucket.org/fonouc/fonouc_callcontrol)
- Clone: `git clone git@ssh.bitbucket.org:fonouc/fonouc_callcontrol.git`
- Customer-facing reference for the Pivot action itself: [Callflow Webhook and Pivot](https://docs.qvoice.net/api/callflow-webhook-pivot/)

## How a Pivot Call Works

```mermaid
sequenceDiagram
    participant C as Caller
    participant P as Platform callflow
    participant A as Your pivot app
    C->>P: Call reaches the Pivot action
    P->>A: POST voice_url (Call-ID, Account-ID, Caller-ID-Number, ...)
    A->>A: PivotRequest.from_dict(form) and CallSession logic
    A-->>P: HTTP 200 JSON: callflow tree, or {} to continue
    P->>C: Runs the returned callflow (route, play, collect digits, ...)
    Note over P,A: A returned pivot action calls your app again,<br/>with the collected Digits
```

1. A callflow reaches a `pivot` action.
2. The platform sends the call data to `voice_url` (form fields or JSON).
3. Your app parses it, decides, and answers HTTP `200` with a callflow tree.
4. The platform validates the tree and runs it in place of the rest of the call.

## What the SDK Gives You

| Layer | What it does | Network I/O |
| --- | --- | --- |
| Core (`PivotRequest`, `CallSession`, `CallflowBuilder`, `PivotResponse`) | Parse the pivot request, build the callflow JSON response, build KAPI command payloads | None. Pure Python, standard library only |
| `crossbar` extra (`FonoUCrossbarClient`) | Look up users, channels and other platform data over the REST API | Yes, opt-in |
| `transport` extra (`AmqpPublisher`, `resolve_routing_key`) | Publish mid-call KAPI commands to RabbitMQ | Yes, opt-in |
| `examples` extra | FastAPI and Flask sample apps, `.env` loading | Yes |

Your application owns the HTTP server and every connection. The SDK never opens one unless you install
and call an optional extra.

## Quick Start: the Noop App

The sample app prints every pivot request and answers `{}`, so the call continues unchanged. Use it to
confirm the platform reaches your server before you write any logic.

```
git clone git@ssh.bitbucket.org:fonouc/fonouc_callcontrol.git
cd fonouc_callcontrol
./scripts/setup_venv.sh          # creates .venv/ and .env; nothing goes into system Python
./scripts/run_sample_fastapi.sh  # Listening on http://127.0.0.1:1999/pivot
```

`.env` sets where the sample listens:

```
PIVOT_LISTEN_HOST=127.0.0.1
PIVOT_LISTEN_PORT=1999
APP_NAME=sample_pivot_app
APP_VERSION=1.0
```

Test it without a call:

```
curl -s -X POST http://127.0.0.1:1999/pivot \
  -d "Call-ID=test-uuid-1" -d "Account-ID=acct123" \
  -d "Request=1001" -d "From=15551234567" -d "To=1002"
## {}
curl -s http://127.0.0.1:1999/health
```

A Flask version of the same app is `examples/sample_pivot_app.py`.

### Point a Callflow at the App

Add a `pivot` action to a test callflow. Use a host the platform can reach, not `127.0.0.1`, unless
the app runs on the platform server itself.

```
{
  "module": "pivot",
  "data": {
    "voice_url": "http://your-app-host:1999/pivot",
    "method": "post",
    "req_format": "kazoo",
    "req_body_format": "form"
  }
}
```

Call the callflow. The app terminal prints the request; the call carries on.

## Write Your Own Handler

```
from fonouc_callcontrol import CallSession, PivotRequest

def handle_pivot(form: dict) -> dict:
    pivot = PivotRequest.from_dict(form)
    session = CallSession.from_pivot(pivot)

    if pivot.caller_id_number == "15551234567":
        return session.route_pstn("+15145551234").to_dict()
    return session.noop().to_dict()
```

Return the dict as the HTTP `200` JSON body.

### Request Fields

`PivotRequest.from_dict()` reads the fields the platform sends. The main ones:

| Field | Attribute | Meaning |
| --- | --- | --- |
| `Call-ID` | `call_id` | Unique ID of the call (channel UUID) |
| `Account-ID` | `account_id` | Account that owns the call |
| `Request` | `request` | Dialed number |
| `Caller-ID-Name`, `Caller-ID-Number` | `caller_id_name`, `caller_id_number` | Who is calling |
| `Digits[<collection_name>]` | `digits` | Digits collected by an earlier `collect_dtmf` |
| `Custom-Channel-Vars` | `custom_channel_vars` | Channel variables on the call |
| `From`, `To`, `User-ID`, `Direction`, `Call-Status`, `Custom-SIP-Headers`, `Custom-Application-Vars` |  | See `docs/fonouc/PIVOT_REQUEST_FIELDS.md` in the repo |

### Responses

| Method | Callflow action returned | Use |
| --- | --- | --- |
| `noop()` | `{}` | Continue the callflow without a change |
| `route_pstn(number, ...)` | `resources` | Dial an external number |
| `route_extension(user_id, ...)` | `user` | Ring a user's devices |
| `route_device(device_id)` | `device` | Ring one device |
| `route_callflow(callflow_id)` | `callflow` | Jump to another callflow |
| `join_conference_flow(conference_id)` | `conference` | Join a conference |
| `hangup_flow()` | `hangup` | End the call |
| `respond(code, message)` | `response` | Answer with a SIP response code |
| `set_caller_id(...)`, `play(media_id)`, `collect_dtmf(...)`, `pivot(voice_url)` | `set_cid`, `play`, `collect_dtmf`, `pivot` | Chainable: finish with `.build()` or `.then(child)` |

Chain actions with `then()`. For example, play a prompt and hang up:

```
from fonouc_callcontrol.callflow_builder import CallflowBuilder

return session.play(media_id).then(CallflowBuilder.root("hangup")).to_dict()
```

### A Simple IVR: Collect Digits, Then Decide

Collect a digit, then call your app again with the digits in the next request:

```
from fonouc_callcontrol import CallSession, PivotRequest
from fonouc_callcontrol.callflow_builder import CallflowBuilder

def handle_pivot(form: dict) -> dict:
    pivot = PivotRequest.from_dict(form)
    session = CallSession.from_pivot(pivot)

    if not pivot.digits:
        return (
            session.collect_dtmf(collection_name="menu", max_digits=1)
            .then(CallflowBuilder.root("pivot", {
                "voice_url": "http://your-app-host:1999/pivot",
                "method": "post",
                "req_format": "kazoo",
                "req_body_format": "form",
            }))
            .to_dict()
        )
    if pivot.digits.get("menu") == "1":
        return session.route_callflow(SALES_CALLFLOW_ID).to_dict()
    return session.route_callflow(SUPPORT_CALLFLOW_ID).to_dict()
```

Any callflow action can be returned with the same `data` fields it takes in a callflow.
`CallflowBuilder` builds trees the session methods do not cover; the module index is in
`docs/fonouc/CALLFLOW_MODULES.md` in the repo.

## Rules Your App Must Follow

| Rule | Why |
| --- | --- |
| Answer HTTP `200` with `Content-Type: application/json` | The body is validated as a callflow |
| Return `{}` to continue, never an empty body | An empty body stops the call |
| Answer within `req_timeout` (default 5000 ms) | The call is waiting on you |
| No custom HTTP headers reach you | Authenticate with a token in the `voice_url` query string, or put a proxy in front |
| Prefer `method: post` | With `get` every field goes into the URL, and large variable sets exceed URL limits |
| If your app cannot be reached, the call follows the Pivot action's own children | Give the Pivot action a fallback child in the callflow |

## Mid-Call Control with KAPI (Platform-Side Apps Only)

The pivot response decides the call once. To act on a call later (hang up, blind transfer, join a
conference, start a recording), the SDK builds KAPI commands that your app publishes to RabbitMQ:

```
cmd = session.make_hangup(routing_key="ecallmgr@node", cause="NORMAL_CLEARING")
## publish cmd.body to cmd.target.exchange / cmd.target.routing_key
```

| Builder | KAPI schema |
| --- | --- |
| `make_hangup(routing_key=, cause=)` | `kapi.dialplan.hangup` |
| `make_blind_transfer(to_ext, routing_key=, leg=)` | `kapi.dialplan.transfer` |
| `make_join_conference(conf_id, routing_key=, ...)` | `kapi.dialplan.conference` |
| `make_start_record(media_name, routing_key=)` | `kapi.dialplan.record_call` |

This needs access to the platform's RabbitMQ, so it applies only to apps that run on the platform
network. The routing key is the ecallmgr queue bound to `call.usurp_control.<call id>` on the
`callevt` exchange (`transport.resolve_routing_key` looks it up). On a bridged call the leg used to
find the routing key can differ from the `Call-ID` in the command body: read
`docs/fonouc/KAPI_OVERVIEW.md` in the repo before moving legs.

## Building a Pivot App with an AI Coding Agent

Give the agent the repository and this read order (also in the repo's `docs/README.md`):

1. `README.md`
2. `docs/library/GETTING_STARTED.md`
3. `docs/library/API_REFERENCE.md`
4. `docs/fonouc/PIVOT_REQUEST_FIELDS.md` and `docs/fonouc/PIVOT_RESPONSE.md`
5. `docs/fonouc/CALLFLOW_MODULES.md` and `docs/reference/schemas/` for any action you return
6. `examples/sample_fastapi_pivot_app.py` as the starting app

A prompt that works:

```
Clone git@ssh.bitbucket.org:fonouc/fonouc_callcontrol.git and read docs/README.md in its read order.
Starting from examples/sample_fastapi_pivot_app.py, build a pivot app that <your call logic>.
Use only CallSession / CallflowBuilder to build responses, return {} when nothing should change,
keep everything in the project .venv, and add pytest cases next to tests/ for each branch.
```

Then run the noop check above against your new app, wire a test callflow to it, and place a call.

## Configuration

| Source | Used for |
| --- | --- |
| `.env` (sample apps) | Listen host and port, `APP_NAME`, `APP_VERSION`, optional REST and AMQP values |
| JSON file: `FONOUC_CALLCONTROL_CONFIG` or `/usr/local/fonouc/etc/fonouc_callcontrol.json` | Production apps: `amqp`, `app_name`, `app_version`, REST API keys (see `config/fonouc_callcontrol.json.sample`) |

Optional extras install into the project venv only:

```
./scripts/setup_venv.sh crossbar,transport,examples,dev
.venv/bin/pytest
```
