Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions .claude/skills/phonecheck/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ skill asks what to test, sets it up, runs, reports and puts things back.
or `printf 'header = "Authorization: Bearer %s"\n' "$TELNYX_PERSON_API_KEY" | curl -sS -K - …`.
Pipe every reply through `jq` and keep only the fields named here.
- **Voice URLs: classify, never print.** A vendor's voice URL or connection setting can embed a
password: an attached router number's Twilio voice URL holds the Stream SIP trunk's. Never
print a voice URL; keep one only after the credential check in "Voice URLs" below passes.
password: the voice URL of a router number attached before the router's call webhook existed
holds the Stream SIP trunk's. Never print a voice URL; keep one only after the credential check in "Voice URLs" below passes.
- **Encode numbers.** A `+` in a query must be encoded: `curl -G --data-urlencode 'PhoneNumber=+15550100002'`,
and the same for Telnyx `filter[…]` keys. In a router path it stays as is.
- **Ask with AskUserQuestion,** one step at a time, defaults first. Accept several answers at once.
Expand Down Expand Up @@ -128,12 +128,14 @@ to its database (migrations, and the router's own background work).
2. **Env names** (only the chosen vendors' matter):

```bash
bash -c 'set -a; . <env file>; set +a; for k in STREAM_API_KEY STREAM_API_SECRET ROUTER_POSTGRES_DSN ROUTER_DEV_KEK TWILIO_PERSON_ACCOUNT_SID TWILIO_PERSON_AUTH_TOKEN TELNYX_PERSON_API_KEY TELNYX_PERSON_ACCOUNT_SID TELNYX_PERSON_CONNECTION_ID TWILIO_ACCOUNT_SID TWILIO_AUTH_TOKEN TELNYX_API_KEY TELNYX_CONNECTION_ID TELNYX_PUBLIC_KEY; do [ -n "${!k}" ] && echo "ok $k" || echo "MISSING $k"; done'
bash -c 'set -a; . <env file>; set +a; for k in STREAM_API_KEY STREAM_API_SECRET ROUTER_POSTGRES_DSN ROUTER_DEV_KEK TWILIO_PERSON_ACCOUNT_SID TWILIO_PERSON_AUTH_TOKEN TELNYX_PERSON_API_KEY TELNYX_PERSON_ACCOUNT_SID TELNYX_PERSON_CONNECTION_ID TWILIO_ACCOUNT_SID TWILIO_AUTH_TOKEN TELNYX_API_KEY TELNYX_CONNECTION_ID TELNYX_PUBLIC_KEY TWILIO_WEBHOOK_AUTH_TOKEN; do [ -n "${!k}" ] && echo "ok $k" || echo "MISSING $k"; done'
```

Remote needs only the Stream keys and the person's. Local also needs `ROUTER_POSTGRES_DSN`
(the `call_sites` row), the router's vendor keys, and `ROUTER_DEV_KEK` to attach a Telnyx
number. The `*_PERSON_*` account may be the router's (`TWILIO_PERSON_ACCOUNT_SID=$TWILIO_ACCOUNT_SID`
or Twilio number. Attaching a Twilio number also needs `TWILIO_WEBHOOK_AUTH_TOKEN` and the
router started with `ROUTER_PUBLIC_URL=<tunnel URL>`: the number's voice URL is the router's
Comment thread
kanat marked this conversation as resolved.
Resolved
`/v1/phone/hooks/twilio` there. The `*_PERSON_*` account may be the router's (`TWILIO_PERSON_ACCOUNT_SID=$TWILIO_ACCOUNT_SID`
in `.env`, after the router's lines). See README §3.
3. **Local router.** Check nothing listens: `lsof -nP -iTCP:8080 -sTCP:LISTEN`; if something
does, show it and ask. Starting it runs migrations, binds :8080 and may start background
Expand Down Expand Up @@ -204,7 +206,8 @@ Show ONE summary and wait for an explicit yes:
webhook), say plainly: while the test runs, real calls to that number reach the test script
instead; it is put back afterwards. Recommend a number used only for tests. Never print the URL;
- cleanup: what goes back (hooks, voice URLs, `connection_id`s, tunnel, router), what stays (the
bought numbers, until you say otherwise), and that release is asked per number afterwards.
bought numbers, until you say otherwise; a kept Twilio router number points at the closed
tunnel), and that release is asked per number afterwards.

No yes: nothing is bought or changed; stop the router this skill started and end.

Expand All @@ -220,7 +223,11 @@ In this order, each change into the state file:
(the call hook only: a text to the agent's channel is not answered by this local router)
(`-remove <stale URL>` only if approved; `-app <id>` only for a router in app mode). A local
Telnyx router's own TeXML app (`TELNYX_CONNECTION_ID`) needs its voice URL on the tunnel; the
human sets that.
human sets that. Before any Twilio router number is attached, restart the local router with
`ROUTER_PUBLIC_URL=<tunnel URL>` added to its start command (section 1, step 3), as the
Twilio number's voice URL is built from it: `kill` the router's id from the state file, wait
until nothing listens on :8080, start it again, and write the new process id to the state
file. The env file's `ROUTER_PUBLIC_URL` is a local address Twilio cannot reach.
2. **Router numbers.** Buy (see the table); add to "bought this run". For inbound, after its
outbound runs: attach.
3. **Person numbers.** Twilio `POST …/IncomingPhoneNumbers.json` with `PhoneNumber=<n>` (keep
Expand Down Expand Up @@ -278,7 +285,9 @@ it lists, in reverse:
release (see the table; it also unwires an attached one), while the router still runs.
Person number: Twilio `DELETE …/IncomingPhoneNumbers/<sid>.json`, Telnyx
`DELETE /v2/phone_numbers/<id>`. Say what is kept and what stays attached: an attached
number blocks inbound tests on other numbers.
number blocks inbound tests on other numbers. A kept Twilio router number keeps its voice
URL on the closed tunnel: its calls fail until the router is reachable there again, so say
so.
4. Stop any phonecheck run left (`pkill -INT -x phonecheck`), then the tunnel, then the router:
`kill <id>` for each process id in the state file, then their background tasks. Check that
nothing is left: `pgrep -x phonecheck`, `pgrep -f 'cloudflared tunnel --url http://localhost:8080'`
Expand Down
2 changes: 1 addition & 1 deletion acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ the other commands that read them there.
| `TWILIO_ACCOUNT_SID` | Twilio credentials, for buying and operating numbers. A call to `/v1/phone/hooks/twilio` that names another account is hung up |
| `TWILIO_AUTH_TOKEN` | Twilio credentials. With `TWILIO_API_KEY_SID` set, that key's secret |
| `TWILIO_API_KEY_SID` | Optional Twilio API key (SK...). Requests are signed with it instead of the account SID |
| `TWILIO_WEBHOOK_AUTH_TOKEN` | Auth Token of the Twilio account whose webhooks the router checks (`X-Twilio-Signature`). It only checks signatures: those of the Monitor alerts and usage-trigger callbacks sent to `/v1/phone/hooks/twilio/events`, and the calls sent to `/v1/phone/hooks/twilio`, each signed over `ROUTER_PUBLIC_URL` and the path. Without it, or without `ROUTER_PUBLIC_URL`, both routes answer 404. A call is answered once per `CallSid`, marked in Redis for a week: a copy of it is hung up, unless the first answer did not reach Twilio, and without Redis every call is hung up. A token with whitespace in it stops the router at start |
| `TWILIO_WEBHOOK_AUTH_TOKEN` | Auth Token of the Twilio account whose webhooks the router checks (`X-Twilio-Signature`). It only checks signatures: those of the Monitor alerts and usage-trigger callbacks sent to `/v1/phone/hooks/twilio/events`, and the calls sent to `/v1/phone/hooks/twilio`, each signed over `ROUTER_PUBLIC_URL` and the path. Without it, or without `ROUTER_PUBLIC_URL`, both routes answer 404 and a Twilio number cannot be attached: an attached number's voice URL is `ROUTER_PUBLIC_URL` and `/v1/phone/hooks/twilio`, by POST. `ROUTER_PUBLIC_URL` must be an https address for a Twilio attach, so a local router on `http://localhost` refuses it. A call is answered once per `CallSid`, marked in Redis for a week: a copy of it is hung up, unless the first answer did not reach Twilio, and without Redis every call is hung up. A token with whitespace in it stops the router at start |
| `TELNYX_API_KEY` | Telnyx credentials |
| `TELNYX_CONNECTION_ID` | The Telnyx TeXML application numbers and calls are on. Calls to the webhook from any other application are hung up |
| `TELNYX_PUBLIC_KEY` | Telnyx's public key (base64), to check the calls it sends to `/v1/phone/hooks/telnyx` and the account events it sends to `/v1/phone/hooks/telnyx/events`. Without it Telnyx numbers are not answered and the events route answers 404. Telnyx numbers also need a key encryption keyring (`ROUTER_DEV_KEK` locally, `ROUTER_AUTH_KEK_V<n>_WRAPPED` hosted): without one they cannot be attached |
Expand Down
7 changes: 5 additions & 2 deletions acceleration/evals/telephony-latency/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ off the network, before any jitter buffer, so a handset would add its own on top
## Running it

Credentials come from the environment: `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`,
`TWILIO_WEBHOOK_AUTH_TOKEN` (the account's Auth Token, which signs Twilio's webhooks),
`TELNYX_API_KEY`, `TELNYX_CONNECTION_ID` and `TELNYX_CALL_CONTROL_ID`. Optionally `IPINFO_TOKEN`
for the report's address lookups.

Expand All @@ -33,7 +34,7 @@ cd acceleration
go run ./evals/telephony-latency provision # buys 2 numbers per vendor per city: 40 numbers
```

Then on a VM in each GCP region, with UDP 5060 and 20000-20999 open to the carriers:
Then on a VM in each GCP region, with UDP 5060 and 20000-20999 and TCP 8080 open to the carriers:

```bash
go run ./evals/telephony-latency run -host <vm public ip> -region us-east1
Expand All @@ -53,7 +54,9 @@ for a smoke test, `-scope all` to call between cities as well, `-parallel` for c

### Carrier setup

- **Twilio** needs nothing: the bench sets each number's voice URL to TwiML that dials it.
- **Twilio** needs nothing more: the bench points each number's voice URL at the call webhook it
serves on `-hook-listen` (`http://<host>:8080/v1/phone/hooks/twilio`), which answers each signed
call with TwiML that dials the bench.
- **Telnyx** routes inbound calls through `TELNYX_CONNECTION_ID`. Make it an FQDN/IP connection
pointing at the bench's address, with the destination number in E.164. Each region's bench
needs its own connection, or the connection repointed before each run.
Expand Down
53 changes: 53 additions & 0 deletions acceleration/evals/telephony-latency/hook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"log/slog"
"net/http"

"github.com/GetStream/Vision-Agents/acceleration/internal/phone"
"github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio"
"github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig"
)

// hookLimit caps the form Twilio posts to the hook, which is a few hundred bytes
// (https://www.twilio.com/docs/voice/twiml, "Twilio's request to your application").
const hookLimit = 64 << 10

// TwilioHook answers Twilio's call webhook as the router does, with the bench as the trunk: a
// Twilio number is pointed at the webhook, so the bench serves it to be told where calls go.
type TwilioHook struct {
// Token is the Auth Token Twilio signs the webhook with.
Token string
// PublicURL is where Twilio reaches the bench's webhook, which the signature is over.
PublicURL string
// Bridges is where each number's calls go, by number.
Bridges map[string]phone.Bridge
Log *slog.Logger
}

// ServeHTTP answers a signed call to one of the bench's numbers with TwiML dialing the bench,
// and any other signed call with a hangup.
func (h *TwilioHook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, hookLimit)
if err := r.ParseForm(); err != nil {
http.Error(w, "that is not a form", http.StatusBadRequest)
return
}
signature := r.Header.Get(twiliosig.SignatureHeader)
if err := twiliosig.Verify(h.Token, h.PublicURL+phone.TwilioCallHookPath, r.PostForm, signature); err != nil {
http.Error(w, "that is not a call from Twilio", http.StatusUnauthorized)
return
}

plan := twilio.RenderHangup()
if bridge, ok := h.Bridges[r.PostForm.Get("To")]; ok {
dial, err := twilio.RenderInbound(bridge)
if err != nil {
h.Log.Error("telephony-latency: render a twilio call", "to", r.PostForm.Get("To"), "error", err)
} else {
plan = dial
}
}
w.Header().Set("Content-Type", plan.ContentType)
_, _ = w.Write(plan.Body)
}
160 changes: 160 additions & 0 deletions acceleration/evals/telephony-latency/hook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package main

import (
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"strings"
"testing"

"github.com/stretchr/testify/suite"

"github.com/GetStream/Vision-Agents/acceleration/internal/phone"
"github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig"
)

type TwilioHookSuite struct {
suite.Suite
hook *TwilioHook
server *httptest.Server
}

func TestTwilioHookSuite(t *testing.T) {
suite.Run(t, new(TwilioHookSuite))
}

func (s *TwilioHookSuite) SetupTest() {
s.hook = &TwilioHook{
Token: "bench-token", PublicURL: "http://203.0.113.7:8080",
Bridges: map[string]phone.Bridge{"+15125550100": {URI: "sip:+15125550100@203.0.113.7:5060"}},
Log: slog.New(slog.DiscardHandler),
}
s.server = httptest.NewServer(s.hook)
}

func (s *TwilioHookSuite) TearDownTest() { s.server.Close() }

// post sends body to the hook with signature, as Twilio does, and answers the status and body.
func (s *TwilioHookSuite) post(body, signature string) (int, string) {
request, err := http.NewRequest(http.MethodPost, s.server.URL+phone.TwilioCallHookPath, strings.NewReader(body))
s.Require().NoError(err)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.Header.Set(twiliosig.SignatureHeader, signature)
response, err := http.DefaultClient.Do(request)
s.Require().NoError(err)
defer response.Body.Close()
answered, err := io.ReadAll(response.Body)
s.Require().NoError(err)
return response.StatusCode, string(answered)
}

// signed is the signature Twilio sends with form, over the bench's public URL and the path.
func (s *TwilioHookSuite) signed(form url.Values) string {
return twiliosig.Sign(s.hook.Token, s.hook.PublicURL+phone.TwilioCallHookPath, form)
}

func (s *TwilioHookSuite) TestASignedCallToABenchNumberDialsTheBench() {
form := url.Values{"To": {"+15125550100"}, "Direction": {"inbound"}}

status, body := s.post(form.Encode(), s.signed(form))

s.Equal(http.StatusOK, status)
s.Contains(body, "<Dial><Sip>sip:+15125550100@203.0.113.7:5060</Sip></Dial>")
}

func (s *TwilioHookSuite) TestASignedCallToAnotherNumberIsHungUp() {
form := url.Values{"To": {"+15125550199"}, "Direction": {"inbound"}}

status, body := s.post(form.Encode(), s.signed(form))

s.Equal(http.StatusOK, status)
s.Contains(body, "<Hangup/>")
s.NotContains(body, "<Dial>")
}

// A number whose bridge cannot be dialled is hung up rather than answered with an empty plan.
func (s *TwilioHookSuite) TestASignedCallToANumberWithABadBridgeIsHungUp() {
s.hook.Bridges["+15125550100"] = phone.Bridge{URI: "https://203.0.113.7/not-sip"}
form := url.Values{"To": {"+15125550100"}, "Direction": {"inbound"}}

status, body := s.post(form.Encode(), s.signed(form))

s.Equal(http.StatusOK, status)
s.Contains(body, "<Hangup/>")
}

func (s *TwilioHookSuite) TestACallNotSignedOverTheBenchsURLIsRefused() {
form := url.Values{"To": {"+15125550100"}}
for name, signature := range map[string]string{
"unsigned": "",
"another token": twiliosig.Sign("another-token", s.hook.PublicURL+phone.TwilioCallHookPath, form),
"another URL": twiliosig.Sign(s.hook.Token, "http://198.51.100.1:8080"+phone.TwilioCallHookPath, form),
} {
s.Run(name, func() {
status, body := s.post(form.Encode(), signature)

s.Equal(http.StatusUnauthorized, status)
s.NotContains(body, "sip:")
})
}
}

func (s *TwilioHookSuite) TestABodyThatIsNoFormOrTooLargeIsRefused() {
for name, body := range map[string]string{
"no form": "To=%zz",
"too large": "To=" + strings.Repeat("1", 64<<10),
} {
s.Run(name, func() {
status, _ := s.post(body, "")

s.Equal(http.StatusBadRequest, status)
})
}
}

// The bench serves the hook at the URL it returns until it is closed, and only with a token.
func (s *TwilioHookSuite) TestTheBenchServesTheHookWhereItSaysUntilClosed() {
bridges := map[string]phone.Bridge{"+15125550100": {URI: "sip:+15125550100@127.0.0.1:5060"}}
host := netip.MustParseAddr("127.0.0.1")
log := slog.New(slog.DiscardHandler)
s.T().Setenv(twiliosig.AuthTokenEnvVar, "")
_, _, err := serveTwilioHook("127.0.0.1:0", host, bridges, log)
s.ErrorContains(err, twiliosig.AuthTokenEnvVar)

s.T().Setenv(twiliosig.AuthTokenEnvVar, "bench-token")
_, _, err = serveTwilioHook("127.0.0.1", host, bridges, log)
s.ErrorContains(err, "missing port", "an address with no port")
taken, err := net.Listen("tcp", "127.0.0.1:0")
s.Require().NoError(err)
defer taken.Close()
_, _, err = serveTwilioHook(taken.Addr().String(), host, bridges, log)
s.ErrorContains(err, "serve twilio's call webhook")

free, err := net.Listen("tcp", "127.0.0.1:0")
s.Require().NoError(err)
address := free.Addr().String()
s.Require().NoError(free.Close())
publicURL, server, err := serveTwilioHook(address, host, bridges, log)
s.Require().NoError(err)
s.Equal("http://"+address, publicURL)

form := url.Values{"To": {"+15125550100"}}
request, err := http.NewRequest(http.MethodPost, publicURL+phone.TwilioCallHookPath, strings.NewReader(form.Encode()))
s.Require().NoError(err)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.Header.Set(twiliosig.SignatureHeader, twiliosig.Sign("bench-token", publicURL+phone.TwilioCallHookPath, form))
response, err := http.DefaultClient.Do(request)
s.Require().NoError(err)
body, err := io.ReadAll(response.Body)
s.Require().NoError(err)
s.Require().NoError(response.Body.Close())
s.Contains(string(body), "<Sip>sip:+15125550100@127.0.0.1:5060</Sip>")

s.Require().NoError(server.Close())
_, err = http.Post(publicURL+phone.TwilioCallHookPath, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
s.Error(err, "nothing serves the hook once it is closed")
}
Loading
Loading